Skip to main content

lichtung_plot/canvas/
placement.rs

1//! Canonical payload/footprint owners, with a derived slot-to-anchor lookup.
2
3use crate::builder::PlotDescription;
4use crate::{
5    data::RawKey,
6    errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
7    kind::ExactFamily,
8    layout::{PanelStep, TextPanel},
9    Error, Plot,
10};
11use std::sync::Arc;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub(super) struct Footprint {
15    pub row: usize,
16    pub column: usize,
17    pub row_span: usize,
18    pub column_span: usize,
19}
20#[derive(Clone)]
21pub(super) enum Payload {
22    Plot(PlotDescription),
23    Text(TextPanel),
24    Fixed(crate::composition::FixedPanel),
25    Reserved((f64, f64)),
26    Vacant,
27}
28
29/// Content for a Canvas panel. Native Plots, text, fixed local images and
30/// frozen outputs can be passed directly.
31#[derive(Clone)]
32pub struct PanelContent(pub(super) Payload);
33
34impl<K: ExactFamily> From<Plot<K>> for PanelContent {
35    fn from(plot: Plot<K>) -> Self {
36        Self(Payload::Plot(plot.into_description()))
37    }
38}
39
40impl<K: ExactFamily> From<&Plot<K>> for PanelContent {
41    fn from(plot: &Plot<K>) -> Self {
42        Self(Payload::Plot(plot.description().clone()))
43    }
44}
45
46impl From<TextPanel> for PanelContent {
47    fn from(text: TextPanel) -> Self {
48        Self(Payload::Text(text))
49    }
50}
51
52impl From<&TextPanel> for PanelContent {
53    fn from(text: &TextPanel) -> Self {
54        Self(Payload::Text(text.clone()))
55    }
56}
57
58impl TryFrom<crate::composition::PanelImage> for PanelContent {
59    type Error = Error;
60    fn try_from(value: crate::composition::PanelImage) -> crate::Result<Self> {
61        Ok(Self(Payload::Fixed(value.admit()?)))
62    }
63}
64
65macro_rules! fixed_content {
66    ($($ty:ty),+ $(,)?) => {$(
67        impl TryFrom<$ty> for PanelContent {
68            type Error = Error;
69            fn try_from(value: $ty) -> crate::Result<Self> {
70                crate::composition::PanelImage::from(value).try_into()
71            }
72        }
73    )+};
74}
75fixed_content!(
76    &str,
77    String,
78    &std::path::Path,
79    std::path::PathBuf,
80    &std::path::PathBuf,
81    crate::composition::ImageAsset,
82    &crate::composition::ImageAsset,
83    crate::Output,
84    &crate::Output,
85    crate::composition::Composite,
86    &crate::composition::Composite,
87);
88
89/// A deliberate empty slot with a minimum allocated size in CSS pixels.
90#[derive(Debug, Clone, Copy, PartialEq)]
91pub struct ReservedSlot {
92    minimum: (f64, f64),
93    row_span: usize,
94    column_span: usize,
95}
96
97impl ReservedSlot {
98    /// Reserve one cell with finite nonnegative minimum dimensions.
99    pub fn at_least(min_width: f64, min_height: f64) -> crate::Result<Self> {
100        if ![min_width, min_height]
101            .into_iter()
102            .all(|value| value.is_finite() && value >= 0.0 && value <= f64::from(u32::MAX))
103        {
104            return Err(Error::Data(
105                "reserved slot minimum dimensions must be finite nonnegative layout lengths".into(),
106            ));
107        }
108        Ok(Self {
109            minimum: (min_width, min_height),
110            row_span: 1,
111            column_span: 1,
112        })
113    }
114
115    /// Set the positive row and column spans of this reservation.
116    pub fn span(mut self, rows: usize, columns: usize) -> crate::Result<Self> {
117        if rows == 0 || columns == 0 {
118            return Err(Error::Data("reserved slot spans must be positive".into()));
119        }
120        self.row_span = rows;
121        self.column_span = columns;
122        Ok(self)
123    }
124}
125
126impl TryFrom<(f64, f64)> for ReservedSlot {
127    type Error = Error;
128
129    fn try_from((width, height): (f64, f64)) -> crate::Result<Self> {
130        Self::at_least(width, height)
131    }
132}
133
134/// One declared grid anchor, including its complete footprint and current state.
135#[derive(Debug, Clone, PartialEq)]
136pub struct PanelSlot {
137    name: Option<Arc<str>>,
138    footprint: Footprint,
139    reservation: Option<(f64, f64)>,
140    filled: bool,
141}
142
143impl PanelSlot {
144    /// The optional authored name, unique within this grid.
145    pub fn name(&self) -> Option<&str> {
146        self.name.as_deref()
147    }
148    /// Zero-based anchor row.
149    pub const fn row(&self) -> usize {
150        self.footprint.row
151    }
152    /// Zero-based anchor column.
153    pub const fn column(&self) -> usize {
154        self.footprint.column
155    }
156    /// Number of rows owned by this anchor.
157    pub const fn row_span(&self) -> usize {
158        self.footprint.row_span
159    }
160    /// Number of columns owned by this anchor.
161    pub const fn column_span(&self) -> usize {
162        self.footprint.column_span
163    }
164    /// Whether the slot owns actual content.
165    pub const fn is_filled(&self) -> bool {
166        self.filled
167    }
168    /// Authored minimum width and height of a deliberate empty reservation.
169    pub const fn reservation(&self) -> Option<(f64, f64)> {
170        self.reservation
171    }
172}
173
174#[derive(Clone)]
175struct Owner {
176    identity: crate::data::InstanceId,
177    footprint: Footprint,
178    payload: Payload,
179    content_origin: Option<crate::data::DataSourceInfo>,
180    name: Option<Arc<str>>,
181}
182
183impl Owner {
184    fn slot(&self) -> PanelSlot {
185        PanelSlot {
186            name: self.name.clone(),
187            footprint: self.footprint,
188            filled: !matches!(self.payload, Payload::Reserved(_) | Payload::Vacant),
189            reservation: match self.payload {
190                Payload::Reserved(minimum) => Some(minimum),
191                _ => None,
192            },
193        }
194    }
195}
196
197#[derive(Clone, Copy)]
198enum Overlap {
199    Reject,
200    Replace,
201}
202
203#[derive(Clone)]
204pub(super) struct Placements {
205    rows: usize,
206    columns: usize,
207    owners: Vec<Option<Owner>>,
208    occupancy: Vec<Option<usize>>,
209}
210impl Placements {
211    pub fn new(rows: usize, columns: usize) -> Result<Self, Error> {
212        let count = rows
213            .checked_mul(columns)
214            .ok_or_else(|| Error::Data("Canvas topology overflows storage".into()))?;
215        Ok(Self {
216            rows,
217            columns,
218            owners: crate::data::source::collect_source((0..count).map(|_| Ok(None)))?,
219            occupancy: crate::data::source::collect_source((0..count).map(|_| Ok(None)))?,
220        })
221    }
222    pub fn len(&self) -> usize {
223        self.owners.len()
224    }
225    pub fn shape(&self) -> (usize, usize) {
226        (self.rows, self.columns)
227    }
228    pub fn plot(&self, index: usize) -> Option<&PlotDescription> {
229        match &self.owners.get(index)?.as_ref()?.payload {
230            Payload::Plot(plot) => Some(plot),
231            _ => None,
232        }
233    }
234    pub fn plot_identity(&self, index: usize) -> Option<&crate::data::InstanceId> {
235        let owner = self.owners.get(index)?.as_ref()?;
236        matches!(owner.payload, Payload::Plot(_)).then_some(&owner.identity)
237    }
238    pub fn text(&self, index: usize) -> Option<&TextPanel> {
239        match &self.owners.get(index)?.as_ref()?.payload {
240            Payload::Text(text) => Some(text),
241            _ => None,
242        }
243    }
244    pub fn fixed(&self, index: usize) -> Option<&crate::composition::FixedPanel> {
245        match &self.owners.get(index)?.as_ref()?.payload {
246            Payload::Fixed(image) => Some(image),
247            _ => None,
248        }
249    }
250    pub(super) fn payload(&self, index: usize) -> Option<&Payload> {
251        self.owners.get(index)?.as_ref().map(|owner| &owner.payload)
252    }
253
254    pub(super) fn payload_mut(&mut self, index: usize) -> Option<&mut Payload> {
255        self.owners
256            .get_mut(index)?
257            .as_mut()
258            .map(|owner| &mut owner.payload)
259    }
260
261    pub(super) fn content_origin(&self, index: usize) -> Option<&crate::data::DataSourceInfo> {
262        self.owners.get(index)?.as_ref()?.content_origin.as_ref()
263    }
264    pub(super) fn set_content_origin(
265        &mut self,
266        index: usize,
267        origin: Option<crate::data::DataSourceInfo>,
268    ) {
269        self.owners[index]
270            .as_mut()
271            .expect("actual content owner")
272            .content_origin = origin;
273    }
274
275    pub(super) fn vacant(&self, index: usize) -> bool {
276        matches!(self.payload(index), Some(Payload::Vacant))
277    }
278
279    pub fn reservation(&self, index: usize) -> Option<(f64, f64)> {
280        match self.owners.get(index)?.as_ref()?.payload {
281            Payload::Reserved(minimum) => Some(minimum),
282            _ => None,
283        }
284    }
285    pub fn plots(&self) -> impl ExactSizeIterator<Item = Option<&PlotDescription>> {
286        (0..self.len()).map(|index| self.plot(index))
287    }
288    pub fn texts(&self) -> impl ExactSizeIterator<Item = Option<&TextPanel>> {
289        (0..self.len()).map(|index| self.text(index))
290    }
291    pub fn footprint(&self, index: usize) -> Option<Footprint> {
292        self.owners
293            .get(index)?
294            .as_ref()
295            .map(|owner| owner.footprint)
296    }
297    pub fn anchor(&self, row: usize, column: usize) -> Option<usize> {
298        if row >= self.rows || column >= self.columns {
299            return None;
300        }
301        self.occupancy[row * self.columns + column]
302    }
303
304    pub fn slots(&self) -> impl Iterator<Item = PanelSlot> + '_ {
305        self.owners.iter().flatten().map(Owner::slot)
306    }
307
308    pub fn slot(&self, index: usize) -> Option<PanelSlot> {
309        self.owners.get(index)?.as_ref().map(Owner::slot)
310    }
311
312    fn find_named(&self, name: &str) -> Option<usize> {
313        self.owners
314            .iter()
315            .position(|owner| owner.as_ref().and_then(|owner| owner.name.as_deref()) == Some(name))
316    }
317
318    pub fn named_index(&self, name: &str) -> crate::Result<usize> {
319        self.find_named(name).ok_or_else(|| {
320            Error::Data(
321                Diagnostic::new(
322                    DiagnosticKind::UnknownKey {
323                        key: Some(RawKey::from(name)),
324                    },
325                    format!("Canvas has no panel named {name:?}"),
326                )
327                .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
328            )
329        })
330    }
331
332    pub fn anchor_index(&self, row: usize, column: usize) -> crate::Result<usize> {
333        let index = self.anchor(row, column).ok_or_else(|| {
334            Error::Data(format!("Canvas has no declared slot at ({row}, {column})").into())
335        })?;
336        let owner = self.owners[index].as_ref().expect("occupied anchor");
337        if (owner.footprint.row, owner.footprint.column) != (row, column) {
338            return Err(Error::Data(
339                format!(
340                    "Canvas cell ({row}, {column}) is covered by anchor ({}, {})",
341                    owner.footprint.row, owner.footprint.column
342                )
343                .into(),
344            ));
345        }
346        Ok(index)
347    }
348
349    pub fn resolve_step(&self, step: &PanelStep) -> crate::Result<usize> {
350        match step {
351            PanelStep::Cell(row, column) => self.anchor_index(*row, *column),
352            PanelStep::Named(name) => self.named_index(name),
353            _ => Err(Error::Data(
354                format!("expected a direct Canvas grid anchor, got {step:?}").into(),
355            )),
356        }
357    }
358
359    pub fn name(&mut self, row: usize, column: usize, name: &str) -> crate::Result<()> {
360        let index = self.anchor_index(row, column)?;
361        if name.is_empty() {
362            return Err(Error::Data("Canvas panel name must not be empty".into()));
363        }
364        if let Some(other) = self.find_named(name) {
365            if other != index {
366                let footprint = self.footprint(other).expect("named owner");
367                return Err(Error::Data(
368                    format!(
369                        "Canvas panel name {name:?} already belongs to anchor ({}, {})",
370                        footprint.row, footprint.column
371                    )
372                    .into(),
373                ));
374            }
375        }
376        self.owners[index].as_mut().expect("declared anchor").name =
377            Some(Arc::from(crate::data::source::copy_source_string(name)?));
378        Ok(())
379    }
380
381    pub fn reserve(&mut self, row: usize, column: usize, slot: ReservedSlot) -> crate::Result<()> {
382        self.insert(
383            Footprint {
384                row,
385                column,
386                row_span: slot.row_span,
387                column_span: slot.column_span,
388            },
389            Payload::Reserved(slot.minimum),
390        )
391    }
392
393    pub fn insert(&mut self, footprint: Footprint, payload: Payload) -> Result<(), Error> {
394        self.place(footprint, payload, Overlap::Reject)
395    }
396
397    pub fn replace(&mut self, footprint: Footprint, payload: Payload) -> Result<(), Error> {
398        self.place(footprint, payload, Overlap::Replace)
399    }
400
401    fn place(
402        &mut self,
403        mut footprint: Footprint,
404        payload: Payload,
405        overlap: Overlap,
406    ) -> Result<(), Error> {
407        // Filling an empty declared anchor consumes its whole slot; an explicit
408        // different spanning rectangle still follows the normal overlap rules.
409        let vacant = if matches!(overlap, Overlap::Reject)
410            && !matches!(payload, Payload::Reserved(_) | Payload::Vacant)
411        {
412            self.anchor(footprint.row, footprint.column)
413                .filter(|&index| {
414                    (self.reservation(index).is_some() || self.vacant(index))
415                        && self.footprint(index).is_some_and(|existing| {
416                            (existing.row, existing.column) == (footprint.row, footprint.column)
417                                && (existing == footprint
418                                    || (footprint.row_span, footprint.column_span) == (1, 1))
419                        })
420                })
421        } else {
422            None
423        };
424        if let Some(index) = vacant {
425            footprint = self.footprint(index).expect("empty declared anchor");
426        }
427        let row_end = footprint
428            .row
429            .checked_add(footprint.row_span)
430            .filter(|&end| footprint.row_span > 0 && end <= self.rows);
431        let column_end = footprint
432            .column
433            .checked_add(footprint.column_span)
434            .filter(|&end| footprint.column_span > 0 && end <= self.columns);
435        let (Some(row_end), Some(column_end)) = (row_end, column_end) else {
436            return Err(Error::Data(
437                "Canvas footprint is empty, overflowing or outside its declared grid".into(),
438            ));
439        };
440        if matches!(overlap, Overlap::Reject) {
441            for row in footprint.row..row_end {
442                for column in footprint.column..column_end {
443                    let occupied = self.occupancy[row * self.columns + column];
444                    if let Some(owner) = occupied.filter(|owner| Some(*owner) != vacant) {
445                        let footprint = self.footprint(owner).expect("occupied anchor");
446                        return Err(Error::Data(
447                            format!(
448                                "Canvas footprint overlaps occupied cell ({row}, {column}) owned by anchor ({}, {})",
449                                footprint.row, footprint.column
450                            ).into(),
451                        ));
452                    }
453                }
454            }
455        }
456        let anchor = footprint.row * self.columns + footprint.column;
457        let name = self.owners[anchor]
458            .as_ref()
459            .filter(|owner| owner.footprint == footprint)
460            .and_then(|owner| owner.name.clone());
461        // All validation and fallible resources precede mutation. Removing a
462        // whole owner clears repeated occupancy hits without a second index.
463        if let Some(index) = vacant {
464            self.remove(index);
465        } else if matches!(overlap, Overlap::Replace) {
466            for row in footprint.row..row_end {
467                for column in footprint.column..column_end {
468                    if let Some(owner) = self.occupancy[row * self.columns + column] {
469                        self.remove(owner);
470                    }
471                }
472            }
473        }
474        self.owners[anchor] = Some(Owner {
475            identity: crate::data::InstanceId::new(),
476            footprint,
477            payload,
478            content_origin: None,
479            name,
480        });
481        for row in footprint.row..row_end {
482            for column in footprint.column..column_end {
483                self.occupancy[row * self.columns + column] = Some(anchor);
484            }
485        }
486        Ok(())
487    }
488
489    fn remove(&mut self, anchor: usize) {
490        let owner = self.owners[anchor]
491            .take()
492            .expect("occupied slot has an owner");
493        let footprint = owner.footprint;
494        for row in footprint.row..footprint.row + footprint.row_span {
495            for column in footprint.column..footprint.column + footprint.column_span {
496                self.occupancy[row * self.columns + column] = None;
497            }
498        }
499    }
500}