lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Canonical payload/footprint owners, with a derived slot-to-anchor lookup.

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,
}

/// Content for a Canvas panel. Native Plots, text, fixed local images and
/// frozen outputs can be passed directly.
#[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,
);

/// A deliberate empty slot with a minimum allocated size in CSS pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ReservedSlot {
    minimum: (f64, f64),
    row_span: usize,
    column_span: usize,
}

impl ReservedSlot {
    /// Reserve one cell with finite nonnegative minimum dimensions.
    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,
        })
    }

    /// Set the positive row and column spans of this reservation.
    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)
    }
}

/// One declared grid anchor, including its complete footprint and current state.
#[derive(Debug, Clone, PartialEq)]
pub struct PanelSlot {
    name: Option<Arc<str>>,
    footprint: Footprint,
    reservation: Option<(f64, f64)>,
    filled: bool,
}

impl PanelSlot {
    /// The optional authored name, unique within this grid.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }
    /// Zero-based anchor row.
    pub const fn row(&self) -> usize {
        self.footprint.row
    }
    /// Zero-based anchor column.
    pub const fn column(&self) -> usize {
        self.footprint.column
    }
    /// Number of rows owned by this anchor.
    pub const fn row_span(&self) -> usize {
        self.footprint.row_span
    }
    /// Number of columns owned by this anchor.
    pub const fn column_span(&self) -> usize {
        self.footprint.column_span
    }
    /// Whether the slot owns actual content.
    pub const fn is_filled(&self) -> bool {
        self.filled
    }
    /// Authored minimum width and height of a deliberate empty reservation.
    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> {
        // Filling an empty declared anchor consumes its whole slot; an explicit
        // different spanning rectangle still follows the normal overlap rules.
        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());
        // All validation and fallible resources precede mutation. Removing a
        // whole owner clears repeated occupancy hits without a second index.
        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;
            }
        }
    }
}