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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! One fixed-source sizing and placement program shared by grid panels and
//! frozen composition. Coordinates here are always CSS pixels, top-down.

use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

use super::asset::{AssetView, Intrinsics};
use super::ImageAsset;
use crate::layout::{Anchor, InkExtent, PositionComponent, Rect};
use crate::{Error, Output, Result};

/// CSS object-fit sizing for a fixed source viewport.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ObjectFit {
    /// Preserve the aspect ratio and fit entirely inside the frame.
    #[default]
    Contain,
    /// Preserve the aspect ratio and cover the frame, clipping the excess.
    Cover,
    /// Fill both frame dimensions independently.
    Fill,
    /// Keep the natural size, clipping against the frame.
    None,
    /// Like contain, without enlarging the natural object.
    ScaleDown,
}

/// CSS object-position: align the rendered object's size within its frame.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ObjectPosition {
    pub(super) x: PositionComponent,
    pub(super) y: PositionComponent,
}

impl ObjectPosition {
    /// Independent horizontal and vertical positions.
    pub const fn new(x: PositionComponent, y: PositionComponent) -> Self {
        Self { x, y }
    }

    const fn aligned(x: f64, y: f64) -> Self {
        Self::new(PositionComponent::aligned(x), PositionComponent::aligned(y))
    }

    /// Center on both axes.
    pub const fn center() -> Self {
        Self::aligned(0.5, 0.5)
    }
    /// Align the left edge, vertically centered.
    pub const fn left() -> Self {
        Self::aligned(0., 0.5)
    }
    /// Align the right edge, vertically centered.
    pub const fn right() -> Self {
        Self::aligned(1., 0.5)
    }
    /// Align the top edge, horizontally centered.
    pub const fn top() -> Self {
        Self::aligned(0.5, 0.)
    }
    /// Align the bottom edge, horizontally centered.
    pub const fn bottom() -> Self {
        Self::aligned(0.5, 1.)
    }
    /// Align the upper left corner.
    pub const fn top_left() -> Self {
        Self::aligned(0., 0.)
    }
    /// Align the upper right corner.
    pub const fn top_right() -> Self {
        Self::aligned(1., 0.)
    }
    /// Align the lower left corner.
    pub const fn bottom_left() -> Self {
        Self::aligned(0., 1.)
    }
    /// Align the lower right corner.
    pub const fn bottom_right() -> Self {
        Self::aligned(1., 1.)
    }

    fn offset(self, spare: (f64, f64)) -> (f64, f64) {
        (self.x.resolve(spare.0), self.y.resolve(spare.1))
    }
}

impl Default for ObjectPosition {
    fn default() -> Self {
        Self::center()
    }
}

/// Sampling policy for image resources. It never changes layout dimensions.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ImageRendering {
    /// Ordinary smooth image sampling.
    #[default]
    Auto,
    /// Preserve hard pixel edges using nearest-neighbor PNG sampling.
    CrispEdges,
}

impl ImageRendering {
    pub(crate) const fn svg(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::CrispEdges => "crisp-edges",
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) enum FixedSource {
    Image(ImageAsset),
    Frozen(Output),
}

impl FixedSource {
    pub(super) fn intrinsics(&self) -> Intrinsics {
        match self {
            Self::Image(asset) => asset.intrinsics(),
            Self::Frozen(output) => Intrinsics::sized(output.width(), output.height()),
        }
    }

    pub(super) fn is_frozen(&self) -> bool {
        matches!(self, Self::Frozen(_))
    }
}

#[derive(Debug, Clone)]
enum PanelSource {
    Path(PathBuf),
    Ready(FixedSource),
}

/// Placement options for an image or an already frozen native output.
/// A path is read when the content is admitted to a Canvas.
#[derive(Debug, Clone)]
#[must_use]
pub struct PanelImage {
    source: PanelSource,
    requested: [Option<f64>; 2],
    fit: ObjectFit,
    position: ObjectPosition,
    rendering: ImageRendering,
}

impl PanelImage {
    /// Describe this placement of a local path, image asset or frozen Output.
    pub fn new(source: impl Into<Self>) -> Self {
        source.into()
    }

