Skip to main content

lichtung_plot/composition/
fixed.rs

1//! One fixed-source sizing and placement program shared by grid panels and
2//! frozen composition. Coordinates here are always CSS pixels, top-down.
3
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, OnceLock};
6
7use super::asset::{AssetView, Intrinsics};
8use super::ImageAsset;
9use crate::layout::{Anchor, InkExtent, PositionComponent, Rect};
10use crate::{Error, Output, Result};
11
12/// CSS object-fit sizing for a fixed source viewport.
13#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum ObjectFit {
16    /// Preserve the aspect ratio and fit entirely inside the frame.
17    #[default]
18    Contain,
19    /// Preserve the aspect ratio and cover the frame, clipping the excess.
20    Cover,
21    /// Fill both frame dimensions independently.
22    Fill,
23    /// Keep the natural size, clipping against the frame.
24    None,
25    /// Like contain, without enlarging the natural object.
26    ScaleDown,
27}
28
29/// CSS object-position: align the rendered object's size within its frame.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct ObjectPosition {
32    pub(super) x: PositionComponent,
33    pub(super) y: PositionComponent,
34}
35
36impl ObjectPosition {
37    /// Independent horizontal and vertical positions.
38    pub const fn new(x: PositionComponent, y: PositionComponent) -> Self {
39        Self { x, y }
40    }
41
42    const fn aligned(x: f64, y: f64) -> Self {
43        Self::new(PositionComponent::aligned(x), PositionComponent::aligned(y))
44    }
45
46    /// Center on both axes.
47    pub const fn center() -> Self {
48        Self::aligned(0.5, 0.5)
49    }
50    /// Align the left edge, vertically centered.
51    pub const fn left() -> Self {
52        Self::aligned(0., 0.5)
53    }
54    /// Align the right edge, vertically centered.
55    pub const fn right() -> Self {
56        Self::aligned(1., 0.5)
57    }
58    /// Align the top edge, horizontally centered.
59    pub const fn top() -> Self {
60        Self::aligned(0.5, 0.)
61    }
62    /// Align the bottom edge, horizontally centered.
63    pub const fn bottom() -> Self {
64        Self::aligned(0.5, 1.)
65    }
66    /// Align the upper left corner.
67    pub const fn top_left() -> Self {
68        Self::aligned(0., 0.)
69    }
70    /// Align the upper right corner.
71    pub const fn top_right() -> Self {
72        Self::aligned(1., 0.)
73    }
74    /// Align the lower left corner.
75    pub const fn bottom_left() -> Self {
76        Self::aligned(0., 1.)
77    }
78    /// Align the lower right corner.
79    pub const fn bottom_right() -> Self {
80        Self::aligned(1., 1.)
81    }
82
83    fn offset(self, spare: (f64, f64)) -> (f64, f64) {
84        (self.x.resolve(spare.0), self.y.resolve(spare.1))
85    }
86}
87
88impl Default for ObjectPosition {
89    fn default() -> Self {
90        Self::center()
91    }
92}
93
94/// Sampling policy for image resources. It never changes layout dimensions.
95#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum ImageRendering {
98    /// Ordinary smooth image sampling.
99    #[default]
100    Auto,
101    /// Preserve hard pixel edges using nearest-neighbor PNG sampling.
102    CrispEdges,
103}
104
105impl ImageRendering {
106    pub(crate) const fn svg(self) -> &'static str {
107        match self {
108            Self::Auto => "auto",
109            Self::CrispEdges => "crisp-edges",
110        }
111    }
112}
113
114#[derive(Debug, Clone)]
115pub(crate) enum FixedSource {
116    Image(ImageAsset),
117    Frozen(Output),
118}
119
120impl FixedSource {
121    pub(super) fn intrinsics(&self) -> Intrinsics {
122        match self {
123            Self::Image(asset) => asset.intrinsics(),
124            Self::Frozen(output) => Intrinsics::sized(output.width(), output.height()),
125        }
126    }
127
128    pub(super) fn is_frozen(&self) -> bool {
129        matches!(self, Self::Frozen(_))
130    }
131}
132
133#[derive(Debug, Clone)]
134enum PanelSource {
135    Path(PathBuf),
136    Ready(FixedSource),
137}
138
139/// Placement options for an image or an already frozen native output.
140/// A path is read when the content is admitted to a Canvas.
141#[derive(Debug, Clone)]
142#[must_use]
143pub struct PanelImage {
144    source: PanelSource,
145    requested: [Option<f64>; 2],
146    fit: ObjectFit,
147    position: ObjectPosition,
148    rendering: ImageRendering,
149}
150
151impl PanelImage {
152    /// Describe this placement of a local path, image asset or frozen Output.
153    pub fn new(source: impl Into<Self>) -> Self {
154        source.into()
155    }
156
157    fn from_source(source: PanelSource) -> Self {
158        Self {
159            source,
160            requested: [None; 2],
161            fit: ObjectFit::Contain,
162            position: ObjectPosition::default(),
163            rendering: ImageRendering::Auto,
164        }
165    }
166
167    /// Specify an exact frame width; infer height from the source ratio.
168    pub fn width(mut self, width: f64) -> Self {
169        self.requested[0] = Some(width);
170        self
171    }
172
173    /// Specify an exact frame height; infer width from the source ratio.
174    pub fn height(mut self, height: f64) -> Self {
175        self.requested[1] = Some(height);
176        self
177    }
178
179    /// Specify an exact frame in CSS pixels.
180    pub fn size(mut self, width: f64, height: f64) -> Self {
181        self.requested = [Some(width), Some(height)];
182        self
183    }
184
185    /// Set the fixed-source fitting policy.
186    pub fn fit(mut self, fit: ObjectFit) -> Self {
187        self.fit = fit;
188        self
189    }
190
191    /// Set alignment within the frame.
192    pub fn position(mut self, position: ObjectPosition) -> Self {
193        self.position = position;
194        self
195    }
196
197    /// Set image sampling independently of geometry.
198    pub fn image_rendering(mut self, rendering: ImageRendering) -> Self {
199        self.rendering = rendering;
200        self
201    }
202
203    pub(crate) fn admit(self) -> Result<FixedPanel> {
204        let source = match self.source {
205            PanelSource::Path(path) => FixedSource::Image(ImageAsset::read_path(&path)?),
206            PanelSource::Ready(source) => source,
207        };
208        let intrinsic = source.intrinsics();
209        let frame = match self.requested {
210            [None, None] => None,
211            [Some(w), Some(h)] => Some((w, h)),
212            [Some(w), None] => Some((w, w / required_ratio(intrinsic)?)),
213            [None, Some(h)] => Some((h * required_ratio(intrinsic)?, h)),
214        };
215        if let Some((w, h)) = frame {
216            positive_size((w, h))?;
217        }
218        Ok(FixedPanel {
219            source,
220            frame,
221            requested: self.requested,
222            fit: self.fit,
223            position: self.position,
224            rendering: self.rendering,
225        })
226    }
227}
228
229impl From<ImageAsset> for PanelImage {
230    fn from(asset: ImageAsset) -> Self {
231        Self::from_source(PanelSource::Ready(FixedSource::Image(asset)))
232    }
233}
234
235impl From<&ImageAsset> for PanelImage {
236    fn from(asset: &ImageAsset) -> Self {
237        Self::from(asset.clone())
238    }
239}
240
241impl From<Output> for PanelImage {
242    fn from(output: Output) -> Self {
243        Self::from_source(PanelSource::Ready(FixedSource::Frozen(output)))
244    }
245}
246
247impl From<&Output> for PanelImage {
248    fn from(output: &Output) -> Self {
249        Self::from(output.clone())
250    }
251}
252
253impl From<super::Composite> for PanelImage {
254    fn from(value: super::Composite) -> Self {
255        Self::from(value.output())
256    }
257}
258impl From<&super::Composite> for PanelImage {
259    fn from(value: &super::Composite) -> Self {
260        Self::from(value.output())
261    }
262}
263
264impl From<PathBuf> for PanelImage {
265    fn from(path: PathBuf) -> Self {
266        Self::from_source(PanelSource::Path(path))
267    }
268}
269
270impl From<&Path> for PanelImage {
271    fn from(path: &Path) -> Self {
272        Self::from(path.to_path_buf())
273    }
274}
275
276impl From<&PathBuf> for PanelImage {
277    fn from(path: &PathBuf) -> Self {
278        Self::from(path.as_path())
279    }
280}
281
282impl From<String> for PanelImage {
283    fn from(path: String) -> Self {
284        Self::from(PathBuf::from(path))
285    }
286}
287
288impl From<&str> for PanelImage {
289    fn from(path: &str) -> Self {
290        Self::from(PathBuf::from(path))
291    }
292}
293
294impl std::str::FromStr for ObjectFit {
295    type Err = Error;
296    fn from_str(value: &str) -> Result<Self> {
297        match value {
298            "contain" => Ok(Self::Contain),
299            "cover" => Ok(Self::Cover),
300            "fill" => Ok(Self::Fill),
301            "none" => Ok(Self::None),
302            "scale-down" => Ok(Self::ScaleDown),
303            _ => Err(Error::Data(format!("unknown object-fit {value:?}").into())),
304        }
305    }
306}
307
308impl std::str::FromStr for ImageRendering {
309    type Err = Error;
310    fn from_str(value: &str) -> Result<Self> {
311        match value {
312            "auto" => Ok(Self::Auto),
313            "crisp-edges" => Ok(Self::CrispEdges),
314            _ => Err(Error::Data(
315                format!("unknown image-rendering {value:?}").into(),
316            )),
317        }
318    }
319}
320
321impl std::str::FromStr for ObjectPosition {
322    type Err = Error;
323    fn from_str(value: &str) -> Result<Self> {
324        let keyword = value.replace('_', " ");
325        let parts: Vec<_> = keyword.split_whitespace().collect();
326        let center = PositionComponent::aligned(0.5);
327        let horizontal = |value: &str| -> Result<PositionComponent> {
328            match value {
329                "left" => Ok(PositionComponent::aligned(0.)),
330                "right" => Ok(PositionComponent::aligned(1.)),
331                "center" => Ok(center),
332                _ => parse_position_component(value),
333            }
334        };
335        let vertical = |value: &str| -> Result<PositionComponent> {
336            match value {
337                "top" => Ok(PositionComponent::aligned(0.)),
338                "bottom" => Ok(PositionComponent::aligned(1.)),
339                "center" => Ok(center),
340                _ => parse_position_component(value),
341            }
342        };
343        match parts.as_slice() {
344            ["top" | "bottom"] => Ok(Self::new(center, vertical(parts[0])?)),
345            [x] => Ok(Self::new(horizontal(x)?, center)),
346            [y @ ("top" | "bottom"), x] | [y @ "center", x @ ("left" | "right")] | [x, y] => {
347                Ok(Self::new(horizontal(x)?, vertical(y)?))
348            }
349            _ => Err(Error::Data(
350                format!("unsupported object position {value:?}").into(),
351            )),
352        }
353    }
354}
355
356fn parse_position_component(value: &str) -> Result<PositionComponent> {
357    let (number, percent) = if let Some(number) = value.strip_suffix('%') {
358        (number, true)
359    } else if let Some(number) = value.strip_suffix("px") {
360        (number, false)
361    } else if value == "0" {
362        (value, false)
363    } else {
364        return Err(Error::Data(
365            format!("object position needs a keyword, percentage or CSS-pixel value: {value:?}")
366                .into(),
367        ));
368    };
369    let number = number
370        .parse::<f64>()
371        .map_err(|_| Error::Data(format!("invalid object position {value:?}").into()))?;
372    if percent {
373        PositionComponent::percent(number)
374    } else {
375        PositionComponent::px(number)
376    }
377}
378fn required_ratio(intrinsic: Intrinsics) -> Result<f64> {
379    intrinsic.ratio.ok_or_else(|| {
380        Error::Data("image has no intrinsic aspect ratio; specify both dimensions".into())
381    })
382}
383
384fn positive_size(size: (f64, f64)) -> Result<()> {
385    if ![size.0, size.1]
386        .into_iter()
387        .all(|value| value > 0. && value.is_finite())
388    {
389        return Err(Error::Data(
390            "image frame dimensions must be finite and positive".into(),
391        ));
392    }
393    Ok(())
394}
395
396#[derive(Debug, Clone)]
397pub(crate) struct FixedPanel {
398    pub(super) source: FixedSource,
399    frame: Option<(f64, f64)>,
400    pub(super) requested: [Option<f64>; 2],
401    pub(super) fit: ObjectFit,
402    pub(super) position: ObjectPosition,
403    pub(super) rendering: ImageRendering,
404}
405
406impl FixedPanel {
407    pub(crate) fn is_frozen(&self) -> bool {
408        self.source.is_frozen()
409    }
410
411    pub(crate) fn minimum(&self) -> (f64, f64) {
412        self.frame.unwrap_or((1. / 1024., 1. / 1024.))
413    }
414
415    pub(crate) fn preferred_width(&self, natural: bool) -> Result<f64> {
416        if let Some(frame) = self.frame {
417            return Ok(frame.0);
418        }
419        let intrinsic = self.source.intrinsics();
420        if let Some(width) = intrinsic
421            .complete()
422            .map(|size| size.0)
423            .or(intrinsic.size[0])
424        {
425            return Ok(width);
426        }
427        if natural {
428            return Err(Error::Data(
429                "image has no intrinsic CSS width; specify a panel dimension or canvas width"
430                    .into(),
431            ));
432        }
433        Ok(self.minimum().0)
434    }
435
436    pub(crate) fn preferred_height(&self, width: f64) -> Result<f64> {
437        if let Some(frame) = self.frame {
438            return Ok(frame.1);
439        }
440        let intrinsic = self.source.intrinsics();
441        intrinsic
442            .ratio
443            .map(|ratio| width / ratio)
444            .or(intrinsic.size[1])
445            .ok_or_else(|| {
446                Error::Data(
447                    "image has no intrinsic height; specify a panel dimension or canvas height"
448                        .into(),
449                )
450            })
451    }
452
453    pub(crate) fn place(&self, allocation: Rect) -> Result<PlacedContent> {
454        let frame = if let Some((w, h)) = self.frame {
455            if w > allocation.width() || h > allocation.height() {
456                return Err(Error::Render(
457                    "explicit image frame does not fit its allocated panel".into(),
458                ));
459            }
460            Rect::new(
461                allocation.left() + (allocation.width() - w) / 2.,
462                allocation.top() + (allocation.height() - h) / 2.,
463                w,
464                h,
465            )?
466        } else {
467            allocation
468        };
469        PlacedContent::boxed(
470            self.source.clone(),
471            frame,
472            self.fit,
473            self.position,
474            self.rendering,
475        )
476    }
477}
478
479// CSS Images' default sizing for an object that has a ratio but no absolute
480// intrinsic size uses the containing box rather than inventing a natural size.
481fn contain(frame: (f64, f64), ratio: f64) -> (f64, f64) {
482    let width = frame.0.min(frame.1 * ratio);
483    (width, width / ratio)
484}
485
486fn object_sizes(
487    intrinsic: Intrinsics,
488    frame: (f64, f64),
489    fit: ObjectFit,
490) -> Result<((f64, f64), (f64, f64))> {
491    let natural = intrinsic.complete().unwrap_or_else(|| {
492        intrinsic.ratio.map_or(
493            (
494                intrinsic.size[0].unwrap_or(frame.0),
495                intrinsic.size[1].unwrap_or(frame.1),
496            ),
497            |ratio| contain(frame, ratio),
498        )
499    });
500    positive_size(natural)?;
501    let ratio = intrinsic.ratio.unwrap_or(natural.0 / natural.1);
502    let fit_size = match fit {
503        ObjectFit::Contain => contain(frame, ratio),
504        ObjectFit::Cover => {
505            let width = frame.0.max(frame.1 * ratio);
506            (width, width / ratio)
507        }
508        ObjectFit::Fill => frame,
509        ObjectFit::None => natural,
510        ObjectFit::ScaleDown => contain((frame.0.min(natural.0), frame.1.min(natural.1)), ratio),
511    };
512    positive_size(fit_size)?;
513    Ok((natural, fit_size))
514}
515
516/// The actual measured placement and sealed source view. Native frozen output
517/// remains an Output, so it never re-enters scientific layout or font shaping.
518#[derive(Debug, Clone)]
519pub(crate) struct PlacedContent {
520    source: FixedSource,
521    pub(crate) frame: Rect,
522    pub(crate) object: Rect,
523    viewport: (f64, f64),
524    pub(crate) rendering: ImageRendering,
525    view: Arc<OnceLock<AssetView>>,
526}
527
528impl PlacedContent {
529    pub(crate) fn at(
530        source: FixedSource,
531        point: (f64, f64),
532        requested: [Option<f64>; 2],
533        anchor: Anchor,
534        rendering: ImageRendering,
535    ) -> Result<Self> {
536        let intrinsic = source.intrinsics();
537        let missing = || {
538            Error::Data("fixed content needs enough dimensions to determine its source viewport; specify a size or use a box".into())
539        };
540        let size = match requested {
541            [Some(w), Some(h)] => (w, h),
542            [Some(w), None] => (
543                w,
544                intrinsic
545                    .ratio
546                    .map(|ratio| w / ratio)
547                    .or(intrinsic.size[1])
548                    .ok_or_else(missing)?,
549            ),
550            [None, Some(h)] => (
551                intrinsic
552                    .ratio
553                    .map(|ratio| h * ratio)
554                    .or(intrinsic.size[0])
555                    .ok_or_else(missing)?,
556                h,
557            ),
558            [None, None] => intrinsic.complete().ok_or_else(missing)?,
559        };
560        positive_size(size)?;
561        let (viewport, _) = object_sizes(intrinsic, size, ObjectFit::Fill)?;
562        let (x, y) = if let Anchor::Local(x, y) = anchor {
563            (x * size.0 / viewport.0, y * size.1 / viewport.1)
564        } else {
565            anchor.point(Rect::new(0., 0., size.0, size.1)?)?
566        };
567        Self::boxed(
568            source,
569            Rect::new(point.0 - x, point.1 - y, size.0, size.1)?,
570            ObjectFit::Fill,
571            ObjectPosition::top_left(),
572            rendering,
573        )
574    }
575
576    pub(crate) fn exact_ink(&self, clip: Rect) -> Result<InkExtent> {
577        let Some(clip) = self
578            .frame
579            .intersection(clip)
580            .and_then(|clip| self.object.intersection(clip))
581        else {
582            return Ok(InkExtent::Empty);
583        };
584        match &self.source {
585            FixedSource::Image(asset) => asset.exact_ink(
586                self.viewport,
587                self.object,
588                clip,
589                self.rendering,
590                self.view.get(),
591            ),
592            FixedSource::Frozen(output) => {
593                let source = Rect::new(0., 0., output.width(), output.height())?;
594                let local_clip = super::ink::map_rect(clip, self.object, source)?;
595                super::ink::map_ink(output.scene().exact_ink(local_clip)?, source, self.object)
596            }
597        }
598    }
599    pub(crate) fn boxed(
600        source: FixedSource,
601        frame: Rect,
602        fit: ObjectFit,
603        position: ObjectPosition,
604        rendering: ImageRendering,
605    ) -> Result<Self> {
606        let frame_size = (frame.width(), frame.height());
607        positive_size(frame_size)?;
608        let (viewport, size) = object_sizes(source.intrinsics(), frame_size, fit)?;
609        let (dx, dy) = position.offset((frame_size.0 - size.0, frame_size.1 - size.1));
610        let object = Rect::new(frame.left() + dx, frame.top() + dy, size.0, size.1)?;
611        Ok(Self {
612            source,
613            frame,
614            object,
615            viewport,
616            rendering,
617            view: Arc::new(OnceLock::new()),
618        })
619    }
620
621    pub(crate) fn is_frozen(&self) -> bool {
622        self.source.is_frozen()
623    }
624
625    pub(crate) fn native_output(&self) -> Option<&Output> {
626        match &self.source {
627            FixedSource::Frozen(output) => Some(output),
628            FixedSource::Image(_) => None,
629        }
630    }
631
632    pub(crate) fn prepare(&self) -> Result<()> {
633        if self.view.get().is_some() {
634            return Ok(());
635        }
636        let FixedSource::Image(asset) = &self.source else {
637            return Ok(());
638        };
639        let view = asset.prepare(self.viewport)?;
640        crate::operation::checkpoint()?;
641        let _ = self.view.set(view);
642        Ok(())
643    }
644
645    pub(crate) fn href(&self, outline: bool) -> Result<&str> {
646        let view = self
647            .view
648            .get()
649            .ok_or_else(|| Error::Render("fixed image was not prepared by capture".into()))?;
650        view.href(outline)
651    }
652
653    pub(crate) fn validate_preserve_text(&self) -> Result<()> {
654        if let Some(native) = self.native_output() {
655            return native.scene().validate_preserve_text();
656        }
657        if let Some(error) = self
658            .view
659            .get()
660            .and_then(|view| view.preserve_error.as_ref())
661        {
662            return Err(Error::Render(error.clone()));
663        }
664        Ok(())
665    }
666
667    pub(crate) fn font_substitutions(&self, output: &mut Vec<super::ImageFontSubstitution>) {
668        if let Some(native) = self.native_output() {
669            native.scene().collect_image_font_substitutions(output);
670        } else if let Some(view) = self.view.get() {
671            output.extend_from_slice(&view.substitutions);
672        }
673    }
674
675    pub(crate) fn ink(&self) -> InkExtent {
676        if let FixedSource::Image(asset) = &self.source {
677            if asset.known_empty() {
678                return InkExtent::Empty;
679            }
680        }
681        if let FixedSource::Frozen(output) = &self.source {
682            if output.scene().composition().is_none() {
683                if let Ok(report) = output.layout_report() {
684                    if report.nodes()[0].ink() == InkExtent::Empty {
685                        return InkExtent::Empty;
686                    }
687                }
688            }
689        }
690        self.object
691            .intersection(self.frame)
692            .map_or(InkExtent::Empty, InkExtent::Bounds)
693    }
694}