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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Final composition keeps the first base and a sequence of independently
//! prepared placements. All coordinates remain relative to that first base.

use std::path::Path;

use crate::layout::{BoundaryRef, InkExtent, LayoutReport, Rect, RectRef, RootSize};
use crate::operation::{self, OperationOptions};
use crate::output::{PngOptions, PngSizing};
use crate::{Canvas, Error, Output, Plot, Result};

use super::fixed::FixedSource;
use super::{
    CompositionSource, ImageAsset, ImageRendering, ObjectFit, ObjectPosition, PlacedContent,
    Placement,
};

/// Options for one final composition.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ComposeOptions {
    /// Enlarge the current viewport only for actual new, visible ink.
    pub expand_canvas: bool,
}

/// One completed, immutable composition, retaining its first coordinate frame.
#[derive(Debug, Clone)]
pub struct Composite {
    output: Output,
}

#[derive(Clone)]
pub(crate) enum FrozenBase {
    Native(Output),
    Image(PlacedContent),
}

/// A real closed position in the original native serializer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct PaintCut {
    pub(crate) buffer: usize,
    pub(crate) offset: usize,
}

#[derive(Clone)]
pub(crate) struct FrozenPlacement {
    pub(crate) content: PlacedContent,
    pub(crate) cut: Option<PaintCut>,
    // Later expansions must not uncover parts clipped by an earlier operation.
    pub(crate) clip: Rect,
}

#[derive(Clone)]
pub(crate) struct FrozenComposition {
    pub(crate) base: FrozenBase,
    pub(crate) original: Rect,
    pub(crate) extent: Rect,
    pub(crate) placements: Vec<FrozenPlacement>,
}

impl FrozenComposition {
    fn new(source: FixedSource) -> Result<Self> {
        let (base, original) = match source {
            FixedSource::Frozen(output) => {
                if let Some(composition) = output.scene().composition() {
                    return Ok(composition.clone());
                }
                let original = Rect::new(0., 0., output.width(), output.height())?;
                (FrozenBase::Native(output), original)
            }
            FixedSource::Image(image) => {
                let (width, height) = image.intrinsics().complete().ok_or_else(|| {
                    Error::Data("a flat base needs a definite intrinsic CSS viewport".into())
                })?;
                let original = Rect::new(0., 0., width, height)?;
                let item = PlacedContent::boxed(
                    FixedSource::Image(image),
                    original,
                    ObjectFit::Fill,
                    ObjectPosition::top_left(),
                    ImageRendering::Auto,
                )?;
                item.prepare()?;
                (FrozenBase::Image(item), original)
            }
        };
        Ok(Self {
            base,
            original,
            extent: original,
            placements: Vec::new(),
        })
    }

    pub(crate) fn report(&self) -> Option<&LayoutReport> {
        match &self.base {
            FrozenBase::Native(output) => output.layout_report().ok(),
            FrozenBase::Image(_) => None,
        }
    }

    pub(crate) fn rect(&self, reference: &RectRef) -> Result<Rect> {
        if *reference == RectRef::viewport() {
            return Ok(self.original);
        }
        self.report()
            .ok_or_else(|| Error::Data("flat image base has no native layout rectangles".into()))?
            .rect(reference)
    }

    fn boundary(&self, boundary: &BoundaryRef) -> Result<PaintCut> {
        let report = self
            .report()
            .ok_or_else(|| Error::Data("flat image base has no native paint boundaries".into()))?;
        if !report.boundaries().contains(boundary) {
            return Err(Error::Data(
                "paint boundary does not identify an actual unique adjacent pair in the base"
                    .into(),
            ));
        }
        let batch = if let Some(ahead) = boundary.ahead() {
            report
                .paint_order()
                .iter()
                .find(|batch| batch.reference() == ahead)
        } else {
            report
                .paint_order()
                .iter()
                .find(|batch| Some(batch.reference()) == boundary.behind())
        }
        .ok_or_else(|| Error::Render("accepted paint boundary has no captured batch".into()))?;
        Ok(PaintCut {
            buffer: batch.buffer,
            offset: if boundary.ahead().is_some() {
                batch.range.start
            } else {
                batch.range.end
            },
        })
    }