    fn from_source(source: PanelSource) -> Self {
        Self {
            source,
            requested: [None; 2],
            fit: ObjectFit::Contain,
            position: ObjectPosition::default(),
            rendering: ImageRendering::Auto,
        }
    }

    /// Specify an exact frame width; infer height from the source ratio.
    pub fn width(mut self, width: f64) -> Self {
        self.requested[0] = Some(width);
        self
    }

    /// Specify an exact frame height; infer width from the source ratio.
    pub fn height(mut self, height: f64) -> Self {
        self.requested[1] = Some(height);
        self
    }

    /// Specify an exact frame in CSS pixels.
    pub fn size(mut self, width: f64, height: f64) -> Self {
        self.requested = [Some(width), Some(height)];
        self
    }

    /// Set the fixed-source fitting policy.
    pub fn fit(mut self, fit: ObjectFit) -> Self {
        self.fit = fit;
        self
    }

    /// Set alignment within the frame.
    pub fn position(mut self, position: ObjectPosition) -> Self {
        self.position = position;
        self
    }

    /// Set image sampling independently of geometry.
    pub fn image_rendering(mut self, rendering: ImageRendering) -> Self {
        self.rendering = rendering;
        self
    }

    pub(crate) fn admit(self) -> Result<FixedPanel> {
        let source = match self.source {
            PanelSource::Path(path) => FixedSource::Image(ImageAsset::read_path(&path)?),
            PanelSource::Ready(source) => source,
        };
        let intrinsic = source.intrinsics();
        let frame = match self.requested {
            [None, None] => None,
            [Some(w), Some(h)] => Some((w, h)),
            [Some(w), None] => Some((w, w / required_ratio(intrinsic)?)),
            [None, Some(h)] => Some((h * required_ratio(intrinsic)?, h)),
        };
        if let Some((w, h)) = frame {
            positive_size((w, h))?;
        }
        Ok(FixedPanel {
            source,
            frame,
            requested: self.requested,
            fit: self.fit,
            position: self.position,
            rendering: self.rendering,
        })
    }
}

impl From<ImageAsset> for PanelImage {
    fn from(asset: ImageAsset) -> Self {
        Self::from_source(PanelSource::Ready(FixedSource::Image(asset)))
    }
}

impl From<&ImageAsset> for PanelImage {
    fn from(asset: &ImageAsset) -> Self {
        Self::from(asset.clone())
    }
}

impl From<Output> for PanelImage {
    fn from(output: Output) -> Self {
        Self::from_source(PanelSource::Ready(FixedSource::Frozen(output)))
    }
}

impl From<&Output> for PanelImage {
    fn from(output: &Output) -> Self {
        Self::from(output.clone())
    }
}

impl From<super::Composite> for PanelImage {
    fn from(value: super::Composite) -> Self {
        Self::from(value.output())
    }
}
impl From<&super::Composite> for PanelImage {
    fn from(value: &super::Composite) -> Self {
        Self::from(value.output())
    }
}

impl From<PathBuf> for PanelImage {
    fn from(path: PathBuf) -> Self {
        Self::from_source(PanelSource::Path(path))
    }
}

impl From<&Path> for PanelImage {
    fn from(path: &Path) -> Self {
        Self::from(path.to_path_buf())
    }
}

impl From<&PathBuf> for PanelImage {
    fn from(path: &PathBuf) -> Self {
        Self::from(path.as_path())
    }
}

impl From<String> for PanelImage {
    fn from(path: String) -> Self {
        Self::from(PathBuf::from(path))
    }
}

impl From<&str> for PanelImage {
    fn from(path: &str) -> Self {
        Self::from(PathBuf::from(path))
    }
}

impl std::str::FromStr for ObjectFit {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self> {
        match value {
            "contain" => Ok(Self::Contain),
            "cover" => Ok(Self::Cover),
            "fill" => Ok(Self::Fill),
            "none" => Ok(Self::None),
            "scale-down" => Ok(Self::ScaleDown),
            _ => Err(Error::Data(format!("unknown object-fit {value:?}").into())),
        }
    }
}

impl std::str::FromStr for ImageRendering {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self> {
        match value {
            "auto" => Ok(Self::Auto),
            "crisp-edges" => Ok(Self::CrispEdges),
            _ => Err(Error::Data(
                format!("unknown image-rendering {value:?}").into(),
            )),
        }
    }
}

impl std::str::FromStr for ObjectPosition {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self> {
        let keyword = value.replace('_', " ");
        let parts: Vec<_> = keyword.split_whitespace().collect();
        let center = PositionComponent::aligned(0.5);
        let horizontal = |value: &str| -> Result<PositionComponent> {
            match value {
                "left" => Ok(PositionComponent::aligned(0.)),
                "right" => Ok(PositionComponent::aligned(1.)),
                "center" => Ok(center),
                _ => parse_position_component(value),
            }
        };
        let vertical = |value: &str| -> Result<PositionComponent> {
            match value {
                "top" => Ok(PositionComponent::aligned(0.)),
                "bottom" => Ok(PositionComponent::aligned(1.)),
                "center" => Ok(center),
                _ => parse_position_component(value),
            }
        };
        match parts.as_slice() {
            ["top" | "bottom"] => Ok(Self::new(center, vertical(parts[0])?)),
            [x] => Ok(Self::new(horizontal(x)?, center)),
            [y @ ("top" | "bottom"), x] | [y @ "center", x @ ("left" | "right")] | [x, y] => {
                Ok(Self::new(horizontal(x)?, vertical(y)?))
            }
            _ => Err(Error::Data(
                format!("unsupported object position {value:?}").into(),
            )),
        }
    }
}

fn parse_position_component(value: &str) -> Result<PositionComponent> {
    let (number, percent) = if let Some(number) = value.strip_suffix('%') {
        (number, true)
    } else if let Some(number) = value.strip_suffix("px") {
        (number, false)
    } else if value == "0" {
        (value, false)
    } else {
        return Err(Error::Data(
            format!("object position needs a keyword, percentage or CSS-pixel value: {value:?}")
                .into(),
        ));
    };
    let number = number
        .parse::<f64>()
        .map_err(|_| Error::Data(format!("invalid object position {value:?}").into()))?;
    if percent {
        PositionComponent::percent(number)
    } else {
        PositionComponent::px(number)
    }
}
fn required_ratio(intrinsic: Intrinsics) -> Result<f64> {
    intrinsic.ratio.ok_or_else(|| {
        Error::Data("image has no intrinsic aspect ratio; specify both dimensions".into())
    })
}

fn positive_size(size: (f64, f64)) -> Result<()> {
    if ![size.0, size.1]
        .into_iter()
        .all(|value| value > 0. && value.is_finite())
    {
        return Err(Error::Data(
            "image frame dimensions must be finite and positive".into(),
        ));
    }
    Ok(())
}

#[derive(Debug, Clone)]
pub(crate) struct FixedPanel {
    pub(super) source: FixedSource,
    frame: Option<(f64, f64)>,
    pub(super) requested: [Option<f64>; 2],
    pub(super) fit: ObjectFit,
    pub(super) position: ObjectPosition,
    pub(super) rendering: ImageRendering,
}

impl FixedPanel {
    pub(crate) fn is_frozen(&self) -> bool {
        self.source.is_frozen()
    }

