vizia_core 0.4.0

Core components of vizia
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! Resource management for fonts, themes, images, and translations.

mod image_id;

pub use image_id::ImageId;
use vizia_id::{GenerationalId, IdManager};

use crate::context::ResourceContext;
use crate::entity::Entity;
use crate::prelude::IntoCssStr;
// use crate::view::Canvas;
use chrono::{DateTime, Utc};
use fluent_bundle::types::{FluentNumber, FluentNumberOptions};
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue};
use hashbrown::{HashMap, HashSet};
use std::fmt;
use unic_langid::LanguageIdentifier;

/// Error type for translation operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TranslationError {
    /// FTL file syntax is invalid.
    InvalidFtl(String),
    /// Failed to add resource to translation bundle.
    BundleError(String),
}

impl fmt::Display for TranslationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TranslationError::InvalidFtl(msg) => write!(f, "Invalid FTL syntax: {}", msg),
            TranslationError::BundleError(msg) => {
                write!(f, "Failed to add to translation bundle: {}", msg)
            }
        }
    }
}

impl std::error::Error for TranslationError {}

fn fluent_number<'a>(positional: &[FluentValue<'a>], named: &FluentArgs) -> FluentValue<'a> {
    let Some(first) = positional.first() else {
        return FluentValue::Error;
    };

    let mut number = match first {
        FluentValue::Number(num) => num.clone(),
        FluentValue::String(value) => value
            .parse::<FluentNumber>()
            .unwrap_or_else(|_| FluentNumber::new(0.0, FluentNumberOptions::default())),
        _ => return FluentValue::Error,
    };

    number.options.merge(named);
    FluentValue::Number(number)
}

fn style_str(args: &FluentArgs, key: &str) -> Option<String> {
    match args.get(key) {
        Some(FluentValue::String(value)) => Some(value.to_string()),
        _ => None,
    }
}

fn datetime_format_pattern(args: &FluentArgs) -> String {
    let weekday = match style_str(args, "weekday").as_deref() {
        Some("long") => Some("%A"),
        Some("short") => Some("%a"),
        _ => None,
    };

    let month = match style_str(args, "month").as_deref() {
        Some("long") => Some("%B"),
        Some("short") => Some("%b"),
        Some("2-digit") => Some("%m"),
        Some("numeric") => Some("%-m"),
        _ => None,
    };

    let day = match style_str(args, "day").as_deref() {
        Some("2-digit") => Some("%d"),
        Some("numeric") => Some("%-d"),
        _ => None,
    };

    let year = match style_str(args, "year").as_deref() {
        Some("2-digit") => Some("%y"),
        Some("numeric") => Some("%Y"),
        _ => None,
    };

    let hour = match style_str(args, "hour").as_deref() {
        Some("2-digit") => Some("%H"),
        Some("numeric") => Some("%-H"),
        _ => None,
    };

    let minute = match style_str(args, "minute").as_deref() {
        Some("2-digit") => Some("%M"),
        Some("numeric") => Some("%-M"),
        _ => None,
    };

    let mut date_parts = Vec::new();
    if let Some(part) = weekday {
        date_parts.push(part);
    }
    if let Some(part) = month {
        date_parts.push(part);
    }
    if let Some(part) = day {
        date_parts.push(part);
    }
    if let Some(part) = year {
        date_parts.push(part);
    }

    let mut pattern = date_parts.join(" ");
    if hour.is_some() || minute.is_some() {
        if !pattern.is_empty() {
            pattern.push(' ');
        }
        let mut time_parts = Vec::new();
        if let Some(part) = hour {
            time_parts.push(part);
        }
        if let Some(part) = minute {
            time_parts.push(part);
        }
        pattern.push_str(&time_parts.join(":"));
    }

    if pattern.is_empty() { "%Y-%m-%d %H:%M:%S".to_string() } else { pattern }
}

