Skip to main content

lichtung_plot/composition/
composite.rs

1//! Final composition keeps the first base and a sequence of independently
2//! prepared placements. All coordinates remain relative to that first base.
3
4use std::path::Path;
5
6use crate::layout::{BoundaryRef, InkExtent, LayoutReport, Rect, RectRef, RootSize};
7use crate::operation::{self, OperationOptions};
8use crate::output::{PngOptions, PngSizing};
9use crate::{Canvas, Error, Output, Plot, Result};
10
11use super::fixed::FixedSource;
12use super::{
13    CompositionSource, ImageAsset, ImageRendering, ObjectFit, ObjectPosition, PlacedContent,
14    Placement,
15};
16
17/// Options for one final composition.
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19pub struct ComposeOptions {
20    /// Enlarge the current viewport only for actual new, visible ink.
21    pub expand_canvas: bool,
22}
23
24/// One completed, immutable composition, retaining its first coordinate frame.
25#[derive(Debug, Clone)]
26pub struct Composite {
27    output: Output,
28}
29
30#[derive(Clone)]
31pub(crate) enum FrozenBase {
32    Native(Output),
33    Image(PlacedContent),
34}
35
36/// A real closed position in the original native serializer.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
38pub(crate) struct PaintCut {
39    pub(crate) buffer: usize,
40    pub(crate) offset: usize,
41}
42
43#[derive(Clone)]
44pub(crate) struct FrozenPlacement {
45    pub(crate) content: PlacedContent,
46    pub(crate) cut: Option<PaintCut>,
47    // Later expansions must not uncover parts clipped by an earlier operation.
48    pub(crate) clip: Rect,
49}
50
51#[derive(Clone)]
52pub(crate) struct FrozenComposition {
53    pub(crate) base: FrozenBase,
54    pub(crate) original: Rect,
55    pub(crate) extent: Rect,
56    pub(crate) placements: Vec<FrozenPlacement>,
57}
58
59impl FrozenComposition {
60    fn new(source: FixedSource) -> Result<Self> {
61        let (base, original) = match source {
62            FixedSource::Frozen(output) => {
63                if let Some(composition) = output.scene().composition() {
64                    return Ok(composition.clone());
65                }
66                let original = Rect::new(0., 0., output.width(), output.height())?;
67                (FrozenBase::Native(output), original)
68            }
69            FixedSource::Image(image) => {
70                let (width, height) = image.intrinsics().complete().ok_or_else(|| {
71                    Error::Data("a flat base needs a definite intrinsic CSS viewport".into())
72                })?;
73                let original = Rect::new(0., 0., width, height)?;
74                let item = PlacedContent::boxed(
75                    FixedSource::Image(image),
76                    original,
77                    ObjectFit::Fill,
78                    ObjectPosition::top_left(),
79                    ImageRendering::Auto,
80                )?;
81                item.prepare()?;
82                (FrozenBase::Image(item), original)
83            }
84        };
85        Ok(Self {
86            base,
87            original,
88            extent: original,
89            placements: Vec::new(),
90        })
91    }
92
93    pub(crate) fn report(&self) -> Option<&LayoutReport> {
94        match &self.base {
95            FrozenBase::Native(output) => output.layout_report().ok(),
96            FrozenBase::Image(_) => None,
97        }
98    }
99
100    pub(crate) fn rect(&self, reference: &RectRef) -> Result<Rect> {
101        if *reference == RectRef::viewport() {
102            return Ok(self.original);
103        }
104        self.report()
105            .ok_or_else(|| Error::Data("flat image base has no native layout rectangles".into()))?
106            .rect(reference)
107    }
108
109    fn boundary(&self, boundary: &BoundaryRef) -> Result<PaintCut> {
110        let report = self
111            .report()
112            .ok_or_else(|| Error::Data("flat image base has no native paint boundaries".into()))?;
113        if !report.boundaries().contains(boundary) {
114            return Err(Error::Data(
115                "paint boundary does not identify an actual unique adjacent pair in the base"
116                    .into(),
117            ));
118        }
119        let batch = if let Some(ahead) = boundary.ahead() {
120            report
121                .paint_order()
122                .iter()
123                .find(|batch| batch.reference() == ahead)
124        } else {
125            report
126                .paint_order()
127                .iter()
128                .find(|batch| Some(batch.reference()) == boundary.behind())
129        }
130        .ok_or_else(|| Error::Render("accepted paint boundary has no captured batch".into()))?;
131        Ok(PaintCut {
132            buffer: batch.buffer,
133            offset: if boundary.ahead().is_some() {
134                batch.range.start
135            } else {
136                batch.range.end
137            },
138        })
139    }
140
141    fn add(
142        &mut self,
143        items: impl IntoIterator<Item = Placement>,
144        expand: bool,
145        parent_theme: Option<&crate::Theme>,
146    ) -> Result<()> {
147        let first = self.placements.len();
148        let mut extent = self.extent;
149        let mut unresolved = Vec::new();
150        for (index, item) in items.into_iter().enumerate() {
151            operation::checkpoint()?;
152            let prepared = (|| {
153                let cut = item
154                    .boundary()
155                    .map(|boundary| self.boundary(boundary))
156                    .transpose()?;
157                let content = item.prepare(|reference| self.rect(reference), parent_theme)?;
158                if expand {
159                    if let Some(possible) = content.object.intersection(content.frame) {
160                        if !extent.contains(possible) {
161                            match content.exact_ink(possible)? {
162                                InkExtent::Empty => {}
163                                InkExtent::Bounds(bounds) => extent = extent.union(bounds),
164                                InkExtent::Unknown => {
165                                    crate::data::source::reserve_source(&mut unresolved, 1)?;
166                                    unresolved.push((index, possible));
167                                }
168                            }
169                        }
170                    }
171                }
172                Ok(FrozenPlacement {
173                    content,
174                    cut,
175                    clip: self.extent,
176                })
177            })()
178            .map_err(|error: Error| error.with_prefix(&format!("placement {index}")))?;
179            crate::data::source::reserve_source(&mut self.placements, 1)?;
180            self.placements.push(prepared);
181        }
182        if let Some((index, _)) = unresolved
183            .into_iter()
184            .find(|(_, possible)| !extent.contains(*possible))
185        {
186            return Err(Error::Render(format!("placement {index}: cannot determine actual visible ink required to expand the canvas for this source").into()));
187        }
188        // Validate the resulting actual viewport before making it observable.
189        RootSize::new(extent.width(), extent.height()).dimensions()?;
190        self.extent = extent;
191        for item in &mut self.placements[first..] {
192            item.clip = extent;
193        }
194        Ok(())
195    }
196
197    pub(crate) fn size(&self) -> RootSize {
198        if self.extent == self.original {
199            if let FrozenBase::Native(output) = &self.base {
200                return output.scene().size();
201            }
202        }
203        RootSize::new(self.extent.width(), self.extent.height())
204    }
205
206    pub(crate) fn is_flat_base(&self) -> bool {
207        matches!(self.base, FrozenBase::Image(_))
208    }
209
210    pub(crate) fn origin(&self) -> (f64, f64) {
211        let positive = |value: f64| if value == 0. { 0. } else { -value };
212        (positive(self.extent.left()), positive(self.extent.top()))
213    }
214
215    pub(crate) fn validate_preserve_text(&self) -> Result<()> {
216        match &self.base {
217            FrozenBase::Native(output) => output.scene().validate_preserve_text()?,
218            FrozenBase::Image(content) => content.validate_preserve_text()?,
219        }
220        for item in &self.placements {
221            item.content.validate_preserve_text()?;
222        }
223        Ok(())
224    }
225
226    pub(crate) fn font_substitutions(&self, substitutions: &mut Vec<super::ImageFontSubstitution>) {
227        match &self.base {
228            FrozenBase::Native(output) => output
229                .scene()
230                .collect_image_font_substitutions(substitutions),
231            FrozenBase::Image(content) => content.font_substitutions(substitutions),
232        }
233        for item in &self.placements {
234            item.content.font_substitutions(substitutions);
235        }
236    }
237
238    pub(crate) fn exact_ink(&self, clip: Rect) -> Result<InkExtent> {
239        let clip = Rect::new(
240            clip.left() + self.extent.left(),
241            clip.top() + self.extent.top(),
242            clip.width(),
243            clip.height(),
244        )?;
245        let mut ink = match &self.base {
246            FrozenBase::Native(output) => output.scene().exact_ink(clip)?,
247            FrozenBase::Image(content) => content.exact_ink(clip)?,
248        };
249        let mut unresolved = if ink == InkExtent::Unknown {
250            ink = InkExtent::Empty;
251            self.original.intersection(clip)
252        } else {
253            None
254        };
255        for item in &self.placements {
256            operation::checkpoint()?;
257            let Some(local) = clip.intersection(item.clip) else {
258                continue;
259            };
260            let Some(possible) = item
261                .content
262                .frame
263                .intersection(item.content.object)
264                .and_then(|possible| possible.intersection(local))
265            else {
266                continue;
267            };
268            if let InkExtent::Bounds(known) = ink {
269                // Any possible contribution entirely inside the proven ink
270                // bounds cannot change the extrema of their union.
271                if known.contains(possible) {
272                    continue;
273                }
274            }
275            match item.content.exact_ink(local)? {
276                InkExtent::Unknown => {
277                    unresolved = Some(unresolved.map_or(possible, |prior| prior.union(possible)));
278                }
279                proven => ink = ink.union(proven),
280            }
281        }
282        if let Some(possible) = unresolved {
283            if !matches!(ink, InkExtent::Bounds(bounds) if bounds.contains(possible)) {
284                return Ok(InkExtent::Unknown);
285            }
286        }
287        match ink {
288            InkExtent::Bounds(rect) => Ok(InkExtent::Bounds(Rect::new(
289                rect.left() - self.extent.left(),
290                rect.top() - self.extent.top(),
291                rect.width(),
292                rect.height(),
293            )?)),
294            other => Ok(other),
295        }
296    }
297}
298
299impl Composite {
300    /// Compose ordered items on a base, with its original viewport unchanged.
301    pub fn new(
302        base: impl TryInto<CompositionSource, Error: Into<Error>>,
303        items: impl IntoIterator<Item = Placement>,
304    ) -> Result<Self> {
305        Self::with_options(base, items, ComposeOptions::default())
306    }
307
308    /// Compose using the requested viewport policy.
309    pub fn with_options(
310        base: impl TryInto<CompositionSource, Error: Into<Error>>,
311        items: impl IntoIterator<Item = Placement>,
312        options: ComposeOptions,
313    ) -> Result<Self> {
314        Self::with_operation(base, items, options, &OperationOptions::default())
315    }
316
317    /// Compose one independent request, retaining cancellation through capture
318    /// and all new item preparations.
319    pub fn with_operation(
320        base: impl TryInto<CompositionSource, Error: Into<Error>>,
321        items: impl IntoIterator<Item = Placement>,
322        options: ComposeOptions,
323        operation_options: &OperationOptions,
324    ) -> Result<Self> {
325        operation::run(operation_options, || {
326            let base = base.try_into().map_err(Into::into)?;
327            Self::prepare(base, items, options, None)
328        })
329    }
330
331    pub(crate) fn prepare(
332        base: CompositionSource,
333        items: impl IntoIterator<Item = Placement>,
334        options: ComposeOptions,
335        parent_theme: Option<&crate::Theme>,
336    ) -> Result<Self> {
337        let base = base.prepare(None, None)?;
338        Ok(Self {
339            output: Output::new(prepare_scene(base, items, options, parent_theme)?),
340        })
341    }
342
343    /// Put one independently prepared item into an actual reserved slot.
344    pub fn in_slot(
345        base: impl TryInto<CompositionSource, Error: Into<Error>>,
346        item: impl TryInto<CompositionSource, Error: Into<Error>>,
347        row: usize,
348        column: usize,
349    ) -> Result<Self> {
350        Self::new(base, [Placement::in_slot(item, row, column)?])
351    }
352
353    /// Borrow the complete frozen output, without preparing or converting it.
354    pub fn output(&self) -> &Output {
355        &self.output
356    }
357
358    /// Final CSS width.
359    pub fn width(&self) -> f64 {
360        self.output.width()
361    }
362    /// Final CSS height.
363    pub fn height(&self) -> f64 {
364        self.output.height()
365    }
366
367    /// The original native base's accepted report, if it has one.
368    pub fn layout_report(&self) -> Result<&LayoutReport> {
369        self.output.layout_report()
370    }
371
372    fn plan(&self) -> &FrozenComposition {
373        self.output.scene().composition().expect("composite scene")
374    }
375
376    /// Position of the original base's top-left in this completed output.
377    pub fn base_origin_in_output(&self) -> (f64, f64) {
378        self.plan().origin()
379    }
380
381    /// The chain's default PNG sampling when no sizing was requested.
382    pub fn default_png_sizing(&self) -> PngSizing {
383        if self.plan().is_flat_base() {
384            PngSizing::Source
385        } else {
386            PngOptions::default().sizing
387        }
388    }
389
390    /// Publish the completed outlined SVG.
391    pub fn svg(&self, path: impl AsRef<Path>) -> Result<Output> {
392        self.output.svg(path)
393    }
394    /// Publish outlined SVG using this call's operation options.
395    pub fn svg_with_operation(
396        &self,
397        path: impl AsRef<Path>,
398        options: &OperationOptions,
399    ) -> Result<Output> {
400        self.output.svg_with_operation(path, options)
401    }
402    /// Publish with actual retained text.
403    pub fn svg_preserve_text(&self, path: impl AsRef<Path>) -> Result<Output> {
404        self.output.svg_preserve_text(path)
405    }
406    /// Publish retained text using this call's operation options.
407    pub fn svg_preserve_text_with_operation(
408        &self,
409        path: impl AsRef<Path>,
410        options: &OperationOptions,
411    ) -> Result<Output> {
412        self.output.svg_preserve_text_with_operation(path, options)
413    }
414    /// Publish with the chain's default PNG sampling (1× for a flat base,
415    /// 300 DPI for a native base).
416    pub fn png(&self, path: impl AsRef<Path>) -> Result<Output> {
417        self.png_with_operation(path, &OperationOptions::default())
418    }
419    /// Publish the default PNG with operation options.
420    pub fn png_with_operation(
421        &self,
422        path: impl AsRef<Path>,
423        options: &OperationOptions,
424    ) -> Result<Output> {
425        self.save_with_operation(path, crate::output::Format::png(), options)
426    }
427    /// Publish an explicit PNG sampling/encoding request.
428    pub fn png_with_options(&self, path: impl AsRef<Path>, options: PngOptions) -> Result<Output> {
429        self.output.png_with_options(path, options)
430    }
431    /// Publish explicit device sizing with this call's operation options.
432    pub fn png_with_options_with_operation(
433        &self,
434        path: impl AsRef<Path>,
435        options: PngOptions,
436        operation: &OperationOptions,
437    ) -> Result<Output> {
438        self.output
439            .png_with_options_with_operation(path, options, operation)
440    }
441    /// Publish a source-sized PNG.
442    pub fn png_preview(&self, path: impl AsRef<Path>) -> Result<Output> {
443        self.output.png_preview(path)
444    }
445    /// Publish a source-sized PNG using this call's operation options.
446    pub fn png_preview_with_operation(
447        &self,
448        path: impl AsRef<Path>,
449        options: &OperationOptions,
450    ) -> Result<Output> {
451        self.output.png_preview_with_operation(path, options)
452    }
453}
454
455fn prepare_scene(
456    base: FixedSource,
457    items: impl IntoIterator<Item = Placement>,
458    options: ComposeOptions,
459    parent: Option<&crate::Theme>,
460) -> Result<crate::scene::RenderedScene> {
461    operation::phase(crate::errors::OperationPhase::Prepare)?;
462    let mut plan = FrozenComposition::new(base)?;
463    plan.add(items, options.expand_canvas, parent)?;
464    let size = plan.size();
465    let report = plan.report().cloned();
466    operation::phase(crate::errors::OperationPhase::Freeze)?;
467    let finalized = crate::render::svg_backend::FinalizedSvgOutput::from_composition(size, plan)?;
468    let mut scene = crate::scene::RenderedScene::new(size, Some(finalized))?;
469    if let Some(report) = report {
470        scene = scene.with_layout_report(report);
471    }
472    operation::phase(crate::errors::OperationPhase::Publish)?;
473    Ok(scene)
474}
475
476pub(crate) fn append_slot_placements(
477    base: Output,
478    items: &[Placement],
479    parent: &crate::Theme,
480) -> Result<crate::scene::RenderedScene> {
481    prepare_scene(
482        FixedSource::Frozen(base),
483        items.iter().cloned(),
484        ComposeOptions::default(),
485        Some(parent),
486    )
487}
488
489impl From<Composite> for CompositionSource {
490    fn from(composite: Composite) -> Self {
491        composite.output.into()
492    }
493}
494impl From<&Composite> for CompositionSource {
495    fn from(composite: &Composite) -> Self {
496        composite.output().into()
497    }
498}
499
500/// Compose items on a base, using the same operation as the receiver method.
501pub fn compose(
502    base: impl TryInto<CompositionSource, Error: Into<Error>>,
503    items: impl IntoIterator<Item = Placement>,
504) -> Result<Composite> {
505    Composite::new(base, items)
506}
507
508macro_rules! compose_methods {
509    () => {
510        /// Compose independently prepared items on this base.
511        pub fn compose(&self, items: impl IntoIterator<Item = Placement>) -> Result<Composite> {
512            Composite::new(self, items)
513        }
514        /// Compose using an explicit viewport policy.
515        pub fn compose_with_options(
516            &self,
517            items: impl IntoIterator<Item = Placement>,
518            options: ComposeOptions,
519        ) -> Result<Composite> {
520            Composite::with_options(self, items, options)
521        }
522        /// Compose with this call's cancellation and viewport policy.
523        pub fn compose_with_operation(
524            &self,
525            items: impl IntoIterator<Item = Placement>,
526            options: ComposeOptions,
527            operation: &OperationOptions,
528        ) -> Result<Composite> {
529            Composite::with_operation(self, items, options, operation)
530        }
531    };
532}
533impl<K: crate::kind::Marker> Plot<K> {
534    compose_methods!();
535}
536impl Canvas {
537    compose_methods!();
538}
539impl crate::recipe::RecipeFigure {
540    compose_methods!();
541}
542impl Output {
543    compose_methods!();
544}
545impl ImageAsset {
546    compose_methods!();
547}
548impl Composite {
549    compose_methods!();
550}