    pub(crate) fn minimum(&self) -> (f64, f64) {
        self.frame.unwrap_or((1. / 1024., 1. / 1024.))
    }

    pub(crate) fn preferred_width(&self, natural: bool) -> Result<f64> {
        if let Some(frame) = self.frame {
            return Ok(frame.0);
        }
        let intrinsic = self.source.intrinsics();
        if let Some(width) = intrinsic
            .complete()
            .map(|size| size.0)
            .or(intrinsic.size[0])
        {
            return Ok(width);
        }
        if natural {
            return Err(Error::Data(
                "image has no intrinsic CSS width; specify a panel dimension or canvas width"
                    .into(),
            ));
        }
        Ok(self.minimum().0)
    }

    pub(crate) fn preferred_height(&self, width: f64) -> Result<f64> {
        if let Some(frame) = self.frame {
            return Ok(frame.1);
        }
        let intrinsic = self.source.intrinsics();
        intrinsic
            .ratio
            .map(|ratio| width / ratio)
            .or(intrinsic.size[1])
            .ok_or_else(|| {
                Error::Data(
                    "image has no intrinsic height; specify a panel dimension or canvas height"
                        .into(),
                )
            })
    }

    pub(crate) fn place(&self, allocation: Rect) -> Result<PlacedContent> {
        let frame = if let Some((w, h)) = self.frame {
            if w > allocation.width() || h > allocation.height() {
                return Err(Error::Render(
                    "explicit image frame does not fit its allocated panel".into(),
                ));
            }
            Rect::new(
                allocation.left() + (allocation.width() - w) / 2.,
                allocation.top() + (allocation.height() - h) / 2.,
                w,
                h,
            )?
        } else {
            allocation
        };
        PlacedContent::boxed(
            self.source.clone(),
            frame,
            self.fit,
            self.position,
            self.rendering,
        )
    }
}

// CSS Images' default sizing for an object that has a ratio but no absolute
// intrinsic size uses the containing box rather than inventing a natural size.
fn contain(frame: (f64, f64), ratio: f64) -> (f64, f64) {
    let width = frame.0.min(frame.1 * ratio);
    (width, width / ratio)
}

fn object_sizes(
    intrinsic: Intrinsics,
    frame: (f64, f64),
    fit: ObjectFit,
) -> Result<((f64, f64), (f64, f64))> {
    let natural = intrinsic.complete().unwrap_or_else(|| {
        intrinsic.ratio.map_or(
            (
                intrinsic.size[0].unwrap_or(frame.0),
                intrinsic.size[1].unwrap_or(frame.1),
            ),
            |ratio| contain(frame, ratio),
        )
    });
    positive_size(natural)?;
    let ratio = intrinsic.ratio.unwrap_or(natural.0 / natural.1);
    let fit_size = match fit {
        ObjectFit::Contain => contain(frame, ratio),
        ObjectFit::Cover => {
            let width = frame.0.max(frame.1 * ratio);
            (width, width / ratio)
        }
        ObjectFit::Fill => frame,
        ObjectFit::None => natural,
        ObjectFit::ScaleDown => contain((frame.0.min(natural.0), frame.1.min(natural.1)), ratio),
    };
    positive_size(fit_size)?;
    Ok((natural, fit_size))
}

/// The actual measured placement and sealed source view. Native frozen output
/// remains an Output, so it never re-enters scientific layout or font shaping.
#[derive(Debug, Clone)]
pub(crate) struct PlacedContent {
    source: FixedSource,
    pub(crate) frame: Rect,
    pub(crate) object: Rect,
    viewport: (f64, f64),
    pub(crate) rendering: ImageRendering,
    view: Arc<OnceLock<AssetView>>,
}

impl PlacedContent {
    pub(crate) fn at(
        source: FixedSource,
        point: (f64, f64),
        requested: [Option<f64>; 2],
        anchor: Anchor,
        rendering: ImageRendering,
    ) -> Result<Self> {
        let intrinsic = source.intrinsics();
        let missing = || {
            Error::Data("fixed content needs enough dimensions to determine its source viewport; specify a size or use a box".into())
        };
        let size = match requested {
            [Some(w), Some(h)] => (w, h),
            [Some(w), None] => (
                w,
                intrinsic
                    .ratio
                    .map(|ratio| w / ratio)
                    .or(intrinsic.size[1])
                    .ok_or_else(missing)?,
            ),
            [None, Some(h)] => (
                intrinsic
                    .ratio
                    .map(|ratio| h * ratio)
                    .or(intrinsic.size[0])
                    .ok_or_else(missing)?,
                h,
            ),
            [None, None] => intrinsic.complete().ok_or_else(missing)?,
        };
        positive_size(size)?;
        let (viewport, _) = object_sizes(intrinsic, size, ObjectFit::Fill)?;
        let (x, y) = if let Anchor::Local(x, y) = anchor {
            (x * size.0 / viewport.0, y * size.1 / viewport.1)
        } else {
            anchor.point(Rect::new(0., 0., size.0, size.1)?)?
        };
        Self::boxed(
            source,
            Rect::new(point.0 - x, point.1 - y, size.0, size.1)?,
            ObjectFit::Fill,
            ObjectPosition::top_left(),
            rendering,
        )
    }

