Skip to main content

capsule_sdk/ffi/
ladder.rs

1//! The render ladder across the FFI boundary: the flattened mirror of
2//! [`crate::fetch::render_step`] and the embedded-preview read it is fed with.
3//!
4//! # Why free functions
5//!
6//! [`render_step`] is pure: it answers from the request, what the surface shows and what the
7//! device holds, all of which the caller passes. The surface keeps the [`FfiRendition`] it shows
8//! and hands it back on the next call, which is what lets a view upgrade in place without this
9//! side holding a per-view object. [`embedded_preview`] reads one file and holds nothing either.
10//! Neither touches a workspace, so neither is a method of
11//! [`FfiWorkspace`](crate::ffi::FfiWorkspace).
12//!
13//! # An app keeps no ladder
14//!
15//! The apps render the rung [`render_step`] names and obtain the rung its `next` names. The
16//! order, the stand-in rule for the embedded preview and the never-downgrade rule live only in
17//! [`crate::fetch::ladder`](crate::fetch::render_step).
18
19use std::collections::BTreeSet;
20use std::path::Path;
21
22use capsule_core::media::{EmbeddedPreview, extract_embedded_preview};
23
24use super::FfiError;
25use crate::fetch::{
26    LocalHoldings, NextStep, PixelSize, RenderRequest, RenderStep, Rendition, Representation,
27    RungSource,
28};
29
30/// A rung of the ladder, cheapest first.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
32pub enum FfiRepresentation {
33    /// The LQIP, embedded in the metadata blob; always present.
34    Lqip,
35    /// The grid thumbnail.
36    Thumbnail,
37    /// The single-asset view's preview.
38    Preview,
39    /// The original.
40    Original,
41}
42
43impl From<FfiRepresentation> for Representation {
44    fn from(rung: FfiRepresentation) -> Self {
45        match rung {
46            FfiRepresentation::Lqip => Self::Lqip,
47            FfiRepresentation::Thumbnail => Self::Thumbnail,
48            FfiRepresentation::Preview => Self::Preview,
49            FfiRepresentation::Original => Self::Original,
50        }
51    }
52}
53
54impl From<Representation> for FfiRepresentation {
55    fn from(rung: Representation) -> Self {
56        match rung {
57            Representation::Lqip => Self::Lqip,
58            Representation::Thumbnail => Self::Thumbnail,
59            Representation::Preview => Self::Preview,
60            Representation::Original => Self::Original,
61        }
62    }
63}
64
65/// Where a shown rung's pixels come from.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
67pub enum FfiRungSource {
68    /// The LQIP (`render_lqip`), which paints the dominant colour where it does not decode.
69    Lqip,
70    /// The original's embedded preview ([`embedded_preview`]).
71    Embedded,
72    /// The rung's encoded tier.
73    Encoded,
74    /// The original, decoded.
75    Original,
76}
77
78impl From<FfiRungSource> for RungSource {
79    fn from(source: FfiRungSource) -> Self {
80        match source {
81            FfiRungSource::Lqip => Self::Lqip,
82            FfiRungSource::Embedded => Self::Embedded,
83            FfiRungSource::Encoded => Self::Encoded,
84            FfiRungSource::Original => Self::Original,
85        }
86    }
87}
88
89impl From<RungSource> for FfiRungSource {
90    fn from(source: RungSource) -> Self {
91        match source {
92            RungSource::Lqip => Self::Lqip,
93            RungSource::Embedded => Self::Embedded,
94            RungSource::Encoded => Self::Encoded,
95            RungSource::Original => Self::Original,
96        }
97    }
98}
99
100/// What a surface shows: a rung and its source. The caller keeps the last one and passes it
101/// back as `shown`.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]
103pub struct FfiRendition {
104    /// The rung shown.
105    pub rung: FfiRepresentation,
106    /// What fills it.
107    pub source: FfiRungSource,
108}
109
110impl From<FfiRendition> for Rendition {
111    fn from(shown: FfiRendition) -> Self {
112        Self {
113            rung: shown.rung.into(),
114            source: shown.source.into(),
115        }
116    }
117}
118
119impl From<Rendition> for FfiRendition {
120    fn from(shown: Rendition) -> Self {
121        Self {
122            rung: shown.rung.into(),
123            source: shown.source.into(),
124        }
125    }
126}
127
128/// A surface's request: its intent and its size in device pixels when the view opened.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]
130pub struct FfiRenderRequest {
131    /// The rung the surface's intent needs: `Thumbnail` for the grid, `Preview` for the
132    /// single-asset view, `Original` for a full-fidelity view.
133    pub intent: FfiRepresentation,
134    /// The surface's width when the view opened. A view that grows keeps passing this.
135    pub surface_width: u32,
136    /// The surface's height when the view opened.
137    pub surface_height: u32,
138}
139
140/// What this device holds for the asset. **Flat**, like `FfiNotifyInput`: an embedded preview
141/// is present when both of its dimensions are.
142#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
143pub struct FfiLocalHoldings {
144    /// The encoded tiers and the original held locally; the LQIP is implied.
145    pub held: Vec<FfiRepresentation>,
146    /// The embedded preview's upright width, from [`embedded_preview`].
147    pub embedded_preview_width: Option<u32>,
148    /// The embedded preview's upright height.
149    pub embedded_preview_height: Option<u32>,
150}
151
152/// How to obtain the next rung.
153#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
154pub enum FfiNextStep {
155    /// Fetch it from the server.
156    Fetch {
157        /// The representation to fetch.
158        representation: FfiRepresentation,
159    },
160    /// Produce it on the device from the original it holds.
161    Generate {
162        /// The rung to produce.
163        representation: FfiRepresentation,
164    },
165}
166
167impl From<NextStep> for FfiNextStep {
168    fn from(next: NextStep) -> Self {
169        match next {
170            NextStep::Fetch(rung) => Self::Fetch {
171                representation: rung.into(),
172            },
173            NextStep::Generate(rung) => Self::Generate {
174                representation: rung.into(),
175            },
176        }
177    }
178}
179
180/// The answer to one [`render_step`].
181#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]
182pub struct FfiRenderStep {
183    /// What to show now.
184    pub show: FfiRendition,
185    /// Whether `show` differs from the `shown` passed in.
186    pub changed: bool,
187    /// What to obtain next, or `None` when the intent is met or nothing can raise it.
188    pub next: Option<FfiNextStep>,
189}
190
191impl From<RenderStep> for FfiRenderStep {
192    fn from(step: RenderStep) -> Self {
193        Self {
194            show: step.show.into(),
195            changed: step.changed,
196            next: step.next.map(Into::into),
197        }
198    }
199}
200
201/// A RAW original's embedded JPEG, as [`embedded_preview`] reads it.
202#[derive(Clone, PartialEq, Eq, uniffi::Record)]
203pub struct FfiEmbeddedPreview {
204    /// The JPEG exactly as the RAW file carries it.
205    pub jpeg: Vec<u8>,
206    /// Upright width in pixels, once `orientation` is applied.
207    pub width: u32,
208    /// Upright height in pixels.
209    pub height: u32,
210    /// The EXIF orientation (1..=8) to apply to `jpeg`'s stored pixels, in place of any tag the
211    /// JPEG itself carries.
212    pub orientation: u16,
213}
214
215impl std::fmt::Debug for FfiEmbeddedPreview {
216    // The JPEG never reaches the log.
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        f.debug_struct("FfiEmbeddedPreview")
219            .field("bytes", &self.jpeg.len())
220            .field("width", &self.width)
221            .field("height", &self.height)
222            .field("orientation", &self.orientation)
223            .finish()
224    }
225}
226
227impl From<EmbeddedPreview> for FfiEmbeddedPreview {
228    fn from(preview: EmbeddedPreview) -> Self {
229        Self {
230            jpeg: preview.jpeg,
231            width: preview.width,
232            height: preview.height,
233            orientation: preview.orientation,
234        }
235    }
236}
237
238/// One step of the render ladder ([`crate::fetch::render_step`]): what to show now and what to
239/// obtain next. `shown` is what the surface shows, `None` when it shows nothing yet or is falling
240/// back below what it showed; `fetchable` is what the server lists for the asset.
241#[uniffi::export]
242#[must_use]
243pub fn render_step(
244    request: FfiRenderRequest,
245    shown: Option<FfiRendition>,
246    local: FfiLocalHoldings,
247    fetchable: Vec<FfiRepresentation>,
248) -> FfiRenderStep {
249    let request = RenderRequest {
250        intent: request.intent.into(),
251        surface: PixelSize {
252            width: request.surface_width,
253            height: request.surface_height,
254        },
255    };
256    let local = LocalHoldings {
257        held: local.held.into_iter().map(Into::into).collect(),
258        embedded_preview: local
259            .embedded_preview_width
260            .zip(local.embedded_preview_height)
261            .map(|(width, height)| PixelSize { width, height }),
262    };
263    let fetchable: BTreeSet<Representation> = fetchable.into_iter().map(Into::into).collect();
264    crate::fetch::render_step(&request, shown.map(Into::into), &local, &fetchable).into()
265}
266
267/// Read the embedded preview of the original at `original_path`, whose extension (without the
268/// dot) is `ext`.
269///
270/// `None` when the original is not a RAW, carries no preview, or carries one that does not read
271/// within the decode budget: each leaves the rung to the next source, so none is an error. The
272/// reason is logged.
273///
274/// This reads the whole original into memory, because the extraction's IFD bounds walk and its
275/// stated-length guard run over the full file before the RAW reader does. Call it once per asset
276/// and keep the [`FfiEmbeddedPreview`] it returns, rather than once per render.
277///
278/// # Errors
279///
280/// [`FfiError::Workspace`] when the file cannot be read.
281#[uniffi::export]
282#[tracing::instrument(level = "debug", skip(original_path))]
283pub fn embedded_preview(
284    original_path: String,
285    ext: String,
286) -> Result<Option<FfiEmbeddedPreview>, FfiError> {
287    let path = Path::new(&original_path);
288    let bytes = std::fs::read(path).map_err(|e| FfiError::Workspace {
289        detail: format!("reading the original {}: {e}", path.display()),
290    })?;
291    Ok(embedded_preview_of(&bytes, &ext))
292}
293
294/// [`embedded_preview`] over bytes already read.
295fn embedded_preview_of(bytes: &[u8], ext: &str) -> Option<FfiEmbeddedPreview> {
296    match extract_embedded_preview(bytes, ext) {
297        Ok(preview) => preview.map(Into::into),
298        Err(error) => {
299            tracing::info!(%error, ext, "ffi: no embedded preview; the rung falls to the next source");
300            None
301        }
302    }
303}
304
305#[cfg(test)]
306mod tests;