    fn add(
        &mut self,
        items: impl IntoIterator<Item = Placement>,
        expand: bool,
        parent_theme: Option<&crate::Theme>,
    ) -> Result<()> {
        let first = self.placements.len();
        let mut extent = self.extent;
        let mut unresolved = Vec::new();
        for (index, item) in items.into_iter().enumerate() {
            operation::checkpoint()?;
            let prepared = (|| {
                let cut = item
                    .boundary()
                    .map(|boundary| self.boundary(boundary))
                    .transpose()?;
                let content = item.prepare(|reference| self.rect(reference), parent_theme)?;
                if expand {
                    if let Some(possible) = content.object.intersection(content.frame) {
                        if !extent.contains(possible) {
                            match content.exact_ink(possible)? {
                                InkExtent::Empty => {}
                                InkExtent::Bounds(bounds) => extent = extent.union(bounds),
                                InkExtent::Unknown => {
                                    crate::data::source::reserve_source(&mut unresolved, 1)?;
                                    unresolved.push((index, possible));
                                }
                            }
                        }
                    }
                }
                Ok(FrozenPlacement {
                    content,
                    cut,
                    clip: self.extent,
                })
            })()
            .map_err(|error: Error| error.with_prefix(&format!("placement {index}")))?;
            crate::data::source::reserve_source(&mut self.placements, 1)?;
            self.placements.push(prepared);
        }
        if let Some((index, _)) = unresolved
            .into_iter()
            .find(|(_, possible)| !extent.contains(*possible))
        {
            return Err(Error::Render(format!("placement {index}: cannot determine actual visible ink required to expand the canvas for this source").into()));
        }
        // Validate the resulting actual viewport before making it observable.
        RootSize::new(extent.width(), extent.height()).dimensions()?;
        self.extent = extent;
        for item in &mut self.placements[first..] {
            item.clip = extent;
        }
        Ok(())
    }

    pub(crate) fn size(&self) -> RootSize {
        if self.extent == self.original {
            if let FrozenBase::Native(output) = &self.base {
                return output.scene().size();
            }
        }
        RootSize::new(self.extent.width(), self.extent.height())
    }

    pub(crate) fn is_flat_base(&self) -> bool {
        matches!(self.base, FrozenBase::Image(_))
    }

    pub(crate) fn origin(&self) -> (f64, f64) {
        let positive = |value: f64| if value == 0. { 0. } else { -value };
        (positive(self.extent.left()), positive(self.extent.top()))
    }

    pub(crate) fn validate_preserve_text(&self) -> Result<()> {
        match &self.base {
            FrozenBase::Native(output) => output.scene().validate_preserve_text()?,
            FrozenBase::Image(content) => content.validate_preserve_text()?,
        }
        for item in &self.placements {
            item.content.validate_preserve_text()?;
        }
        Ok(())
    }

    pub(crate) fn font_substitutions(&self, substitutions: &mut Vec<super::ImageFontSubstitution>) {
        match &self.base {
            FrozenBase::Native(output) => output
                .scene()
                .collect_image_font_substitutions(substitutions),
            FrozenBase::Image(content) => content.font_substitutions(substitutions),
        }
        for item in &self.placements {
            item.content.font_substitutions(substitutions);
        }
    }

    pub(crate) fn exact_ink(&self, clip: Rect) -> Result<InkExtent> {
        let clip = Rect::new(
            clip.left() + self.extent.left(),
            clip.top() + self.extent.top(),
            clip.width(),
            clip.height(),
        )?;
        let mut ink = match &self.base {
            FrozenBase::Native(output) => output.scene().exact_ink(clip)?,
            FrozenBase::Image(content) => content.exact_ink(clip)?,
        };
        let mut unresolved = if ink == InkExtent::Unknown {
            ink = InkExtent::Empty;
            self.original.intersection(clip)
        } else {
            None
        };
        for item in &self.placements {
            operation::checkpoint()?;
            let Some(local) = clip.intersection(item.clip) else {
                continue;
            };
            let Some(possible) = item
                .content
                .frame
                .intersection(item.content.object)
                .and_then(|possible| possible.intersection(local))
            else {
                continue;
            };
            if let InkExtent::Bounds(known) = ink {
                // Any possible contribution entirely inside the proven ink
                // bounds cannot change the extrema of their union.
                if known.contains(possible) {
                    continue;
                }
            }
            match item.content.exact_ink(local)? {
                InkExtent::Unknown => {
                    unresolved = Some(unresolved.map_or(possible, |prior| prior.union(possible)));
                }
                proven => ink = ink.union(proven),
            }
        }
        if let Some(possible) = unresolved {
            if !matches!(ink, InkExtent::Bounds(bounds) if bounds.contains(possible)) {
                return Ok(InkExtent::Unknown);
            }
        }
        match ink {
            InkExtent::Bounds(rect) => Ok(InkExtent::Bounds(Rect::new(
                rect.left() - self.extent.left(),
                rect.top() - self.extent.top(),
                rect.width(),
                rect.height(),
            )?)),
            other => Ok(other),
        }
    }
}