fn fluent_datetime<'a>(positional: &[FluentValue<'a>], named: &FluentArgs) -> FluentValue<'a> {
    let Some(first) = positional.first() else {
        return FluentValue::Error;
    };

    let millis = match first {
        FluentValue::Number(num) => num.value as i64,
        FluentValue::String(value) => value.parse::<i64>().unwrap_or_default(),
        _ => return FluentValue::Error,
    };

    let Some(dt) = DateTime::<Utc>::from_timestamp_millis(millis) else {
        return FluentValue::Error;
    };

    let pattern = datetime_format_pattern(named);
    FluentValue::String(dt.format(&pattern).to_string().into())
}

fn make_bundle(lang: LanguageIdentifier) -> FluentBundle<FluentResource> {
    let mut bundle = FluentBundle::new(vec![lang]);

    bundle.add_function("NUMBER", fluent_number).expect("Failed to register NUMBER function");
    bundle.add_function("DATETIME", fluent_datetime).expect("Failed to register DATETIME function");

    bundle
}

/// Structured diagnostics emitted by localization while resolving messages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum LocalizationIssue {
    /// A message key was not found in any fallback bundle.
    MissingMessage { key: String, requested_locale: String },
    /// A message attribute was not found in any fallback bundle.
    MissingAttribute { key: String, attribute: String, requested_locale: String },
    /// Fluent formatting reported errors while resolving a message.
    FormatError { key: String, locale: String, details: String },
}

impl fmt::Display for LocalizationIssue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LocalizationIssue::MissingMessage { key, requested_locale } => {
                write!(f, "Missing localized message '{}' for locale '{}'.", key, requested_locale)
            }
            LocalizationIssue::MissingAttribute { key, attribute, requested_locale } => write!(
                f,
                "Missing localized attribute '{}.{}' for locale '{}'.",
                key, attribute, requested_locale
            ),
            LocalizationIssue::FormatError { key, locale, details } => {
                write!(f, "Formatting error for key '{}' in locale '{}': {}", key, locale, details)
            }
        }
    }
}

pub(crate) enum ImageOrSvg {
    Svg(skia_safe::svg::Dom),
    Image(skia_safe::Image),
}

pub(crate) struct StoredImage {
    pub image: ImageOrSvg,
    pub retention_policy: ImageRetentionPolicy,
    pub used: bool,
    pub dirty: bool,
    pub observers: HashSet<Entity>,
}

/// An image should be stored in the resource manager.
#[derive(Copy, Clone, PartialEq)]
pub enum ImageRetentionPolicy {
    ///  The image should live for the entire duration of the application.
    Forever,
    /// The image should be dropped when not used for one frame.
    DropWhenUnusedForOneFrame,
    /// The image should be dropped when no views are using the image.
    DropWhenNoObservers,
}

#[doc(hidden)]
#[derive(Default)]
pub struct ResourceManager {
    pub styles: Vec<Box<dyn IntoCssStr>>,

    pub(crate) image_id_manager: IdManager<ImageId>,
    pub(crate) images: HashMap<ImageId, StoredImage>,
    pub(crate) image_ids: HashMap<String, ImageId>,

    pub translations: HashMap<LanguageIdentifier, FluentBundle<FluentResource>>,

    pub language: LanguageIdentifier,

    pub image_loader: Option<Box<dyn Fn(&mut ResourceContext, &str)>>,
}

