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    #[cfg_attr(not(feature = "image-sequence"), allow(clippy::needless_pass_by_value))]
114    pub fn open(
115        &self,
116        source: &ProviderSource,
117        bytes: Option<Arc<[u8]>>,
118        resolver: SharedResolver,
119    ) -> Result<Box<dyn VisualSource>, ExtensionError> {
120        let name = provider_name(source);
121        let opened = match source {
122            #[cfg(feature = "image-sequence")]
123            ProviderSource::ImageSequence {
124                frames,
125                frame_rate,
126                missing,
127                primaries,
128                ..
129            } => contained(name, || {
130                crate::open_sequence(frames, *frame_rate, *missing, *primaries, resolver)
131            })?,
132            #[cfg(feature = "latex")]
133            ProviderSource::Latex {
134                latex,
135                font_size,
136                color,
137                display,
138            } => contained(name, || {
139                crate::open_latex(latex, *font_size, *color, *display)
140            })?,
141            other => {
142                let provider = self.named(name).ok_or_else(|| {
143                    ExtensionError::Unsupported(format!("this build has no {name} provider"))
144                })?;
145                let bytes = bytes.ok_or_else(|| {
146                    ExtensionError::MissingResource("the source's own bytes".into())
147                })?;
148                // Open detects a format mismatch itself, so no extra probe pass is needed.
149                contained(name, || provider.open(bytes, other, &*resolver))?
150            }
151        };
152        Ok(Box::new(Contained {
153            name,
154            source: opened,
155            failed: None,
156        }))
157    }
158
159    fn named(&self, name: &str) -> Option<&dyn VisualProvider> {
160        self.providers
161            .iter()
162            .find(|provider| provider.name() == name)
163            .map(AsRef::as_ref)
164    }
165}
166
167/// A source whose renders go through the panic boundary.
168struct Contained {
169    name: &'static str,
170    source: Box<dyn VisualSource>,
171    /// Set once a render panics, and returned by every later render.
172    failed: Option<ExtensionError>,
173}
174
175impl VisualSource for Contained {
176    fn report(&self) -> &ProbeReport {
177        self.source.report()
178    }
179
180    fn render(&mut self, time: MediaTime, fit: (u32, u32)) -> Result<VisualFrame, ExtensionError> {
181        if let Some(error) = &self.failed {
182            return Err(error.clone());
183        }
184        let source = &mut self.source;
185        catch_unwind(AssertUnwindSafe(|| source.render(time, fit))).unwrap_or_else(|payload| {
186            let error = panicked(self.name, payload.as_ref());
187            self.failed = Some(error.clone());
188            Err(error)
189        })
190    }
191
192    fn needs(&self, time: MediaTime) -> Vec<String> {
193        if self.failed.is_some() {
194            return Vec::new();
195        }
196        catch_unwind(AssertUnwindSafe(|| self.source.needs(time))).unwrap_or_default()
197    }
198
199    fn resident_bytes(&self) -> usize {
200        catch_unwind(AssertUnwindSafe(|| self.source.resident_bytes())).unwrap_or_default()
201    }
202
203    /// None after a panic, since shared state may be what the panic left.
204    fn reader(&self) -> Option<Box<dyn VisualSource>> {
205        if self.failed.is_some() {
206            return None;
207        }
208        let source = catch_unwind(AssertUnwindSafe(|| self.source.reader())).ok()??;
209        Some(Box::new(Self {
210            name: self.name,
211            source,
212            failed: None,
213        }))
214    }
215
216    fn shared_bytes(&self) -> usize {
217        catch_unwind(AssertUnwindSafe(|| self.source.shared_bytes())).unwrap_or_default()
218    }
219}
220
221/// Runs `call`, turning a panic into the file's failure.
222fn contained<T>(
223    provider: &str,
224    call: impl FnOnce() -> Result<T, ExtensionError>,
225) -> Result<T, ExtensionError> {
226    catch_unwind(AssertUnwindSafe(call))
227        .unwrap_or_else(|payload| Err(panicked(provider, payload.as_ref())))
228}
229
230fn panicked(provider: &str, payload: &(dyn std::any::Any + Send)) -> ExtensionError {
231    let message = payload
232        .downcast_ref::<&str>()
233        .copied()
234        .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
235        .unwrap_or("no message");
236    ExtensionError::Malformed(format!(
237        "the {provider} provider failed on this file (it panicked: {message})"
238    ))
239}
240
241fn provider_name(source: &ProviderSource) -> &'static str {
242    match source {
243        ProviderSource::Svg => "svg",
244        ProviderSource::AnimatedImage => "animated-image",
245        ProviderSource::Lottie { .. } => "lottie",
246        ProviderSource::Exr { .. } => "exr",
247        ProviderSource::Latex { .. } => "latex",
248        ProviderSource::Pdf { .. } => "pdf",
249        _ => "image-sequence",
250    }
251}