impl Composite {
    /// Compose ordered items on a base, with its original viewport unchanged.
    pub fn new(
        base: impl TryInto<CompositionSource, Error: Into<Error>>,
        items: impl IntoIterator<Item = Placement>,
    ) -> Result<Self> {
        Self::with_options(base, items, ComposeOptions::default())
    }

    /// Compose using the requested viewport policy.
    pub fn with_options(
        base: impl TryInto<CompositionSource, Error: Into<Error>>,
        items: impl IntoIterator<Item = Placement>,
        options: ComposeOptions,
    ) -> Result<Self> {
        Self::with_operation(base, items, options, &OperationOptions::default())
    }

    /// Compose one independent request, retaining cancellation through capture
    /// and all new item preparations.
    pub fn with_operation(
        base: impl TryInto<CompositionSource, Error: Into<Error>>,
        items: impl IntoIterator<Item = Placement>,
        options: ComposeOptions,
        operation_options: &OperationOptions,
    ) -> Result<Self> {
        operation::run(operation_options, || {
            let base = base.try_into().map_err(Into::into)?;
            Self::prepare(base, items, options, None)
        })
    }

    pub(crate) fn prepare(
        base: CompositionSource,
        items: impl IntoIterator<Item = Placement>,
        options: ComposeOptions,
        parent_theme: Option<&crate::Theme>,
    ) -> Result<Self> {
        let base = base.prepare(None, None)?;
        Ok(Self {
            output: Output::new(prepare_scene(base, items, options, parent_theme)?),
        })
    }

    /// Put one independently prepared item into an actual reserved slot.
    pub fn in_slot(
        base: impl TryInto<CompositionSource, Error: Into<Error>>,
        item: impl TryInto<CompositionSource, Error: Into<Error>>,
        row: usize,
        column: usize,
    ) -> Result<Self> {
        Self::new(base, [Placement::in_slot(item, row, column)?])
    }

    /// Borrow the complete frozen output, without preparing or converting it.
    pub fn output(&self) -> &Output {
        &self.output
    }

    /// Final CSS width.
    pub fn width(&self) -> f64 {
        self.output.width()
    }
    /// Final CSS height.
    pub fn height(&self) -> f64 {
        self.output.height()
    }

    /// The original native base's accepted report, if it has one.
    pub fn layout_report(&self) -> Result<&LayoutReport> {
        self.output.layout_report()
    }

    fn plan(&self) -> &FrozenComposition {
        self.output.scene().composition().expect("composite scene")
    }

    /// Position of the original base's top-left in this completed output.
    pub fn base_origin_in_output(&self) -> (f64, f64) {
        self.plan().origin()
    }

    /// The chain's default PNG sampling when no sizing was requested.
    pub fn default_png_sizing(&self) -> PngSizing {
        if self.plan().is_flat_base() {
            PngSizing::Source
        } else {
            PngOptions::default().sizing
        }
    }