impl ResourceManager {
    pub fn new() -> Self {
        // Get the system locale
        let locale = sys_locale::get_locale().and_then(|l| l.parse().ok()).unwrap_or_default();

        let default_image_loader: Option<Box<dyn Fn(&mut ResourceContext, &str)>> = None;

        // Disable this for now because reqwest pulls in too many dependencies.
        // let default_image_loader: Option<Box<dyn Fn(&mut ResourceContext, &str)>> =
        //     Some(Box::new(|cx: &mut ResourceContext, path: &str| {
        //         if path.starts_with("https://") {
        //             let path = path.to_string();
        //             cx.spawn(move |cx| {
        //                 let data = reqwest::blocking::get(&path).unwrap().bytes().unwrap();
        //                 cx.load_image(
        //                     path,
        //                     image::load_from_memory_with_format(
        //                         &data,
        //                         image::guess_format(&data).unwrap(),
        //                     )
        //                     .unwrap(),
        //                     ImageRetentionPolicy::DropWhenUnusedForOneFrame,
        //                 )
        //                 .unwrap();
        //             });
        //         } else {
        //             // TODO: Try to load path from file
        //         }
        //     }));

        let mut image_id_manager = IdManager::new();

        // Create root id for broken image
        image_id_manager.create();

        let mut images = HashMap::new();

        images.insert(
            ImageId::root(),
            StoredImage {
                image: ImageOrSvg::Image(
                    skia_safe::Image::from_encoded(unsafe {
                        skia_safe::Data::new_bytes(include_bytes!(
                            "../../resources/images/broken_image.png"
                        ))
                    })
                    .unwrap(),
                ),

                retention_policy: ImageRetentionPolicy::Forever,
                used: true,
                dirty: false,
                observers: HashSet::new(),
            },
        );

        ResourceManager {
            image_id_manager,
            images,
            image_ids: HashMap::new(),
            styles: Vec::new(),

            translations: HashMap::from([(
                LanguageIdentifier::default(),
                make_bundle(LanguageIdentifier::default()),
            )]),

            language: locale,
            image_loader: default_image_loader,
        }
    }

    pub(crate) fn report_localization_issue(&self, issue: LocalizationIssue) {
        // Localization issues are non-fatal and intended for diagnostics.
        log::warn!("{}", issue);
    }

    pub fn renegotiate_language(&mut self) {
        let available = self
            .translations
            .keys()
            .filter(|&x| x != &LanguageIdentifier::default())
            .collect::<Vec<_>>();
        let locale = sys_locale::get_locale()
            .and_then(|l| l.parse().ok())
            .unwrap_or_else(|| available.first().copied().cloned().unwrap_or_default());
        let default = LanguageIdentifier::default();
        let default_ref = &default; // ???
        let langs = fluent_langneg::negotiate::negotiate_languages(
            &[locale],
            &available,
            Some(&default_ref),
            fluent_langneg::NegotiationStrategy::Filtering,
        );
        self.language = (**langs.first().unwrap()).clone();
    }

    fn negotiate_translation_locale(&self, locale: &LanguageIdentifier) -> LanguageIdentifier {
        if self.translations.contains_key(locale) {
            return locale.clone();
        }

        let available = self
            .translations
            .keys()
            .filter(|&lang| lang != &LanguageIdentifier::default())
            .collect::<Vec<_>>();

        if available.is_empty() {
            return LanguageIdentifier::default();
        }

        // Pick a fallback from the registered translations: prefer `self.language` if it
        // is one of them, otherwise the first registered translation. `available` is
        // non-empty here (checked above), so `available.first()` is always `Some`.
        let first_available = *available.first().expect("non-empty checked above");
        let fallback =
            if available.contains(&&self.language) { &self.language } else { first_available };
        let langs = fluent_langneg::negotiate::negotiate_languages(
            &[locale],
            &available,
            Some(&fallback),
            fluent_langneg::NegotiationStrategy::Filtering,
        );

        langs.first().map(|lang| (**lang).clone()).unwrap_or_else(|| fallback.clone())
    }

    pub fn translation_locales(&self, locale: &LanguageIdentifier) -> Vec<LanguageIdentifier> {
        let mut locales = Vec::new();

        if self.translations.contains_key(locale) {
            locales.push(locale.clone());
        }

        let negotiated = self.negotiate_translation_locale(locale);
        if !locales.contains(&negotiated) {
            locales.push(negotiated);
        }

        let default = LanguageIdentifier::default();
        if !locales.contains(&default) {
            locales.push(default);
        }

        locales
    }

