Skip to main content

lichtung_plot/composition/
placement.rs

1//! A typed, owned source and its independent placement declaration.
2
3use std::path::{Path, PathBuf};
4
5use super::fixed::FixedSource;
6use super::{ImageAsset, ImageRendering, ObjectFit, ObjectPosition, PlacedContent};
7use crate::builder::PlotDescription;
8use crate::layout::{
9    Anchor, BoundaryRef, BoxTarget, PlacePoint, Rect, RectRef, RootRequest, TextPanel,
10};
11use crate::{Canvas, Error, Output, Plot, Result};
12
13/// A source accepted by final composition. Native declarations, retained
14/// native outputs and sealed local images all retain their actual content.
15#[derive(Clone)]
16pub struct CompositionSource(
17    pub(crate) Source,
18    pub(crate) Option<crate::data::DataSourceInfo>,
19);
20
21#[derive(Clone)]
22pub(crate) enum Source {
23    Plot(Box<PlotDescription>),
24    Canvas(Box<Canvas>),
25    Text(TextPanel),
26    Fixed(FixedSource),
27}
28
29impl<K: crate::kind::Marker> From<Plot<K>> for CompositionSource {
30    fn from(plot: Plot<K>) -> Self {
31        Self(Source::Plot(Box::new(plot.into_description())), None)
32    }
33}
34impl<K: crate::kind::Marker> From<&Plot<K>> for CompositionSource {
35    fn from(plot: &Plot<K>) -> Self {
36        Self(Source::Plot(Box::new(plot.description().clone())), None)
37    }
38}
39impl From<Canvas> for CompositionSource {
40    fn from(canvas: Canvas) -> Self {
41        Self(Source::Canvas(Box::new(canvas)), None)
42    }
43}
44impl From<&Canvas> for CompositionSource {
45    fn from(canvas: &Canvas) -> Self {
46        Self::from(canvas.clone())
47    }
48}
49impl From<TextPanel> for CompositionSource {
50    fn from(text: TextPanel) -> Self {
51        Self(Source::Text(text), None)
52    }
53}
54impl From<&TextPanel> for CompositionSource {
55    fn from(text: &TextPanel) -> Self {
56        Self::from(text.clone())
57    }
58}
59impl From<Output> for CompositionSource {
60    fn from(output: Output) -> Self {
61        Self(Source::Fixed(FixedSource::Frozen(output)), None)
62    }
63}
64impl From<&Output> for CompositionSource {
65    fn from(output: &Output) -> Self {
66        Self::from(output.clone())
67    }
68}
69impl From<ImageAsset> for CompositionSource {
70    fn from(asset: ImageAsset) -> Self {
71        Self(Source::Fixed(FixedSource::Image(asset)), None)
72    }
73}
74impl From<&ImageAsset> for CompositionSource {
75    fn from(asset: &ImageAsset) -> Self {
76        Self::from(asset.clone())
77    }
78}
79
80macro_rules! local_source {
81    ($($ty:ty),+ $(,)?) => {$(
82        impl TryFrom<$ty> for CompositionSource {
83            type Error = Error;
84            fn try_from(path: $ty) -> Result<Self> {
85                Ok(ImageAsset::read_path(path.as_ref())?.into())
86            }
87        }
88    )+};
89}
90local_source!(&str, String, &Path, PathBuf, &PathBuf);
91
92impl CompositionSource {
93    pub(super) fn prepare(
94        self,
95        constraint: Option<RootRequest>,
96        parent_theme: Option<&crate::Theme>,
97    ) -> Result<FixedSource> {
98        use crate::orchestrator::root::RootSource;
99        match self.0 {
100            Source::Fixed(source) => Ok(source),
101            Source::Plot(plot) => {
102                let mut plot = *plot;
103                if let Some(request) = constraint {
104                    plot.set_sizing_request(request);
105                }
106                if let Some(parent) = parent_theme {
107                    plot.inherit_composition_theme(parent);
108                }
109                Ok(FixedSource::Frozen(Output::new(
110                    crate::orchestrator::render_scene(RootSource::Plot(&plot))?,
111                )))
112            }
113            Source::Canvas(canvas) => {
114                let mut canvas = *canvas;
115                if let Some(request) = constraint {
116                    canvas.set_sizing_request(request);
117                }
118                if let Some(parent) = parent_theme {
119                    if canvas.get_theme().is_none() {
120                        canvas = canvas.theme(parent.clone());
121                    }
122                }
123                Ok(FixedSource::Frozen(Output::new(
124                    crate::orchestrator::render_scene(RootSource::Canvas(&canvas))?,
125                )))
126            }
127            Source::Text(text) => {
128                // A standalone text panel reuses the real one-panel layout.
129                // The internal wrapper has no construction-context default.
130                let canvas = Canvas::grid(1, 1)?.default_theme(None).panel(0, 0, text)?;
131                Self::from(canvas).prepare(constraint, parent_theme)
132            }
133        }
134    }
135
136    fn is_fixed(&self) -> bool {
137        matches!(self.0, Source::Fixed(_))
138    }
139
140    fn is_image(&self) -> bool {
141        matches!(self.0, Source::Fixed(FixedSource::Image(_)))
142    }
143}
144
145#[derive(Clone)]
146pub(super) enum Target {
147    At(PlacePoint),
148    Box(BoxTarget),
149}
150
151/// An owned item and a placement in the original base scene's CSS coordinates.
152/// One placement chooses a point or a box; its optional boundary is independent
153/// of its geometric target.
154#[derive(Clone)]
155#[must_use]
156pub struct Placement {
157    pub(super) source: CompositionSource,
158    pub(super) target: Target,
159    pub(super) fit: Option<ObjectFit>,
160    pub(super) position: Option<ObjectPosition>,
161    pub(super) anchor: Option<Anchor>,
162    pub(super) requested: [Option<f64>; 2],
163    pub(super) rendering: Option<ImageRendering>,
164    pub(super) boundary: Option<BoundaryRef>,
165}
166
167impl Placement {
168    pub(super) fn new(source: CompositionSource, target: Target) -> Self {
169        Self {
170            source,
171            target,
172            fit: None,
173            position: None,
174            anchor: None,
175            requested: [None, None],
176            rendering: None,
177            boundary: None,
178        }
179    }
180
181    /// Place a source by its own viewport anchor.
182    pub fn at(
183        item: impl TryInto<CompositionSource, Error: Into<Error>>,
184        at: impl TryInto<PlacePoint, Error: Into<Error>>,
185    ) -> Result<Self> {
186        Ok(Self::new(
187            item.try_into().map_err(Into::into)?,
188            Target::At(at.try_into().map_err(Into::into)?),
189        ))
190    }
191
192    /// Fit a source into a real CSS rectangle or a frozen layout reference.
193    pub fn boxed(
194        item: impl TryInto<CompositionSource, Error: Into<Error>>,
195        target: impl TryInto<BoxTarget, Error: Into<Error>>,
196    ) -> Result<Self> {
197        Ok(Self::new(
198            item.try_into().map_err(Into::into)?,
199            Target::Box(target.try_into().map_err(Into::into)?),
200        ))
201    }
202
203    /// Use the complete allocated footprint of an actual reserved anchor.
204    pub fn in_slot(
205        item: impl TryInto<CompositionSource, Error: Into<Error>>,
206        row: usize,
207        column: usize,
208    ) -> Result<Self> {
209        Self::boxed(item, RectRef::slot(row, column))
210    }
211
212    /// Set an explicit fixed-source fitting policy for this box.
213    pub fn fit(mut self, fit: ObjectFit) -> Self {
214        self.fit = Some(fit);
215        self
216    }
217    /// Set the object's position within its box.
218    pub fn position(mut self, position: ObjectPosition) -> Self {
219        self.position = Some(position);
220        self
221    }
222    /// Choose the source viewport point for an at-placement.
223    pub fn anchor(mut self, anchor: Anchor) -> Self {
224        self.anchor = Some(anchor);
225        self
226    }
227    /// Request an at-placement width in CSS pixels.
228    pub fn width(mut self, width: f64) -> Self {
229        self.requested[0] = Some(width);
230        self
231    }
232    /// Request an at-placement height in CSS pixels.
233    pub fn height(mut self, height: f64) -> Self {
234        self.requested[1] = Some(height);
235        self
236    }
237    /// Request an at-placement size in CSS pixels.
238    pub fn size(mut self, width: f64, height: f64) -> Self {
239        self.requested = [Some(width), Some(height)];
240        self
241    }
242    /// Set the sampling policy for an image source.
243    pub fn image_rendering(mut self, rendering: ImageRendering) -> Self {
244        self.rendering = Some(rendering);
245        self
246    }
247    /// Use a real closed boundary of the original native base.
248    pub fn at_boundary(mut self, boundary: BoundaryRef) -> Self {
249        self.boundary = Some(boundary);
250        self
251    }
252
253    pub(crate) fn boundary(&self) -> Option<&BoundaryRef> {
254        self.boundary.as_ref()
255    }
256
257    /// Validate this placement's authored options without resolving a base.
258    pub fn validate(&self) -> Result<()> {
259        if self
260            .requested
261            .into_iter()
262            .flatten()
263            .any(|value| !value.is_finite() || value <= 0.)
264        {
265            return Err(Error::Data(
266                "placement dimensions must be positive finite CSS pixels".into(),
267            ));
268        }
269        match self.target {
270            Target::At(_) if self.fit.is_some() || self.position.is_some() => {
271                return Err(Error::Data(
272                    "fit and position require a placement box".into(),
273                ))
274            }
275            Target::Box(_)
276                if self.anchor.is_some() || self.requested.iter().any(Option::is_some) =>
277            {
278                return Err(Error::Data(
279                    "anchor, width and height require an at-placement".into(),
280                ))
281            }
282            _ => {}
283        }
284        if self.rendering.is_some() && !self.source.is_image() {
285            return Err(Error::Data(
286                "image_rendering requires an image source".into(),
287            ));
288        }
289        Ok(())
290    }
291
292    pub(crate) fn slot_borrow(&self) -> Result<(usize, usize)> {
293        self.validate()?;
294        if self.boundary.is_some() {
295            return Err(Error::Data(
296                "a paint boundary requires a frozen base scene".into(),
297            ));
298        }
299        match &self.target {
300            Target::Box(target) => target.reservation_anchor(),
301            Target::At(_) => None,
302        }
303        .ok_or_else(|| {
304            Error::Data("an editable Canvas placement must borrow a reserved slot".into())
305        })
306    }
307
308    pub(crate) fn prepare(
309        self,
310        resolve: impl Fn(&RectRef) -> Result<Rect>,
311        parent_theme: Option<&crate::Theme>,
312    ) -> Result<PlacedContent> {
313        self.validate()?;
314        let fixed = self.source.is_fixed();
315        let rendering = self.rendering.unwrap_or_default();
316        let placed = match self.target {
317            Target::Box(target) => {
318                let frame = target.resolve(&resolve)?;
319                let request = (!fixed && self.fit.is_none())
320                    .then(|| RootRequest::size(frame.width(), frame.height()));
321                let source = self.source.prepare(request, parent_theme)?;
322                PlacedContent::boxed(
323                    source,
324                    frame,
325                    if request.is_some() {
326                        ObjectFit::Fill
327                    } else {
328                        self.fit.unwrap_or_default()
329                    },
330                    self.position.unwrap_or_default(),
331                    rendering,
332                )?
333            }
334            Target::At(target) => {
335                let point = target.resolve(&resolve)?;
336                let request = match self.requested {
337                    [Some(w), Some(h)] => Some(RootRequest::size(w, h)),
338                    [Some(w), None] => Some(RootRequest::width(w)),
339                    [None, Some(h)] => Some(RootRequest::height(h)),
340                    [None, None] => None,
341                };
342                let source = self
343                    .source
344                    .prepare(if fixed { None } else { request }, parent_theme)?;
345                PlacedContent::at(
346                    source,
347                    point,
348                    if fixed { self.requested } else { [None, None] },
349                    self.anchor.unwrap_or_default(),
350                    rendering,
351                )?
352            }
353        };
354        placed.prepare()?;
355        Ok(placed)
356    }
357}