Skip to main content

vizia_core/resource/
mod.rs

1//! Resource management for fonts, themes, images, and translations.
2
3mod file_resource_loader;
4mod image_id;
5mod url_resource_loader;
6
7pub use file_resource_loader::FileResourceLoader;
8pub use image_id::ImageId;
9#[cfg(feature = "url-loader")]
10pub use url_resource_loader::UrlResourceLoader;
11use vizia_id::IdManager;
12use vizia_reactive::{Signal, SignalGet, SignalUpdate};
13
14use crate::context::ResourceContext;
15use crate::entity::Entity;
16use crate::prelude::IntoCssStr;
17// use crate::view::Canvas;
18use fluent_bundle::types::FluentNumber;
19use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue};
20use hashbrown::{HashMap, HashSet};
21use jiff::Timestamp;
22use jiff::tz::TimeZone;
23use std::fmt;
24use unic_langid::LanguageIdentifier;
25
26/// Error type for translation operations.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum TranslationError {
29    /// FTL file syntax is invalid.
30    InvalidFtl(String),
31    /// Failed to add resource to translation bundle.
32    BundleError(String),
33}
34
35impl fmt::Display for TranslationError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            TranslationError::InvalidFtl(msg) => write!(f, "Invalid FTL syntax: {}", msg),
39            TranslationError::BundleError(msg) => {
40                write!(f, "Failed to add to translation bundle: {}", msg)
41            }
42        }
43    }
44}
45
46impl std::error::Error for TranslationError {}
47
48fn fluent_number<'a>(positional: &[FluentValue<'a>], named: &FluentArgs) -> FluentValue<'a> {
49    let Some(first) = positional.first() else {
50        return FluentValue::Error;
51    };
52
53    let mut number = match first {
54        FluentValue::Number(num) => num.clone(),
55        FluentValue::String(value) => match value.parse::<FluentNumber>() {
56            Ok(number) => number,
57            Err(_) => return FluentValue::Error,
58        },
59        _ => return FluentValue::Error,
60    };
61
62    number.options.merge(named);
63    FluentValue::Number(number)
64}
65
66fn style_str(args: &FluentArgs, key: &str) -> Option<String> {
67    match args.get(key) {
68        Some(FluentValue::String(value)) => Some(value.to_string()),
69        _ => None,
70    }
71}
72
73fn datetime_format_pattern(args: &FluentArgs) -> String {
74    let weekday = match style_str(args, "weekday").as_deref() {
75        Some("long") => Some("%A"),
76        Some("short") => Some("%a"),
77        _ => None,
78    };
79
80    let month = match style_str(args, "month").as_deref() {
81        Some("long") => Some("%B"),
82        Some("short") => Some("%b"),
83        Some("2-digit") => Some("%m"),
84        Some("numeric") => Some("%-m"),
85        _ => None,
86    };
87
88    let day = match style_str(args, "day").as_deref() {
89        Some("2-digit") => Some("%d"),
90        Some("numeric") => Some("%-d"),
91        _ => None,
92    };
93
94    let year = match style_str(args, "year").as_deref() {
95        Some("2-digit") => Some("%y"),
96        Some("numeric") => Some("%Y"),
97        _ => None,
98    };
99
100    let hour = match style_str(args, "hour").as_deref() {
101        Some("2-digit") => Some("%H"),
102        Some("numeric") => Some("%-H"),
103        _ => None,
104    };
105
106    let minute = match style_str(args, "minute").as_deref() {
107        Some("2-digit") => Some("%M"),
108        Some("numeric") => Some("%-M"),
109        _ => None,
110    };
111
112    let mut date_parts = Vec::new();
113    if let Some(part) = weekday {
114        date_parts.push(part);
115    }
116    if let Some(part) = month {
117        date_parts.push(part);
118    }
119    if let Some(part) = day {
120        date_parts.push(part);
121    }
122    if let Some(part) = year {
123        date_parts.push(part);
124    }
125
126    let mut pattern = date_parts.join(" ");
127    if hour.is_some() || minute.is_some() {
128        if !pattern.is_empty() {
129            pattern.push(' ');
130        }
131        let mut time_parts = Vec::new();
132        if let Some(part) = hour {
133            time_parts.push(part);
134        }
135        if let Some(part) = minute {
136            time_parts.push(part);
137        }
138        pattern.push_str(&time_parts.join(":"));
139    }
140
141    if pattern.is_empty() { "%Y-%m-%d %H:%M:%S".to_string() } else { pattern }
142}
143
144fn fluent_datetime<'a>(positional: &[FluentValue<'a>], named: &FluentArgs) -> FluentValue<'a> {
145    let Some(first) = positional.first() else {
146        return FluentValue::Error;
147    };
148
149    let millis = match first {
150        FluentValue::Number(num) => num.value,
151        FluentValue::String(value) => match value.parse::<f64>() {
152            Ok(millis) => millis,
153            Err(_) => return FluentValue::Error,
154        },
155        _ => return FluentValue::Error,
156    };
157
158    // NaN would cast to 0 and render the epoch; infinities saturate and are rejected below anyway.
159    if !millis.is_finite() {
160        return FluentValue::Error;
161    }
162
163    // Round toward negative infinity, like `timestamp_millis` in `localization`.
164    let Ok(timestamp) = Timestamp::from_millisecond(millis.floor() as i64) else {
165        return FluentValue::Error;
166    };
167
168    let pattern = datetime_format_pattern(named);
169    match jiff::fmt::strtime::format(&pattern, &timestamp.to_zoned_datetime(TimeZone::UTC)) {
170        Ok(text) => FluentValue::String(text.into()),
171        Err(_) => FluentValue::Error,
172    }
173}
174
175fn make_bundle(lang: LanguageIdentifier) -> FluentBundle<FluentResource> {
176    let mut bundle = FluentBundle::new(vec![lang]);
177
178    bundle.add_function("NUMBER", fluent_number).expect("Failed to register NUMBER function");
179    bundle.add_function("DATETIME", fluent_datetime).expect("Failed to register DATETIME function");
180
181    bundle
182}
183
184/// Structured diagnostics emitted by localization while resolving messages.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub(crate) enum LocalizationIssue {
187    /// A message key was not found in any fallback bundle.
188    MissingMessage { key: String, requested_locale: String },
189    /// A message attribute was not found in any fallback bundle.
190    MissingAttribute { key: String, attribute: String, requested_locale: String },
191    /// Fluent formatting reported errors while resolving a message.
192    FormatError { key: String, locale: String, details: String },
193}
194
195impl fmt::Display for LocalizationIssue {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self {
198            LocalizationIssue::MissingMessage { key, requested_locale } => {
199                write!(f, "Missing localized message '{}' for locale '{}'.", key, requested_locale)
200            }
201            LocalizationIssue::MissingAttribute { key, attribute, requested_locale } => write!(
202                f,
203                "Missing localized attribute '{}.{}' for locale '{}'.",
204                key, attribute, requested_locale
205            ),
206            LocalizationIssue::FormatError { key, locale, details } => {
207                write!(f, "Formatting error for key '{}' in locale '{}': {}", key, locale, details)
208            }
209        }
210    }
211}
212
213/// Request to load an image resource.
214#[derive(Debug, Clone)]
215pub struct ImageRequest {
216    /// Name used to reference the loaded image in styles and image views.
217    pub name: String,
218    /// Path or URL to the image resource.
219    pub path: String,
220    /// How long the image should be retained in memory.
221    pub policy: ImageRetentionPolicy,
222}
223
224/// Request to load a font resource.
225#[derive(Debug, Clone)]
226pub struct FontRequest {
227    /// Path or URL to the font resource.
228    pub path: String,
229}
230
231/// Request to load a translation resource.
232#[derive(Debug, Clone)]
233pub struct TranslationRequest {
234    /// Language identifier this translation file belongs to.
235    pub lang: LanguageIdentifier,
236    /// Path or URL to the translation resource.
237    pub path: String,
238}
239
240/// Loading status of a resource.
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum LoadingStatus {
243    /// Resource has not been loaded yet.
244    NotLoaded,
245    /// Resource is currently loading.
246    Loading,
247    /// Resource has been successfully loaded.
248    Loaded,
249    /// Resource failed to load.
250    Error,
251}
252
253/// Preferred execution strategy for handling a single resource request.
254#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
255pub enum ResourceLoadExecution {
256    /// Let loaders choose their default strategy.
257    #[default]
258    Auto,
259    /// Prefer asynchronous loading.
260    Async,
261    /// Prefer synchronous loading.
262    Sync,
263}
264
265/// Per-request options that influence how a resource is loaded.
266#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
267pub struct ResourceLoadOptions {
268    /// Preferred execution strategy for this request.
269    pub execution: ResourceLoadExecution,
270}
271
272impl ResourceLoadOptions {
273    /// Construct options with automatic execution strategy selection.
274    pub const fn auto() -> Self {
275        Self { execution: ResourceLoadExecution::Auto }
276    }
277
278    /// Construct options that prefer asynchronous loading.
279    pub const fn asynchronous() -> Self {
280        Self { execution: ResourceLoadExecution::Async }
281    }
282
283    /// Construct options that prefer synchronous loading.
284    pub const fn synchronous() -> Self {
285        Self { execution: ResourceLoadExecution::Sync }
286    }
287}
288
289/// A resource request that loaders can handle.
290#[non_exhaustive]
291#[derive(Debug, Clone)]
292pub enum ResourceRequest {
293    /// Request to load an image.
294    Image(ImageRequest),
295    /// Request to load a font.
296    Font(FontRequest),
297    /// Request to load a translation file.
298    Translation(TranslationRequest),
299}
300
301impl ResourceRequest {
302    /// Returns the canonical resource path associated with this request.
303    pub fn path(&self) -> &str {
304        match self {
305            ResourceRequest::Image(req) => &req.path,
306            ResourceRequest::Font(req) => &req.path,
307            ResourceRequest::Translation(req) => &req.path,
308        }
309    }
310}
311
312/// A resource request queued for dispatch, paired with loader policy.
313#[derive(Debug, Clone)]
314pub struct QueuedResourceRequest {
315    /// Request payload describing what to load.
316    pub request: ResourceRequest,
317    /// Loader policy describing how to perform the load.
318    pub options: ResourceLoadOptions,
319}
320
321/// Trait for loading resources asynchronously or from various sources.
322///
323/// Loaders are invoked in chain-of-responsibility order when a resource is requested.
324/// Return `true` to indicate the request was handled (no further loaders are tried),
325/// or `false` to continue to the next loader.
326pub trait ResourceLoader: Send + Sync + 'static {
327    /// Attempt to load a resource.
328    ///
329    /// `request` describes what to load, while `options` describes how to load it.
330    /// Return `true` if this loader handled the request, `false` to try the next loader.
331    fn load(
332        &self,
333        request: ResourceRequest,
334        options: ResourceLoadOptions,
335        cx: &mut ResourceContext,
336    ) -> bool;
337
338    /// Query the loading status of a resource path.
339    ///
340    /// Default implementation returns `NotLoaded` — override to track async loading progress.
341    fn status(&self, _path: &str) -> LoadingStatus {
342        LoadingStatus::NotLoaded
343    }
344}
345
346pub(crate) enum ImageOrSvg {
347    Svg(skia_safe::svg::Dom),
348    Image(skia_safe::Image),
349}
350
351pub(crate) struct StoredImage {
352    pub image: ImageOrSvg,
353    pub retention_policy: ImageRetentionPolicy,
354    pub used: bool,
355    pub dirty: bool,
356    pub observers: HashSet<Entity>,
357}
358
359/// An image should be stored in the resource manager.
360#[derive(Debug, Copy, Clone, PartialEq)]
361pub enum ImageRetentionPolicy {
362    ///  The image should live for the entire duration of the application.
363    Forever,
364    /// The image should be dropped when not used for one frame.
365    DropWhenUnusedForOneFrame,
366    /// The image should be dropped when no views are using the image.
367    DropWhenNoObservers,
368}
369
370#[doc(hidden)]
371#[derive(Default)]
372pub struct ResourceManager {
373    pub styles: Vec<Box<dyn IntoCssStr>>,
374
375    pub(crate) image_id_manager: IdManager<ImageId>,
376    pub(crate) images: HashMap<ImageId, StoredImage>,
377    pub(crate) image_ids: HashMap<String, ImageId>,
378    pub(crate) image_sources: HashMap<String, String>,
379
380    pub translations: HashMap<LanguageIdentifier, FluentBundle<FluentResource>>,
381
382    pub language: LanguageIdentifier,
383
384    pub(crate) resource_loaders: Vec<Box<dyn ResourceLoader>>,
385    /// Resource requests waiting to be dispatched through the configured loader chain.
386    pub(crate) pending_requests: Vec<QueuedResourceRequest>,
387    /// Reactive status tracking per resource path.
388    /// Signals allow automatic updates to Memos when status changes.
389    pub(crate) loading_status: HashMap<String, Signal<LoadingStatus>>,
390}
391
392impl ResourceManager {
393    pub fn new() -> Self {
394        // Get the system locale
395        let locale = sys_locale::get_locale().and_then(|l| l.parse().ok()).unwrap_or_default();
396
397        let mut image_id_manager = IdManager::new();
398
399        // Create root id for broken image
400        image_id_manager.create();
401
402        let images = HashMap::new();
403
404        #[cfg(feature = "url-loader")]
405        // Keep file loading ahead of URL loading so local/file:// paths are resolved first.
406        let resource_loaders: Vec<Box<dyn ResourceLoader>> =
407            vec![Box::new(FileResourceLoader), Box::new(UrlResourceLoader::default())];
408
409        #[cfg(not(feature = "url-loader"))]
410        let resource_loaders: Vec<Box<dyn ResourceLoader>> = vec![Box::new(FileResourceLoader)];
411
412        ResourceManager {
413            image_id_manager,
414            images,
415            image_ids: HashMap::new(),
416            image_sources: HashMap::new(),
417            styles: Vec::new(),
418
419            translations: HashMap::from([(
420                LanguageIdentifier::default(),
421                make_bundle(LanguageIdentifier::default()),
422            )]),
423
424            language: locale,
425            resource_loaders,
426            pending_requests: Vec::new(),
427            loading_status: HashMap::new(),
428        }
429    }
430
431    /// Registers a stable image key to source path/URL mapping.
432    pub(crate) fn register_image_source(&mut self, name: String, path: String) {
433        self.image_sources.insert(name, path);
434    }
435
436    /// Resolves an image key to its source path/URL when registered.
437    pub(crate) fn resolve_image_source<'a>(&'a self, name_or_path: &'a str) -> &'a str {
438        self.image_sources.get(name_or_path).map(String::as_str).unwrap_or(name_or_path)
439    }
440
441    pub(crate) fn report_localization_issue(&self, issue: LocalizationIssue) {
442        // Localization issues are non-fatal and intended for diagnostics.
443        log::warn!("{}", issue);
444    }
445
446    pub fn renegotiate_language(&mut self) {
447        let available_native = self
448            .translations
449            .keys()
450            .filter(|&x| x != &LanguageIdentifier::default())
451            .collect::<Vec<_>>();
452        let locale_native = sys_locale::get_locale()
453            .and_then(|l| l.parse().ok())
454            .unwrap_or_else(|| available_native.first().copied().cloned().unwrap_or_default());
455        let available = available_native
456            .iter()
457            .map(|locale| locale.to_string().parse::<fluent_langneg::LanguageIdentifier>())
458            .collect::<Result<Vec<_>, _>>()
459            .expect("unic-langid identifiers must parse as ICU locale identifiers");
460        let locale = locale_native
461            .to_string()
462            .parse::<fluent_langneg::LanguageIdentifier>()
463            .expect("unic-langid identifiers must parse as ICU locale identifiers");
464        let default = LanguageIdentifier::default()
465            .to_string()
466            .parse::<fluent_langneg::LanguageIdentifier>()
467            .expect("default locale must parse as an ICU locale identifier");
468        let langs = fluent_langneg::negotiate::negotiate_languages(
469            &[locale],
470            &available,
471            Some(&default),
472            fluent_langneg::NegotiationStrategy::Filtering,
473        );
474        self.language = langs
475            .first()
476            .expect("language negotiation must return its default locale")
477            .to_string()
478            .parse()
479            .expect("negotiated ICU locale must parse as a unic-langid identifier");
480    }
481
482    fn negotiate_translation_locale(&self, locale: &LanguageIdentifier) -> LanguageIdentifier {
483        if self.translations.contains_key(locale) {
484            return locale.clone();
485        }
486
487        let available = self
488            .translations
489            .keys()
490            .filter(|&lang| lang != &LanguageIdentifier::default())
491            .collect::<Vec<_>>();
492
493        if available.is_empty() {
494            return LanguageIdentifier::default();
495        }
496
497        // Pick a fallback from the registered translations: prefer `self.language` if it
498        // is one of them, otherwise the first registered translation. `available` is
499        // non-empty here (checked above), so `available.first()` is always `Some`.
500        let first_available = *available.first().expect("non-empty checked above");
501        let fallback_native =
502            if available.contains(&&self.language) { &self.language } else { first_available };
503        let available_icu = available
504            .iter()
505            .map(|locale| locale.to_string().parse::<fluent_langneg::LanguageIdentifier>())
506            .collect::<Result<Vec<_>, _>>()
507            .expect("unic-langid identifiers must parse as ICU locale identifiers");
508        let locale_icu = locale
509            .to_string()
510            .parse::<fluent_langneg::LanguageIdentifier>()
511            .expect("unic-langid identifier must parse as an ICU locale identifier");
512        let fallback_icu = fallback_native
513            .to_string()
514            .parse::<fluent_langneg::LanguageIdentifier>()
515            .expect("unic-langid identifier must parse as an ICU locale identifier");
516        let langs = fluent_langneg::negotiate::negotiate_languages(
517            &[locale_icu],
518            &available_icu,
519            Some(&fallback_icu),
520            fluent_langneg::NegotiationStrategy::Filtering,
521        );
522
523        langs
524            .first()
525            .map(|lang| {
526                lang.to_string()
527                    .parse()
528                    .expect("negotiated ICU locale must parse as a unic-langid identifier")
529            })
530            .unwrap_or_else(|| fallback_native.clone())
531    }
532
533    pub fn translation_locales(&self, locale: &LanguageIdentifier) -> Vec<LanguageIdentifier> {
534        let mut locales = Vec::new();
535
536        if self.translations.contains_key(locale) {
537            locales.push(locale.clone());
538        }
539
540        let negotiated = self.negotiate_translation_locale(locale);
541        if !locales.contains(&negotiated) {
542            locales.push(negotiated);
543        }
544
545        let default = LanguageIdentifier::default();
546        if !locales.contains(&default) {
547            locales.push(default);
548        }
549
550        locales
551    }
552
553    pub fn add_translation(
554        &mut self,
555        lang: LanguageIdentifier,
556        ftl: String,
557    ) -> Result<(), TranslationError> {
558        match fluent_bundle::FluentResource::try_new(ftl) {
559            Ok(res) => {
560                let bundle =
561                    self.translations.entry(lang.clone()).or_insert_with(|| make_bundle(lang));
562                bundle.add_resource(res).map_err(|errors| {
563                    let msg = format!("{:?}", errors);
564                    TranslationError::BundleError(msg)
565                })?;
566                self.renegotiate_language();
567                Ok(())
568            }
569            Err((_, parse_errors)) => {
570                let msg =
571                    parse_errors.iter().map(|e| format!("{:?}", e)).collect::<Vec<_>>().join("; ");
572                Err(TranslationError::InvalidFtl(msg))
573            }
574        }
575    }
576
577    pub fn current_translation(
578        &self,
579        locale: &LanguageIdentifier,
580    ) -> &FluentBundle<FluentResource> {
581        let locale = self.translation_locales(locale).into_iter().next().unwrap();
582        self.translations.get(&locale).unwrap()
583    }
584
585    pub fn mark_images_unused(&mut self) {
586        for (_, img) in self.images.iter_mut() {
587            img.used = false;
588        }
589    }
590
591    pub fn evict_unused_images(&mut self) {
592        let rem = self
593            .images
594            .iter()
595            .filter_map(|(id, img)| match img.retention_policy {
596                ImageRetentionPolicy::DropWhenUnusedForOneFrame => (!img.used).then_some(*id),
597
598                ImageRetentionPolicy::DropWhenNoObservers => {
599                    img.observers.is_empty().then_some(*id)
600                }
601
602                ImageRetentionPolicy::Forever => None,
603            })
604            .collect::<Vec<_>>();
605
606        for id in rem {
607            self.images.remove(&id);
608
609            // Collect all name→id mappings that point to this id.
610            let removed_names = self
611                .image_ids
612                .iter()
613                .filter_map(|(name, img_id)| (*img_id == id).then_some(name.clone()))
614                .collect::<Vec<_>>();
615
616            // Remove each name from image_ids and image_sources, recording the resolved
617            // source paths (image_sources maps name→path; for direct-path references the
618            // name IS the path, so fall back to the name itself).
619            let mut source_paths = Vec::new();
620            for name in removed_names {
621                self.image_ids.remove(&name);
622                let source_path = self.image_sources.remove(&name).unwrap_or(name);
623                source_paths.push(source_path);
624            }
625
626            // Clear loading_status for each source path, but only when no remaining
627            // image_sources entry still references it (another name may alias the same path).
628            for source_path in source_paths {
629                if !self.image_sources.values().any(|p| p == &source_path) {
630                    self.loading_status.remove(&source_path);
631                }
632            }
633
634            self.image_id_manager.destroy(id);
635        }
636    }
637
638    /// Query the loading status of a resource path.
639    pub fn resource_status(&self, path: &str) -> LoadingStatus {
640        // First check cached status signal
641        if let Some(signal) = self.loading_status.get(path) {
642            return signal.get();
643        }
644
645        // If not in cache, ask each loader in the chain
646        for loader in &self.resource_loaders {
647            let status = loader.status(path);
648            if status != LoadingStatus::NotLoaded {
649                return status;
650            }
651        }
652
653        LoadingStatus::NotLoaded
654    }
655
656    /// Enqueue a resource request to be handled by the resource system.
657    pub(crate) fn queue_resource_request(
658        &mut self,
659        request: ResourceRequest,
660        options: ResourceLoadOptions,
661    ) {
662        self.pending_requests.push(QueuedResourceRequest { request, options });
663    }
664
665    /// Drain pending resource requests for this frame.
666    pub(crate) fn take_pending_resource_requests(&mut self) -> Vec<QueuedResourceRequest> {
667        std::mem::take(&mut self.pending_requests)
668    }
669
670    /// Update the loading status of a resource path.
671    pub(crate) fn set_resource_status(&mut self, path: impl Into<String>, status: LoadingStatus) {
672        let path = path.into();
673        // Get or create the signal for this path
674        let signal = self.loading_status.entry(path).or_insert_with(|| Signal::new(status));
675        // Update the signal - this will notify any observers (Memos, Bindings)
676        signal.set_if_changed(status);
677    }
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683    use crate::entity::Entity;
684    use hashbrown::HashSet;
685
686    fn test_image() -> skia_safe::Image {
687        skia_safe::Image::from_encoded(unsafe {
688            skia_safe::Data::new_bytes(include_bytes!("../../resources/images/broken_image.png"))
689        })
690        .unwrap()
691    }
692
693    fn stored_image(
694        policy: ImageRetentionPolicy,
695        used: bool,
696        observers: HashSet<Entity>,
697    ) -> StoredImage {
698        StoredImage {
699            image: ImageOrSvg::Image(test_image()),
700            retention_policy: policy,
701            used,
702            dirty: false,
703            observers,
704        }
705    }
706
707    #[test]
708    fn add_translation_returns_error_for_invalid_ftl() {
709        let mut manager = ResourceManager::new();
710
711        // Invalid FTL: unclosed placeable
712        let res = manager.add_translation("en-US".parse().unwrap(), "hello = { $name".to_string());
713
714        assert!(matches!(res, Err(TranslationError::InvalidFtl(_))));
715    }
716
717    #[test]
718    fn translation_locales_prefers_exact_then_default() {
719        let mut manager = ResourceManager::new();
720
721        manager.add_translation("fr".parse().unwrap(), "hello = Bonjour".to_string()).unwrap();
722
723        let locales = manager.translation_locales(&"fr".parse().unwrap());
724
725        assert_eq!(locales.first(), Some(&"fr".parse().unwrap()));
726        assert!(locales.contains(&LanguageIdentifier::default()));
727    }
728
729    #[test]
730    fn translation_locales_falls_back_to_default_when_no_locale_matches() {
731        let manager = ResourceManager::new();
732
733        let locales = manager.translation_locales(&"zz-ZZ".parse().unwrap());
734
735        assert_eq!(locales, vec![LanguageIdentifier::default()]);
736    }
737
738    #[test]
739    fn current_translation_falls_back_to_registered_bundle_when_requested_locale_missing() {
740        let mut manager = ResourceManager::new();
741
742        manager.add_translation("en-US".parse().unwrap(), "hello = Hello".to_string()).unwrap();
743
744        let bundle = manager.current_translation(&"zz-ZZ".parse().unwrap());
745
746        assert!(bundle.get_message("hello").is_some());
747    }
748
749    #[test]
750    fn current_translation_returns_registered_bundle_for_exact_match() {
751        let mut manager = ResourceManager::new();
752
753        manager.add_translation("fr".parse().unwrap(), "hello = Bonjour".to_string()).unwrap();
754
755        let bundle = manager.current_translation(&"fr".parse().unwrap());
756        let message = bundle.get_message("hello");
757
758        assert!(message.is_some());
759    }
760
761    #[test]
762    fn current_translation_returns_empty_default_when_no_translations_registered() {
763        let manager = ResourceManager::new();
764
765        // No `add_translation` call. The only entry in `translations` is the seeded empty
766        // default. A miss must not panic — it falls back to that default bundle.
767        let bundle = manager.current_translation(&"zz-ZZ".parse().unwrap());
768
769        assert!(bundle.get_message("hello").is_none());
770    }
771
772    fn format_datetime(
773        millis: i64,
774        options: &[(&'static str, &'static str)],
775    ) -> FluentValue<'static> {
776        let mut args = FluentArgs::new();
777        for (key, value) in options {
778            args.set(*key, *value);
779        }
780        fluent_datetime(&[FluentValue::from(millis)], &args)
781    }
782
783    fn string_value(text: &str) -> FluentValue<'static> {
784        FluentValue::String(text.to_owned().into())
785    }
786
787    #[test]
788    fn datetime_without_options_uses_the_default_pattern() {
789        assert_eq!(format_datetime(0, &[]), string_value("1970-01-01 00:00:00"));
790        assert_eq!(format_datetime(1_700_000_000_000, &[]), string_value("2023-11-14 22:13:20"));
791    }
792
793    #[test]
794    fn datetime_formats_before_the_epoch_and_drops_sub_second_millis() {
795        assert_eq!(format_datetime(-1, &[]), string_value("1969-12-31 23:59:59"));
796        assert_eq!(format_datetime(1_700_000_000_999, &[]), string_value("2023-11-14 22:13:20"));
797    }
798
799    #[test]
800    fn datetime_formats_date_options() {
801        assert_eq!(
802            format_datetime(
803                1_700_000_000_000,
804                &[("weekday", "long"), ("month", "long"), ("day", "numeric"), ("year", "numeric")],
805            ),
806            string_value("Tuesday November 14 2023")
807        );
808        assert_eq!(
809            format_datetime(
810                1_700_000_000_000,
811                &[
812                    ("weekday", "short"),
813                    ("month", "short"),
814                    ("day", "2-digit"),
815                    ("year", "2-digit")
816                ],
817            ),
818            string_value("Tue Nov 14 23")
819        );
820        assert_eq!(
821            format_datetime(
822                1_704_067_200_000,
823                &[("month", "numeric"), ("day", "numeric"), ("year", "numeric")],
824            ),
825            string_value("1 1 2024")
826        );
827        assert_eq!(
828            format_datetime(
829                1_704_067_200_000,
830                &[("month", "2-digit"), ("day", "2-digit"), ("year", "numeric")],
831            ),
832            string_value("01 01 2024")
833        );
834    }
835
836    #[test]
837    fn datetime_formats_time_options() {
838        assert_eq!(
839            format_datetime(
840                1_704_067_200_000 + (5 * 60 + 7) * 60_000,
841                &[("hour", "numeric"), ("minute", "numeric")],
842            ),
843            string_value("5:7")
844        );
845        assert_eq!(
846            format_datetime(
847                1_704_067_200_000 + (5 * 60 + 7) * 60_000,
848                &[
849                    ("month", "short"),
850                    ("day", "numeric"),
851                    ("hour", "2-digit"),
852                    ("minute", "2-digit")
853                ],
854            ),
855            string_value("Jan 1 05:07")
856        );
857    }
858
859    #[test]
860    fn datetime_accepts_numeric_strings_and_rejects_other_values() {
861        let args = FluentArgs::new();
862        assert_eq!(
863            fluent_datetime(&[string_value("1700000000000")], &args),
864            string_value("2023-11-14 22:13:20")
865        );
866        assert_eq!(
867            fluent_datetime(&[string_value("1.7e12")], &args),
868            string_value("2023-11-14 22:13:20")
869        );
870        assert!(matches!(
871            fluent_datetime(&[string_value("not a number")], &args),
872            FluentValue::Error
873        ));
874        assert!(matches!(fluent_datetime(&[string_value("")], &args), FluentValue::Error));
875        assert!(matches!(fluent_datetime(&[FluentValue::None], &args), FluentValue::Error));
876        assert!(matches!(fluent_datetime(&[], &args), FluentValue::Error));
877    }
878
879    #[test]
880    fn datetime_rejects_milliseconds_outside_the_supported_range() {
881        let args = FluentArgs::new();
882        assert!(matches!(
883            fluent_datetime(&[FluentValue::from(i64::MAX)], &args),
884            FluentValue::Error
885        ));
886        assert!(matches!(
887            fluent_datetime(&[FluentValue::from(i64::MIN)], &args),
888            FluentValue::Error
889        ));
890    }
891
892    #[test]
893    fn datetime_range_ends_at_the_edges_of_a_timestamp() {
894        let max = Timestamp::MAX.as_millisecond();
895        let min = Timestamp::MIN.as_millisecond();
896
897        assert_eq!(format_datetime(max, &[]), string_value("9999-12-30 22:00:00"));
898        assert!(matches!(format_datetime(max + 1, &[]), FluentValue::Error));
899        assert_eq!(format_datetime(min, &[]), string_value("-9999-01-02 01:59:59"));
900        assert!(matches!(format_datetime(min - 1, &[]), FluentValue::Error));
901    }
902
903    #[test]
904    fn datetime_accepts_fractional_milliseconds() {
905        let args = FluentArgs::new();
906        assert_eq!(
907            fluent_datetime(&[FluentValue::from(1_700_000_000_000.5)], &args),
908            string_value("2023-11-14 22:13:20")
909        );
910        assert_eq!(
911            fluent_datetime(&[string_value("1700000000000.5")], &args),
912            string_value("2023-11-14 22:13:20")
913        );
914    }
915
916    #[test]
917    fn datetime_rounds_negative_fractional_milliseconds_toward_negative_infinity() {
918        let args = FluentArgs::new();
919        assert_eq!(
920            fluent_datetime(&[FluentValue::from(-0.5)], &args),
921            string_value("1969-12-31 23:59:59")
922        );
923        assert_eq!(
924            fluent_datetime(&[FluentValue::from(-1_000.5)], &args),
925            string_value("1969-12-31 23:59:58")
926        );
927        assert_eq!(
928            fluent_datetime(&[string_value("-0.5")], &args),
929            string_value("1969-12-31 23:59:59")
930        );
931    }
932
933    #[test]
934    fn datetime_range_edges_apply_to_fractional_milliseconds() {
935        let args = FluentArgs::new();
936        let max = Timestamp::MAX.as_millisecond() as f64;
937        let min = Timestamp::MIN.as_millisecond() as f64;
938
939        assert_eq!(
940            fluent_datetime(&[FluentValue::from(max + 0.5)], &args),
941            string_value("9999-12-30 22:00:00")
942        );
943        assert!(matches!(
944            fluent_datetime(&[FluentValue::from(min - 0.5)], &args),
945            FluentValue::Error
946        ));
947    }
948
949    #[test]
950    fn datetime_rejects_nan() {
951        let args = FluentArgs::new();
952        assert!(matches!(
953            fluent_datetime(&[FluentValue::from(f64::NAN)], &args),
954            FluentValue::Error
955        ));
956        assert!(matches!(fluent_datetime(&[string_value("NaN")], &args), FluentValue::Error));
957    }
958
959    #[test]
960    fn datetime_rejects_infinity() {
961        let args = FluentArgs::new();
962        assert!(matches!(
963            fluent_datetime(&[FluentValue::from(f64::INFINITY)], &args),
964            FluentValue::Error
965        ));
966        assert!(matches!(
967            fluent_datetime(&[FluentValue::from(f64::NEG_INFINITY)], &args),
968            FluentValue::Error
969        ));
970        assert!(matches!(fluent_datetime(&[string_value("inf")], &args), FluentValue::Error));
971        assert!(matches!(fluent_datetime(&[string_value("-inf")], &args), FluentValue::Error));
972    }
973
974    #[test]
975    fn datetime_rejects_the_last_day_of_year_9999() {
976        // 9999-12-31 12:00:00 UTC is past the last instant a timestamp holds.
977        assert!(matches!(format_datetime(253_402_257_600_000, &[]), FluentValue::Error));
978        assert_eq!(format_datetime(253_402_207_199_000, &[]), string_value("9999-12-30 21:59:59"));
979    }
980
981    #[test]
982    fn datetime_formats_negative_years() {
983        // 0000-06-15, -0001-06-15 and -9999-06-15 at noon UTC.
984        let year_zero = -62_152_833_600_000;
985        let year_minus_one = -62_184_456_000_000;
986        let year_minus_9999 = -377_690_817_600_000;
987
988        assert_eq!(format_datetime(year_zero, &[("year", "numeric")]), string_value("0000"));
989        assert_eq!(format_datetime(year_zero, &[("year", "2-digit")]), string_value("00"));
990        assert_eq!(format_datetime(year_minus_one, &[("year", "numeric")]), string_value("-001"));
991        assert_eq!(format_datetime(year_minus_one, &[("year", "2-digit")]), string_value("-1"));
992        assert_eq!(format_datetime(year_minus_9999, &[("year", "numeric")]), string_value("-9999"));
993        assert_eq!(format_datetime(year_minus_9999, &[("year", "2-digit")]), string_value("-99"));
994    }
995
996    #[test]
997    fn number_accepts_numeric_strings_and_rejects_other_values() {
998        let args = FluentArgs::new();
999        assert_eq!(fluent_number(&[string_value("1234")], &args), FluentValue::from(1234.0));
1000        assert_eq!(fluent_number(&[string_value("-12")], &args), FluentValue::from(-12.0));
1001        assert_eq!(fluent_number(&[string_value("1e3")], &args), FluentValue::from(1000.0));
1002        assert!(matches!(fluent_number(&[string_value("abc")], &args), FluentValue::Error));
1003        assert!(matches!(fluent_number(&[string_value("")], &args), FluentValue::Error));
1004        assert!(matches!(fluent_number(&[string_value(" 5")], &args), FluentValue::Error));
1005        assert!(matches!(fluent_number(&[string_value("1,234")], &args), FluentValue::Error));
1006        assert!(matches!(fluent_number(&[FluentValue::None], &args), FluentValue::Error));
1007        assert!(matches!(fluent_number(&[], &args), FluentValue::Error));
1008    }
1009
1010    #[test]
1011    fn number_merges_named_options_into_a_numeric_string() {
1012        let mut args = FluentArgs::new();
1013        args.set("minimumFractionDigits", 3);
1014        let FluentValue::Number(number) = fluent_number(&[string_value("2.5")], &args) else {
1015            panic!("expected a number");
1016        };
1017        assert_eq!(number.as_string(), "2.500");
1018    }
1019
1020    #[test]
1021    fn number_passes_nan_and_infinite_strings_through_like_numbers() {
1022        let args = FluentArgs::new();
1023        let FluentValue::Number(nan) = fluent_number(&[string_value("NaN")], &args) else {
1024            panic!("expected a number");
1025        };
1026        assert!(nan.value.is_nan());
1027        assert_eq!(fluent_number(&[string_value("inf")], &args), FluentValue::from(f64::INFINITY));
1028        assert_eq!(
1029            fluent_number(&[string_value("-inf")], &args),
1030            FluentValue::from(f64::NEG_INFINITY)
1031        );
1032    }
1033
1034    fn format_number_message(ftl: &str, value: &'static str) -> String {
1035        let mut bundle = make_bundle("en-US".parse().unwrap());
1036        bundle.add_resource(FluentResource::try_new(ftl.to_owned()).unwrap()).unwrap();
1037        let mut args = FluentArgs::new();
1038        args.set("value", value);
1039        let pattern = bundle.get_message("message").unwrap().value().unwrap();
1040        let mut errors = Vec::new();
1041        bundle.format_pattern(pattern, Some(&args), &mut errors).into_owned()
1042    }
1043
1044    #[test]
1045    fn number_shows_an_error_in_a_message_for_a_string_that_is_not_a_number() {
1046        let ftl = "message = { NUMBER($value) }";
1047        assert_eq!(format_number_message(ftl, "abc"), "NUMBER()");
1048        assert_eq!(format_number_message(ftl, "42"), "42");
1049    }
1050
1051    #[test]
1052    fn number_selects_the_default_variant_for_a_string_that_is_not_a_number() {
1053        let ftl = "message = { NUMBER($value) ->\n    [0] No items\n   *[other] Some items\n}";
1054        assert_eq!(format_number_message(ftl, "abc"), "Some items");
1055        assert_eq!(format_number_message(ftl, "0"), "No items");
1056    }
1057
1058    #[test]
1059    fn report_localization_issue_does_not_panic() {
1060        let manager = ResourceManager::new();
1061        manager.report_localization_issue(LocalizationIssue::MissingMessage {
1062            key: "missing-key".to_string(),
1063            requested_locale: "en-US".to_string(),
1064        });
1065    }
1066
1067    #[test]
1068    fn evict_unused_images_keeps_used_one_frame_images() {
1069        let mut manager = ResourceManager::new();
1070
1071        let used_id = manager.image_id_manager.create();
1072        manager.images.insert(
1073            used_id,
1074            stored_image(ImageRetentionPolicy::DropWhenUnusedForOneFrame, true, HashSet::new()),
1075        );
1076
1077        let unused_id = manager.image_id_manager.create();
1078        manager.images.insert(
1079            unused_id,
1080            stored_image(ImageRetentionPolicy::DropWhenUnusedForOneFrame, false, HashSet::new()),
1081        );
1082
1083        manager.evict_unused_images();
1084
1085        assert!(manager.images.contains_key(&used_id));
1086        assert!(!manager.images.contains_key(&unused_id));
1087    }
1088
1089    #[test]
1090    fn evict_unused_images_clears_status_for_evicted_paths() {
1091        let mut manager = ResourceManager::new();
1092
1093        let id = manager.image_id_manager.create();
1094        let name = "my-image".to_string();
1095        let path = "test://evicted-image".to_string();
1096
1097        manager.images.insert(
1098            id,
1099            stored_image(ImageRetentionPolicy::DropWhenNoObservers, false, HashSet::new()),
1100        );
1101        // image_ids is keyed by name; image_sources maps name → source path.
1102        manager.image_ids.insert(name.clone(), id);
1103        manager.image_sources.insert(name.clone(), path.clone());
1104        manager.set_resource_status(path.clone(), LoadingStatus::Loaded);
1105
1106        manager.evict_unused_images();
1107
1108        assert!(!manager.image_ids.contains_key(&name));
1109        assert!(!manager.image_sources.contains_key(&name));
1110        assert_eq!(manager.resource_status(&path), LoadingStatus::NotLoaded);
1111    }
1112}