    pub fn add_translation(
        &mut self,
        lang: LanguageIdentifier,
        ftl: String,
    ) -> Result<(), TranslationError> {
        match fluent_bundle::FluentResource::try_new(ftl) {
            Ok(res) => {
                let bundle =
                    self.translations.entry(lang.clone()).or_insert_with(|| make_bundle(lang));
                bundle.add_resource(res).map_err(|errors| {
                    let msg = format!("{:?}", errors);
                    TranslationError::BundleError(msg)
                })?;
                self.renegotiate_language();
                Ok(())
            }
            Err((_, parse_errors)) => {
                let msg =
                    parse_errors.iter().map(|e| format!("{:?}", e)).collect::<Vec<_>>().join("; ");
                Err(TranslationError::InvalidFtl(msg))
            }
        }
    }

    pub fn current_translation(
        &self,
        locale: &LanguageIdentifier,
    ) -> &FluentBundle<FluentResource> {
        let locale = self.translation_locales(locale).into_iter().next().unwrap();
        self.translations.get(&locale).unwrap()
    }

    pub fn mark_images_unused(&mut self) {
        for (_, img) in self.images.iter_mut() {
            img.used = false;
        }
    }

    pub fn evict_unused_images(&mut self) {
        let rem = self
            .images
            .iter()
            .filter_map(|(id, img)| match img.retention_policy {
                ImageRetentionPolicy::DropWhenUnusedForOneFrame => (img.used).then_some(*id),

                ImageRetentionPolicy::DropWhenNoObservers => {
                    img.observers.is_empty().then_some(*id)
                }

                ImageRetentionPolicy::Forever => None,
            })
            .collect::<Vec<_>>();

        for id in rem {
            self.images.remove(&id);
            self.image_ids.retain(|_, img| *img != id);
            self.image_id_manager.destroy(id);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn add_translation_returns_error_for_invalid_ftl() {
        let mut manager = ResourceManager::new();

        // Invalid FTL: unclosed placeable
        let res = manager.add_translation("en-US".parse().unwrap(), "hello = { $name".to_string());

        assert!(matches!(res, Err(TranslationError::InvalidFtl(_))));
    }

    #[test]
    fn translation_locales_prefers_exact_then_default() {
        let mut manager = ResourceManager::new();

        manager.add_translation("fr".parse().unwrap(), "hello = Bonjour".to_string()).unwrap();

        let locales = manager.translation_locales(&"fr".parse().unwrap());

        assert_eq!(locales.first(), Some(&"fr".parse().unwrap()));
        assert!(locales.contains(&LanguageIdentifier::default()));
    }

    #[test]
    fn translation_locales_falls_back_to_default_when_no_locale_matches() {
        let manager = ResourceManager::new();

        let locales = manager.translation_locales(&"zz-ZZ".parse().unwrap());

        assert_eq!(locales, vec![LanguageIdentifier::default()]);
    }

    #[test]
    fn current_translation_falls_back_to_registered_bundle_when_requested_locale_missing() {
        let mut manager = ResourceManager::new();

        manager.add_translation("en-US".parse().unwrap(), "hello = Hello".to_string()).unwrap();

        let bundle = manager.current_translation(&"zz-ZZ".parse().unwrap());

        assert!(bundle.get_message("hello").is_some());
    }

    #[test]
    fn current_translation_returns_registered_bundle_for_exact_match() {
        let mut manager = ResourceManager::new();

        manager.add_translation("fr".parse().unwrap(), "hello = Bonjour".to_string()).unwrap();

        let bundle = manager.current_translation(&"fr".parse().unwrap());
        let message = bundle.get_message("hello");

        assert!(message.is_some());
    }

    #[test]
    fn current_translation_returns_empty_default_when_no_translations_registered() {
        let manager = ResourceManager::new();

        // No `add_translation` call. The only entry in `translations` is the seeded empty
        // default. A miss must not panic — it falls back to that default bundle.
        let bundle = manager.current_translation(&"zz-ZZ".parse().unwrap());

        assert!(bundle.get_message("hello").is_none());
    }

    #[test]
    fn report_localization_issue_does_not_panic() {
        let manager = ResourceManager::new();
        manager.report_localization_issue(LocalizationIssue::MissingMessage {
            key: "missing-key".to_string(),
            requested_locale: "en-US".to_string(),
        });
    }
}