    /// Publish the completed outlined SVG.
    pub fn svg(&self, path: impl AsRef<Path>) -> Result<Output> {
        self.output.svg(path)
    }
    /// Publish outlined SVG using this call's operation options.
    pub fn svg_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Output> {
        self.output.svg_with_operation(path, options)
    }
    /// Publish with actual retained text.
    pub fn svg_preserve_text(&self, path: impl AsRef<Path>) -> Result<Output> {
        self.output.svg_preserve_text(path)
    }
    /// Publish retained text using this call's operation options.
    pub fn svg_preserve_text_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Output> {
        self.output.svg_preserve_text_with_operation(path, options)
    }
    /// Publish with the chain's default PNG sampling (1× for a flat base,
    /// 300 DPI for a native base).
    pub fn png(&self, path: impl AsRef<Path>) -> Result<Output> {
        self.png_with_operation(path, &OperationOptions::default())
    }
    /// Publish the default PNG with operation options.
    pub fn png_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Output> {
        self.save_with_operation(path, crate::output::Format::png(), options)
    }
    /// Publish an explicit PNG sampling/encoding request.
    pub fn png_with_options(&self, path: impl AsRef<Path>, options: PngOptions) -> Result<Output> {
        self.output.png_with_options(path, options)
    }
    /// Publish explicit device sizing with this call's operation options.
    pub fn png_with_options_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: PngOptions,
        operation: &OperationOptions,
    ) -> Result<Output> {
        self.output
            .png_with_options_with_operation(path, options, operation)
    }
    /// Publish a source-sized PNG.
    pub fn png_preview(&self, path: impl AsRef<Path>) -> Result<Output> {
        self.output.png_preview(path)
    }
    /// Publish a source-sized PNG using this call's operation options.
    pub fn png_preview_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Output> {
        self.output.png_preview_with_operation(path, options)
    }
}

fn prepare_scene(
    base: FixedSource,
    items: impl IntoIterator<Item = Placement>,
    options: ComposeOptions,
    parent: Option<&crate::Theme>,
) -> Result<crate::scene::RenderedScene> {
    operation::phase(crate::errors::OperationPhase::Prepare)?;
    let mut plan = FrozenComposition::new(base)?;
    plan.add(items, options.expand_canvas, parent)?;
    let size = plan.size();
    let report = plan.report().cloned();
    operation::phase(crate::errors::OperationPhase::Freeze)?;
    let finalized = crate::render::svg_backend::FinalizedSvgOutput::from_composition(size, plan)?;
    let mut scene = crate::scene::RenderedScene::new(size, Some(finalized))?;
    if let Some(report) = report {
        scene = scene.with_layout_report(report);
    }
    operation::phase(crate::errors::OperationPhase::Publish)?;
    Ok(scene)
}

pub(crate) fn append_slot_placements(
    base: Output,
    items: &[Placement],
    parent: &crate::Theme,
) -> Result<crate::scene::RenderedScene> {
    prepare_scene(
        FixedSource::Frozen(base),
        items.iter().cloned(),
        ComposeOptions::default(),
        Some(parent),
    )
}

impl From<Composite> for CompositionSource {
    fn from(composite: Composite) -> Self {
        composite.output.into()
    }
}
impl From<&Composite> for CompositionSource {
    fn from(composite: &Composite) -> Self {
        composite.output().into()
    }
}

/// Compose items on a base, using the same operation as the receiver method.
pub fn compose(
    base: impl TryInto<CompositionSource, Error: Into<Error>>,
    items: impl IntoIterator<Item = Placement>,
) -> Result<Composite> {
    Composite::new(base, items)
}

macro_rules! compose_methods {
    () => {
        /// Compose independently prepared items on this base.
        pub fn compose(&self, items: impl IntoIterator<Item = Placement>) -> Result<Composite> {
            Composite::new(self, items)
        }
        /// Compose using an explicit viewport policy.
        pub fn compose_with_options(
            &self,
            items: impl IntoIterator<Item = Placement>,
            options: ComposeOptions,
        ) -> Result<Composite> {
            Composite::with_options(self, items, options)
        }
        /// Compose with this call's cancellation and viewport policy.
        pub fn compose_with_operation(
            &self,
            items: impl IntoIterator<Item = Placement>,
            options: ComposeOptions,
            operation: &OperationOptions,
        ) -> Result<Composite> {
            Composite::with_operation(self, items, options, operation)
        }
    };
}
impl<K: crate::kind::Marker> Plot<K> {
    compose_methods!();
}
impl Canvas {
    compose_methods!();
}
impl crate::recipe::RecipeFigure {
    compose_methods!();
}
impl Output {
    compose_methods!();
}
impl ImageAsset {
    compose_methods!();
}
impl Composite {
    compose_methods!();
}