    pub(crate) fn exact_ink(&self, clip: Rect) -> Result<InkExtent> {
        let Some(clip) = self
            .frame
            .intersection(clip)
            .and_then(|clip| self.object.intersection(clip))
        else {
            return Ok(InkExtent::Empty);
        };
        match &self.source {
            FixedSource::Image(asset) => asset.exact_ink(
                self.viewport,
                self.object,
                clip,
                self.rendering,
                self.view.get(),
            ),
            FixedSource::Frozen(output) => {
                let source = Rect::new(0., 0., output.width(), output.height())?;
                let local_clip = super::ink::map_rect(clip, self.object, source)?;
                super::ink::map_ink(output.scene().exact_ink(local_clip)?, source, self.object)
            }
        }
    }
    pub(crate) fn boxed(
        source: FixedSource,
        frame: Rect,
        fit: ObjectFit,
        position: ObjectPosition,
        rendering: ImageRendering,
    ) -> Result<Self> {
        let frame_size = (frame.width(), frame.height());
        positive_size(frame_size)?;
        let (viewport, size) = object_sizes(source.intrinsics(), frame_size, fit)?;
        let (dx, dy) = position.offset((frame_size.0 - size.0, frame_size.1 - size.1));
        let object = Rect::new(frame.left() + dx, frame.top() + dy, size.0, size.1)?;
        Ok(Self {
            source,
            frame,
            object,
            viewport,
            rendering,
            view: Arc::new(OnceLock::new()),
        })
    }

