Skip to main content

alpha2_extensions/
registry.rs

1//! Provider selection by probing bytes in registration order, with no fallback after a failure.
2//!
3//! Every provider call goes through [`contained`], so a panic in third-party parsing code fails
4//! only that file. In the browser module panics abort, and `alpha2/extensions` restarts the module.
5
6use std::panic::{AssertUnwindSafe, catch_unwind};
7use std::sync::Arc;
8
9use alpha2_model::ProviderSource;
10use alpha2_time::MediaTime;
11
12use crate::api::{
13    ExtensionError, ProbeReport, SharedResolver, VisualFrame, VisualProvider, VisualSource,
14};
15
16/// The providers a host's build includes, highest priority first.
17#[derive(Default)]
18pub struct Registry {
19    providers: Vec<Box<dyn VisualProvider>>,
20}
21
22impl Registry {
23    /// Every provider this build includes, in order: SVG, PDF, animated images, Lottie, OpenEXR.
24    /// Image sequences and LaTeX are opened without one.
25    #[must_use]
26    pub fn with_defaults() -> Self {
27        #[allow(unused_mut)]
28        let mut registry = Self::default();
29        #[cfg(feature = "svg")]
30        registry.register(Box::new(crate::SvgProvider));
31        #[cfg(feature = "pdf")]
32        registry.register(Box::new(crate::PdfProvider));
33        #[cfg(feature = "animated-image")]
34        registry.register(Box::new(crate::AnimatedImageProvider));
35        #[cfg(feature = "lottie")]
36        registry.register(Box::new(crate::LottieProvider));
37        #[cfg(feature = "exr")]
38        registry.register(Box::new(crate::ExrProvider));
39        registry
40    }
41
42    /// Adds `provider` after those already registered.
43    pub fn register(&mut self, provider: Box<dyn VisualProvider>) {
44        self.providers.push(provider);
45    }
46
47    /// The registered providers' names, in priority order.
48    #[must_use]
49    pub fn names(&self) -> Vec<&'static str> {
50        self.providers
51            .iter()
52            .map(|provider| provider.name())
53            .collect()
54    }
55
56    /// The first provider that claims `bytes` and its report, or `None`. A claiming provider's
57    /// error is returned as is; no other provider is tried.
58    #[must_use]
59    pub fn probe(
60        &self,
61        bytes: &[u8],
62    ) -> Option<Result<(&'static str, ProbeReport), ExtensionError>> {
63        self.providers.iter().find_map(|provider| {
64            let name = provider.name();
65            contained(name, || Ok(provider.probe(bytes)))
66                .unwrap_or_else(|error| Some(Err(error)))
67                .map(|report| report.map(|report| (name, report)))
68        })
69    }
70
71    /// Whether this build opens `source`.
72    #[must_use]
73    pub fn supports(&self, source: &ProviderSource) -> bool {
74        match source {
75            ProviderSource::ImageSequence { .. } => Self::reads_image_sequences(),
76            ProviderSource::Latex { .. } => Self::reads_latex(),
77            other => self.named(provider_name(other)).is_some(),
78        }
79    }
80
81    /// Whether this build reads image sequences, which have no registered provider.
82    #[must_use]
83    pub const fn reads_image_sequences() -> bool {
84        cfg!(feature = "image-sequence")
85    }
86
87    /// Whether this build typesets LaTeX, which reads no file and so has no registered provider.
88    #[must_use]
89    pub const fn reads_latex() -> bool {
90        cfg!(feature = "latex")
91    }
92
93    /// Locators [`Self::open`] reads for `source` (an image sequence's first frame).
94    #[must_use]
95    pub fn open_needs(&self, source: &ProviderSource) -> Vec<String> {
96        match source {
97            ProviderSource::ImageSequence { frames, .. } => {
98                frames.first().cloned().flatten().into_iter().collect()
99            }
100            _ => Vec::new(),
101        }
102    }
103
104    /// Opens a project's provider source from its bytes (`None` for an image sequence, whose
105    /// frames come from `resolver`, and for LaTeX, which reads no file).
106    ///
107    /// Renders go through the same panic boundary. After one render panics, every later render
108    /// fails without running provider code on the state the panic left.
109    ///
110    /// # Errors
111    /// [`ExtensionError::Unsupported`] without a provider, [`ExtensionError::Mismatch`] for
112    /// another format, or the provider's error ([`ExtensionError::Malformed`] if it panicked).
113    pub fn open(
114        &self,
115        source: &ProviderSource,
116        bytes: Option<Arc<[u8]>>,
117        resolver: SharedResolver,
118    ) -> Result<Box<dyn VisualSource>, ExtensionError> {
119        self.open_within(source, bytes, resolver, crate::DEFAULT_FRAME_BUDGET)
120    }
121
122    /// [`Self::open`], with an image sequence keeping at most `sequence_frames` decoded bytes, or
123    /// the frame it last showed alone when that is larger.
124    ///
125    /// # Errors
126    /// As [`Self::open`].
127    #[cfg_attr(
128        not(feature = "image-sequence"),
129        allow(clippy::needless_pass_by_value, unused_variables)
130    )]
131    pub fn open_within(
132        &self,
133        source: &ProviderSource,
134        bytes: Option<Arc<[u8]>>,
135        resolver: SharedResolver,
136        sequence_frames: usize,
137    ) -> Result<Box<dyn VisualSource>, ExtensionError> {
138        let name = provider_name(source);
139        let opened = match source {
140            #[cfg(feature = "image-sequence")]
141            ProviderSource::ImageSequence {
142                frames,
143                frame_rate,
144                missing,
145                primaries,
146                ..
147            } => contained(name, || {
148                crate::sequence::open_within(
149                    frames,
150                    *frame_rate,
151                    *missing,
152                    *primaries,
153                    resolver,
154                    sequence_frames,
155                )
156            })?,
157            #[cfg(feature = "latex")]
158            ProviderSource::Latex {
159                latex,
160                font_size,
161                color,
162                display,
163            } => contained(name, || {
164                crate::open_latex(latex, *font_size, *color, *display)
165            })?,
166            other => {
167                let provider = self.named(name).ok_or_else(|| {
168                    ExtensionError::Unsupported(format!("this build has no {name} provider"))
169                })?;
170                let bytes = bytes.ok_or_else(|| {
171                    ExtensionError::MissingResource("the source's own bytes".into())
172                })?;
173                // Open detects a format mismatch itself, so no extra probe pass is needed.
174                contained(name, || provider.open(bytes, other, &*resolver))?
175            }
176        };
177        Ok(Box::new(Contained {
178            name,
179            source: opened,
180            failed: None,
181        }))
182    }
183
184    fn named(&self, name: &str) -> Option<&dyn VisualProvider> {
185        self.providers
186            .iter()
187            .find(|provider| provider.name() == name)
188            .map(AsRef::as_ref)
189    }
190}
191
192/// A source whose renders go through the panic boundary.
193struct Contained {
194    name: &'static str,
195    source: Box<dyn VisualSource>,
196    /// Set once a render panics, and returned by every later render.
197    failed: Option<ExtensionError>,
198}
199
200impl VisualSource for Contained {
201    fn report(&self) -> &ProbeReport {
202        self.source.report()
203    }
204
205    fn render(&mut self, time: MediaTime, fit: (u32, u32)) -> Result<VisualFrame, ExtensionError> {
206        if let Some(error) = &self.failed {
207            return Err(error.clone());
208        }
209        let source = &mut self.source;
210        catch_unwind(AssertUnwindSafe(|| source.render(time, fit))).unwrap_or_else(|payload| {
211            let error = panicked(self.name, payload.as_ref());
212            self.failed = Some(error.clone());
213            Err(error)
214        })
215    }
216
217    fn needs(&self, time: MediaTime) -> Vec<String> {
218        if self.failed.is_some() {
219            return Vec::new();
220        }
221        catch_unwind(AssertUnwindSafe(|| self.source.needs(time))).unwrap_or_default()
222    }
223
224    fn resident_bytes(&self) -> usize {
225        catch_unwind(AssertUnwindSafe(|| self.source.resident_bytes())).unwrap_or_default()
226    }
227
228    /// None after a panic, since shared state may be what the panic left.
229    fn reader(&self) -> Option<Box<dyn VisualSource>> {
230        if self.failed.is_some() {
231            return None;
232        }
233        let source = catch_unwind(AssertUnwindSafe(|| self.source.reader())).ok()??;
234        Some(Box::new(Self {
235            name: self.name,
236            source,
237            failed: None,
238        }))
239    }
240
241    fn shared_bytes(&self) -> usize {
242        catch_unwind(AssertUnwindSafe(|| self.source.shared_bytes())).unwrap_or_default()
243    }
244}
245
246/// Runs `call`, turning a panic into the file's failure.
247fn contained<T>(
248    provider: &str,
249    call: impl FnOnce() -> Result<T, ExtensionError>,
250) -> Result<T, ExtensionError> {
251    catch_unwind(AssertUnwindSafe(call))
252        .unwrap_or_else(|payload| Err(panicked(provider, payload.as_ref())))
253}
254
255fn panicked(provider: &str, payload: &(dyn std::any::Any + Send)) -> ExtensionError {
256    let message = payload
257        .downcast_ref::<&str>()
258        .copied()
259        .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
260        .unwrap_or("no message");
261    ExtensionError::Malformed(format!(
262        "the {provider} provider failed on this file (it panicked: {message})"
263    ))
264}
265
266fn provider_name(source: &ProviderSource) -> &'static str {
267    match source {
268        ProviderSource::Svg => "svg",
269        ProviderSource::AnimatedImage => "animated-image",
270        ProviderSource::Lottie { .. } => "lottie",
271        ProviderSource::Exr { .. } => "exr",
272        ProviderSource::Latex { .. } => "latex",
273        ProviderSource::Pdf { .. } => "pdf",
274        _ => "image-sequence",
275    }
276}