    pub(crate) fn is_frozen(&self) -> bool {
        self.source.is_frozen()
    }

    pub(crate) fn native_output(&self) -> Option<&Output> {
        match &self.source {
            FixedSource::Frozen(output) => Some(output),
            FixedSource::Image(_) => None,
        }
    }

    pub(crate) fn prepare(&self) -> Result<()> {
        if self.view.get().is_some() {
            return Ok(());
        }
        let FixedSource::Image(asset) = &self.source else {
            return Ok(());
        };
        let view = asset.prepare(self.viewport)?;
        crate::operation::checkpoint()?;
        let _ = self.view.set(view);
        Ok(())
    }

    pub(crate) fn href(&self, outline: bool) -> Result<&str> {
        let view = self
            .view
            .get()
            .ok_or_else(|| Error::Render("fixed image was not prepared by capture".into()))?;
        view.href(outline)
    }

    pub(crate) fn validate_preserve_text(&self) -> Result<()> {
        if let Some(native) = self.native_output() {
            return native.scene().validate_preserve_text();
        }
        if let Some(error) = self
            .view
            .get()
            .and_then(|view| view.preserve_error.as_ref())
        {
            return Err(Error::Render(error.clone()));
        }
        Ok(())
    }

    pub(crate) fn font_substitutions(&self, output: &mut Vec<super::ImageFontSubstitution>) {
        if let Some(native) = self.native_output() {
            native.scene().collect_image_font_substitutions(output);
        } else if let Some(view) = self.view.get() {
            output.extend_from_slice(&view.substitutions);
        }
    }

    pub(crate) fn ink(&self) -> InkExtent {
        if let FixedSource::Image(asset) = &self.source {
            if asset.known_empty() {
                return InkExtent::Empty;
            }
        }
        if let FixedSource::Frozen(output) = &self.source {
            if output.scene().composition().is_none() {
                if let Ok(report) = output.layout_report() {
                    if report.nodes()[0].ink() == InkExtent::Empty {
                        return InkExtent::Empty;
                    }
                }
            }
        }
        self.object
            .intersection(self.frame)
            .map_or(InkExtent::Empty, InkExtent::Bounds)
    }
}