native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
//! Shared localization model (unblocks the `internat` example).
//!
//! Decisions frozen here:
//! - **Fallback chain**: exact tag (`de-at`) → language (`de`) → app default
//!   (exact → language) → the key itself. Missing keys are recorded, never
//!   panics.
//! - **Plural rules** are a deliberately small, deterministic CLDR-lite model:
//!   English-family `one`/`other`, French zero-as-singular, the Slavic
//!   `one`/`few`/`many` modulo sets (Polish and East Slavic differ on the
//!   `one` form), Arabic's six categories, East Asian languages with no
//!   plural distinction, and `other` for everything else. Catalogs declare
//!   the forms they use.
//! - **Number/date formatting** uses per-locale data shipped with this module
//!   (separators and a few date patterns) — platform resource formats are
//!   never hard-wired into the shared API, and unknown input passes through
//!   unchanged.
//! - **Runtime changes** switch the active locale in place; apps re-render the
//!   strings they own (`set_locale` returns whether the locale changed).

use std::collections::{HashMap, HashSet};
use std::fmt;

/// A normalized language tag such as `de-at` or `en`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Locale {
    tag: String,
    language: String,
}

impl Locale {
    /// Parses and normalizes a tag: `_` becomes `-`, everything is
    /// lowercased, and empty input becomes `und` (undetermined).
    pub fn parse(tag: &str) -> Self {
        let normalized = tag.trim().replace('_', "-").to_lowercase();
        let normalized = if normalized.is_empty() {
            "und".to_owned()
        } else {
            normalized
        };
        let language = normalized.split('-').next().unwrap_or("und").to_owned();
        Self {
            tag: normalized,
            language,
        }
    }

    /// The normalized full tag (`de-at`).
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// The language subtag (`de`).
    pub fn language(&self) -> &str {
        &self.language
    }

    /// The region subtag (`at`), when present.
    pub fn region(&self) -> Option<&str> {
        self.tag.split_once('-').map(|(_, region)| region)
    }
}

impl fmt::Display for Locale {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.tag)
    }
}

/// Returns whether a locale conventionally lays out text right-to-left.
pub fn is_rtl_locale(locale: &Locale) -> bool {
    matches!(locale.language(), "ar" | "he" | "fa" | "ur")
}

/// Wraps text in a directional isolate for mixed-direction UI strings.
pub fn isolate_text(locale: &Locale, text: &str) -> String {
    let opener = if is_rtl_locale(locale) {
        '\u{2067}'
    } else {
        '\u{2066}'
    };
    format!("{opener}{text}\u{2069}")
}

/// CLDR-lite plural categories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PluralCategory {
    Zero,
    One,
    Two,
    Few,
    Many,
    Other,
}

impl PluralCategory {
    /// Stable lowercase name, used in catalogs and diagnostics.
    pub fn as_str(&self) -> &'static str {
        match self {
            PluralCategory::Zero => "zero",
            PluralCategory::One => "one",
            PluralCategory::Two => "two",
            PluralCategory::Few => "few",
            PluralCategory::Many => "many",
            PluralCategory::Other => "other",
        }
    }
}

/// Deterministic CLDR-lite plural selection.
///
/// Rules are matched on the language subtag and the absolute count:
///
/// - `en`/`de`/`nl`/`es`/`it`/`pt`/`sv`: `one` for 1, `other` otherwise.
/// - `fr`: `one` for 0 and 1 (French counts zero as a singular), `other` after.
/// - `pl`: `one` (1), `few` (n mod 10 in 2..=4, excluding n mod 100 in
///   12..=14), `many` (everything else — 21 and 101 are `many` in Polish).
/// - `ru`/`uk`: `one` (n mod 10 is 1 and n mod 100 is not 11, so 21 and 101
///   are `one`), `few` (n mod 10 in 2..=4, excluding n mod 100 in 12..=14),
///   `many` (everything else).
/// - `ar`: all six categories — `zero` (0), `one` (1), `two` (2), `few`
///   (n mod 100 in 3..=10), `many` (n mod 100 in 11..=99), `other`.
/// - `ja`/`zh`/`ko`/`th`/`vi`: no plural distinction, always `other`.
/// - Anything else: `other`.
pub fn plural_category(locale: &Locale, count: i64) -> PluralCategory {
    let count = count.unsigned_abs();
    match locale.language() {
        "en" | "de" | "nl" | "es" | "it" | "pt" | "sv" => {
            if count == 1 {
                PluralCategory::One
            } else {
                PluralCategory::Other
            }
        }
        "fr" => {
            if count <= 1 {
                PluralCategory::One
            } else {
                PluralCategory::Other
            }
        }
        "pl" => {
            let last_two = count % 100;
            let last = count % 10;
            if count == 1 {
                PluralCategory::One
            } else if (2..=4).contains(&last) && !(12..=14).contains(&last_two) {
                PluralCategory::Few
            } else {
                PluralCategory::Many
            }
        }
        "ru" | "uk" => {
            let last_two = count % 100;
            let last = count % 10;
            if last == 1 && last_two != 11 {
                PluralCategory::One
            } else if (2..=4).contains(&last) && !(12..=14).contains(&last_two) {
                PluralCategory::Few
            } else {
                PluralCategory::Many
            }
        }
        "ar" => {
            let last_two = count % 100;
            if count == 0 {
                PluralCategory::Zero
            } else if count == 1 {
                PluralCategory::One
            } else if count == 2 {
                PluralCategory::Two
            } else if (3..=10).contains(&last_two) {
                PluralCategory::Few
            } else if (11..=99).contains(&last_two) {
                PluralCategory::Many
            } else {
                PluralCategory::Other
            }
        }
        "ja" | "zh" | "ko" | "th" | "vi" => PluralCategory::Other,
        _ => PluralCategory::Other,
    }
}

/// Deterministic CLDR-lite ordinal plural selection.
///
/// `en`: `one` (1), `two` (2), `few` (3), `other`.
/// `fr`: `one` (1), `other`.
/// `ar`: `one` (1), `two` (2), `few` (n % 100 in 3..=10), `many`
/// (n % 100 in 11..=99), `other` — note the divergence from the cardinal
/// rules: ordinals never select `zero`, so 0 is `other` (cardinal 0 is
/// `zero`) and the category set is five-wide instead of six.
/// Anything else: `other`.
pub fn ordinal_category(locale: &Locale, count: i64) -> PluralCategory {
    let count = count.unsigned_abs();
    match locale.language() {
        "en" => match count {
            1 => PluralCategory::One,
            2 => PluralCategory::Two,
            3 => PluralCategory::Few,
            _ => PluralCategory::Other,
        },
        "fr" => {
            if count == 1 {
                PluralCategory::One
            } else {
                PluralCategory::Other
            }
        }
        "ar" => {
            let last_two = count % 100;
            if count == 1 {
                PluralCategory::One
            } else if count == 2 {
                PluralCategory::Two
            } else if (3..=10).contains(&last_two) {
                PluralCategory::Few
            } else if (11..=99).contains(&last_two) {
                PluralCategory::Many
            } else {
                PluralCategory::Other
            }
        }
        _ => PluralCategory::Other,
    }
}

/// One catalog message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Message {
    /// A single string; `{n}` substitutes the count when one is supplied.
    Simple(String),
    /// Plural forms; the first matching `PluralCategory` for the locale and
    /// count is rendered, with `{n}` substituted.
    Plural(Vec<(PluralCategory, String)>),
}

impl Message {
    fn render(&self, locale: &Locale, count: Option<i64>) -> String {
        match self {
            Message::Simple(text) => match count {
                Some(count) => text.replace("{n}", &count.to_string()),
                None => text.clone(),
            },
            Message::Plural(forms) => {
                let count = count.unwrap_or(0);
                let category = plural_category(locale, count);
                let template = forms
                    .iter()
                    .find(|(form, _)| *form == category)
                    .or_else(|| {
                        forms
                            .iter()
                            .find(|(form, _)| *form == PluralCategory::Other)
                    })
                    .map(|(_, text)| text.as_str())
                    .unwrap_or("");
                template.replace("{n}", &count.to_string())
            }
        }
    }
}

/// Messages for one locale.
#[derive(Debug, Clone, Default)]
pub struct MessageCatalog {
    messages: HashMap<String, Message>,
}

impl MessageCatalog {
    /// Creates an empty catalog.
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts a simple message.
    pub fn insert(&mut self, key: &str, text: &str) {
        self.messages
            .insert(key.to_owned(), Message::Simple(text.to_owned()));
    }

    /// Inserts a plural message; forms are tried in the given order.
    pub fn insert_plural(&mut self, key: &str, forms: &[(PluralCategory, &str)]) {
        self.messages.insert(
            key.to_owned(),
            Message::Plural(
                forms
                    .iter()
                    .map(|(category, text)| (*category, (*text).to_owned()))
                    .collect(),
            ),
        );
    }

    /// Number of stored messages.
    pub fn len(&self) -> usize {
        self.messages.len()
    }

    /// Whether the catalog has no messages.
    pub fn is_empty(&self) -> bool {
        self.messages.is_empty()
    }

    fn get(&self, key: &str) -> Option<&Message> {
        self.messages.get(key)
    }
}

/// Locale-aware lookup and formatting.
#[derive(Debug)]
pub struct Localizer {
    default: Locale,
    current: Locale,
    catalogs: HashMap<String, MessageCatalog>,
    missing: Vec<String>,
    missing_set: HashSet<String>,
}

impl Localizer {
    /// Creates a localizer with a default locale and no catalogs.
    pub fn new(default: Locale) -> Self {
        Self {
            current: default.clone(),
            default,
            catalogs: HashMap::new(),
            missing: Vec::new(),
            missing_set: HashSet::new(),
        }
    }

    /// Registers (or replaces) the catalog for a locale.
    pub fn add_catalog(&mut self, locale: Locale, catalog: MessageCatalog) {
        self.catalogs.insert(locale.tag, catalog);
    }

    /// The active locale.
    pub fn locale(&self) -> &Locale {
        &self.current
    }

    /// The default locale used at the end of the fallback chain.
    pub fn default_locale(&self) -> &Locale {
        &self.default
    }

    /// Switches the active locale; returns `true` when it changed.
    pub fn set_locale(&mut self, locale: Locale) -> bool {
        if self.current == locale {
            false
        } else {
            self.current = locale;
            true
        }
    }

    /// Resolves `key` through the fallback chain: exact tag → language →
    /// default exact → default language → the key itself (recorded as
    /// missing). The key is returned when nothing matches.
    pub fn tr(&mut self, key: &str) -> String {
        if let Some(message) = self.lookup(key, None) {
            return message;
        }
        self.note_missing(key);
        key.to_owned()
    }

    /// Like [`Localizer::tr`] but renders the plural form for `count`.
    pub fn trn(&mut self, key: &str, count: i64) -> String {
        if let Some(message) = self.lookup(key, Some(count)) {
            return message;
        }
        self.note_missing(key);
        format!("{key} ({count})")
    }

    fn lookup(&self, key: &str, count: Option<i64>) -> Option<String> {
        // Borrow the locale tags: cloning four Strings per lookup dominated
        // the call and made every translated label allocate.
        let tags = [
            self.current.tag.as_str(),
            self.current.language.as_str(),
            self.default.tag.as_str(),
            self.default.language.as_str(),
        ];
        for tag in tags {
            if let Some(catalog) = self.catalogs.get(tag) {
                if let Some(message) = catalog.get(key) {
                    return Some(message.render(&self.current, count));
                }
            }
        }
        None
    }

    fn note_missing(&mut self, key: &str) {
        if self.missing_set.insert(key.to_owned()) {
            self.missing.push(key.to_owned());
        }
    }

    /// Missing keys in first-seen order (deduplicated).
    pub fn missing_keys(&self) -> &[String] {
        &self.missing
    }

    /// Clears the missing-key log.
    pub fn clear_missing_keys(&mut self) {
        self.missing.clear();
        self.missing_set.clear();
    }

    /// Formats a number with the active locale's separators.
    ///
    /// Locale data is intentionally small and deterministic: `de`/`es`/`it`/
    /// `pt`/`ru`/`pl` group with `.` and separate decimals with `,`;
    /// `fr` groups with a space; English-style locales group with `,` and
    /// separate decimals with `.`. This is fixture-quality data for tests and
    /// examples, not a full resource-format implementation.
    pub fn format_number(&self, value: f64, decimals: usize) -> String {
        let (group, decimal) = number_separators(self.current.language());
        let negative = value.is_sign_negative() && value != 0.0;
        let rendered = format!("{:.*}", decimals, value.abs());
        let (integer, fraction) = match rendered.split_once('.') {
            Some((integer, fraction)) => (integer.to_owned(), Some(fraction.to_owned())),
            None => (rendered, None),
        };

        let mut grouped = String::new();
        let digits: Vec<char> = integer.chars().collect();
        for (index, digit) in digits.iter().enumerate() {
            if index > 0 && (digits.len() - index).is_multiple_of(3) {
                grouped.push(group);
            }
            grouped.push(*digit);
        }

        let mut result = String::new();
        if negative {
            result.push('-');
        }
        result.push_str(&grouped);
        if let Some(fraction) = fraction {
            result.push(decimal);
            result.push_str(&fraction);
        }
        result
    }

    /// Formats an ISO `YYYY-MM-DD` date with the active locale's pattern:
    /// `en-US` → `MM/DD/YYYY`, other `en` → `DD/MM/YYYY`, `de`/`ru`/`pl` →
    /// `DD.MM.YYYY`, everything else → `DD/MM/YYYY`. Input that is not a
    /// valid ISO date passes through unchanged.
    pub fn format_date(&self, iso_date: &str) -> String {
        let Some((year, month, day)) = parse_iso_date(iso_date) else {
            return iso_date.to_owned();
        };
        match date_pattern(self.current.language(), self.current.region()) {
            DatePattern::MonthDayYear => format!("{month:02}/{day:02}/{year:04}"),
            DatePattern::DayMonthYear => format!("{day:02}/{month:02}/{year:04}"),
            DatePattern::DayMonthYearDotted => format!("{day:02}.{month:02}.{year:04}"),
        }
    }
}

fn number_separators(language: &str) -> (char, char) {
    match language {
        "de" | "es" | "it" | "pt" | "ru" | "pl" => ('.', ','),
        "fr" => (' ', ','),
        _ => (',', '.'),
    }
}

/// Deterministic CLDR-lite collation for UI sorting.
///
/// The default compares case-folded letters by code point, with non-letter
/// characters after the letters. `sv` places `å ä ö` after `z`, and
/// `da`/`nb`/`no` place `æ ø å` after `z` — the documented non-code-point
/// tails this helper exists for. Case-folded equality reports `Equal` so
/// stable sorts keep the caller's order.
pub fn collate(locale: &Locale, left: &str, right: &str) -> std::cmp::Ordering {
    sort_key(locale.language(), left)
        .cmp(&sort_key(locale.language(), right))
        .then_with(|| left.to_lowercase().cmp(&right.to_lowercase()))
}

fn sort_key(language: &str, text: &str) -> Vec<u32> {
    let tail: &[char] = match language {
        "sv" => &['å', 'ä', 'ö'],
        "da" | "nb" | "no" => &['æ', 'ø', 'å'],
        _ => &[],
    };
    text.chars()
        .map(|ch| {
            let lower = ch.to_lowercase().next().unwrap_or(ch);
            if let Some(index) = tail.iter().position(|candidate| *candidate == lower) {
                return 27 + index as u32;
            }
            if lower.is_ascii_lowercase() {
                return (lower as u32 - 'a' as u32) + 1;
            }
            10_000 + lower as u32
        })
        .collect()
}

enum DatePattern {
    MonthDayYear,
    DayMonthYear,
    DayMonthYearDotted,
}

fn date_pattern(language: &str, region: Option<&str>) -> DatePattern {
    match language {
        "en" => match region {
            Some("us") | None => DatePattern::MonthDayYear,
            _ => DatePattern::DayMonthYear,
        },
        "de" | "ru" | "pl" => DatePattern::DayMonthYearDotted,
        _ => DatePattern::DayMonthYear,
    }
}

fn parse_iso_date(iso_date: &str) -> Option<(u32, u32, u32)> {
    let mut parts = iso_date.split('-');
    let year: u32 = parts.next()?.parse().ok()?;
    let month: u32 = parts.next()?.parse().ok()?;
    let day: u32 = parts.next()?.parse().ok()?;
    if parts.next().is_some() || !(1..=12).contains(&month) || !(1..=31).contains(&day) {
        return None;
    }
    Some((year, month, day))
}

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

    #[test]
    fn rtl_detection_and_isolation_are_deterministic() {
        let arabic = Locale::parse("ar-EG");
        let english = Locale::parse("en-US");
        assert!(is_rtl_locale(&arabic));
        assert!(!is_rtl_locale(&english));
        assert_eq!(
            isolate_text(&arabic, "42 files"),
            "\u{2067}42 files\u{2069}"
        );
        assert_eq!(
            isolate_text(&english, "42 ملفات"),
            "\u{2066}42 ملفات\u{2069}"
        );
    }

    fn english() -> MessageCatalog {
        let mut catalog = MessageCatalog::new();
        catalog.insert("greeting", "Hello");
        catalog.insert_plural(
            "files",
            &[
                (PluralCategory::One, "{n} file"),
                (PluralCategory::Other, "{n} files"),
            ],
        );
        catalog
    }

    fn german() -> MessageCatalog {
        let mut catalog = MessageCatalog::new();
        catalog.insert("greeting", "Hallo");
        catalog
    }

    fn polish() -> MessageCatalog {
        let mut catalog = MessageCatalog::new();
        catalog.insert_plural(
            "files",
            &[
                (PluralCategory::One, "{n} plik"),
                (PluralCategory::Few, "{n} pliki"),
                (PluralCategory::Many, "{n} plików"),
            ],
        );
        catalog
    }

    fn arabic() -> MessageCatalog {
        let mut catalog = MessageCatalog::new();
        catalog.insert_plural(
            "files",
            &[
                (PluralCategory::Zero, "لا ملفات"),
                (PluralCategory::One, "ملف واحد"),
                (PluralCategory::Two, "ملفان"),
                (PluralCategory::Few, "{n} ملفات"),
                (PluralCategory::Many, "{n} ملفًا"),
                (PluralCategory::Other, "{n} ملف"),
            ],
        );
        catalog
    }

    #[test]
    fn locale_parsing_normalizes_tags() {
        let locale = Locale::parse("  DE_at ");
        assert_eq!(locale.tag(), "de-at");
        assert_eq!(locale.language(), "de");
        assert_eq!(locale.region(), Some("at"));
        assert_eq!(Locale::parse("").tag(), "und");
        assert_eq!(Locale::parse("en-US").region(), Some("us"));
    }

    #[test]
    fn fallback_chain_prefers_exact_then_language_then_default() {
        let mut localizer = Localizer::new(Locale::parse("en"));
        localizer.add_catalog(Locale::parse("en"), english());
        localizer.add_catalog(Locale::parse("de"), german());
        localizer.set_locale(Locale::parse("de-AT"));

        // de-AT has no catalog: falls back to the `de` language catalog.
        assert_eq!(localizer.tr("greeting"), "Hallo");
        // `files` exists only in the default `en` catalog.
        assert_eq!(localizer.trn("files", 2), "2 files");
        assert!(localizer.missing_keys().is_empty());
    }

    #[test]
    fn untranslated_keys_are_tracked_not_panicked() {
        let mut localizer = Localizer::new(Locale::parse("en"));
        localizer.add_catalog(Locale::parse("en"), english());

        assert_eq!(localizer.tr("missing.key"), "missing.key");
        assert_eq!(localizer.trn("missing.plural", 3), "missing.plural (3)");
        // Duplicates are recorded once, in first-seen order.
        assert_eq!(localizer.tr("missing.key"), "missing.key");
        assert_eq!(
            localizer.missing_keys(),
            &["missing.key".to_owned(), "missing.plural".to_owned()]
        );
        localizer.clear_missing_keys();
        assert!(localizer.missing_keys().is_empty());
    }

    #[test]
    fn runtime_locale_switches_report_changes() {
        let mut localizer = Localizer::new(Locale::parse("en"));
        localizer.add_catalog(Locale::parse("en"), english());
        localizer.add_catalog(Locale::parse("de"), german());

        assert!(localizer.set_locale(Locale::parse("de")));
        assert_eq!(localizer.tr("greeting"), "Hallo");
        assert!(!localizer.set_locale(Locale::parse("DE")));
        assert!(localizer.set_locale(Locale::parse("en-gb")));
        assert_eq!(localizer.tr("greeting"), "Hello");
    }

    #[test]
    fn plural_rules_cover_english_and_slavic_families() {
        let mut localizer = Localizer::new(Locale::parse("en"));
        localizer.add_catalog(Locale::parse("en"), english());
        localizer.add_catalog(Locale::parse("pl"), polish());

        assert_eq!(localizer.trn("files", 1), "1 file");
        assert_eq!(localizer.trn("files", 2), "2 files");

        localizer.set_locale(Locale::parse("pl"));
        assert_eq!(localizer.trn("files", 1), "1 plik");
        assert_eq!(localizer.trn("files", 2), "2 pliki");
        assert_eq!(localizer.trn("files", 5), "5 plików");
        assert_eq!(localizer.trn("files", 12), "12 plików");
        assert_eq!(localizer.trn("files", 22), "22 pliki");
        assert_eq!(
            plural_category(&Locale::parse("xx"), 1),
            PluralCategory::Other
        );
    }

    /// Arabic selects all six CLDR categories.
    #[test]
    fn plural_rules_cover_arabic_six_categories() {
        let ar = Locale::parse("ar");
        assert_eq!(plural_category(&ar, 0), PluralCategory::Zero);
        assert_eq!(plural_category(&ar, 1), PluralCategory::One);
        assert_eq!(plural_category(&ar, 2), PluralCategory::Two);
        for count in [3, 10, 103] {
            assert_eq!(
                plural_category(&ar, count),
                PluralCategory::Few,
                "few: {count}"
            );
        }
        for count in [11, 99, 111] {
            assert_eq!(
                plural_category(&ar, count),
                PluralCategory::Many,
                "many: {count}"
            );
        }
        for count in [100, 101, 102, 200] {
            assert_eq!(
                plural_category(&ar, count),
                PluralCategory::Other,
                "other: {count}"
            );
        }
    }

    /// French treats zero as singular; Spanish does not.
    #[test]
    fn plural_rules_give_french_zero_the_one_form() {
        let fr = Locale::parse("fr");
        assert_eq!(plural_category(&fr, 0), PluralCategory::One);
        assert_eq!(plural_category(&fr, 1), PluralCategory::One);
        assert_eq!(plural_category(&fr, 2), PluralCategory::Other);

        let es = Locale::parse("es");
        assert_eq!(plural_category(&es, 0), PluralCategory::Other);
        assert_eq!(plural_category(&es, 1), PluralCategory::One);
    }

    /// East Asian languages have no plural distinction at all.
    #[test]
    fn plural_rules_cover_east_asian_no_distinction() {
        for tag in ["ja", "zh", "ko", "th", "vi"] {
            let locale = Locale::parse(tag);
            for count in [0, 1, 2, 5, 100] {
                assert_eq!(
                    plural_category(&locale, count),
                    PluralCategory::Other,
                    "{tag}:{count}"
                );
            }
        }
    }

    /// The matcher works on absolute counts, so negative inputs stay sane.
    #[test]
    fn plural_rules_use_absolute_counts() {
        assert_eq!(
            plural_category(&Locale::parse("ar"), -2),
            PluralCategory::Two
        );
        assert_eq!(
            plural_category(&Locale::parse("ru"), -3),
            PluralCategory::Few
        );
        assert_eq!(
            plural_category(&Locale::parse("fr"), -1),
            PluralCategory::One
        );
    }

    /// End to end: an Arabic catalog renders each of the six forms.
    #[test]
    fn arabic_plural_rendering_uses_all_six_forms() {
        let mut localizer = Localizer::new(Locale::parse("ar"));
        localizer.add_catalog(Locale::parse("ar"), arabic());

        assert_eq!(localizer.trn("files", 0), "لا ملفات");
        assert_eq!(localizer.trn("files", 1), "ملف واحد");
        assert_eq!(localizer.trn("files", 2), "ملفان");
        assert_eq!(localizer.trn("files", 4), "4 ملفات");
        assert_eq!(localizer.trn("files", 42), "42 ملفًا");
        assert_eq!(localizer.trn("files", 100), "100 ملف");
        assert!(localizer.missing_keys().is_empty());
    }

    #[test]
    fn number_formatting_uses_locale_separators() {
        let mut localizer = Localizer::new(Locale::parse("en-us"));
        assert_eq!(localizer.format_number(1234.5, 2), "1,234.50");
        assert_eq!(localizer.format_number(-1234567.0, 0), "-1,234,567");

        localizer.set_locale(Locale::parse("de"));
        assert_eq!(localizer.format_number(1234.5, 2), "1.234,50");

        localizer.set_locale(Locale::parse("fr"));
        assert_eq!(localizer.format_number(1234.5, 1), "1 234,5");
    }

    #[test]
    fn date_formatting_uses_locale_patterns_with_passthrough() {
        let mut localizer = Localizer::new(Locale::parse("en-us"));
        assert_eq!(localizer.format_date("2026-09-12"), "09/12/2026");

        localizer.set_locale(Locale::parse("en-gb"));
        assert_eq!(localizer.format_date("2026-09-12"), "12/09/2026");

        localizer.set_locale(Locale::parse("de"));
        assert_eq!(localizer.format_date("2026-09-12"), "12.09.2026");

        // Invalid or non-ISO input passes through unchanged.
        assert_eq!(localizer.format_date("not-a-date"), "not-a-date");
        assert_eq!(localizer.format_date("2026-13-01"), "2026-13-01");
    }

    /// Arabic ordinals never select `zero`; every other
    /// category matches the cardinal classification.
    #[test]
    fn ordinal_rules_diverge_from_cardinals_for_arabic_zero() {
        let ar = Locale::parse("ar_EG");
        assert_eq!(plural_category(&ar, 0), PluralCategory::Zero);
        assert_eq!(ordinal_category(&ar, 0), PluralCategory::Other);
        for (count, cardinal, ordinal) in [
            (1, PluralCategory::One, PluralCategory::One),
            (2, PluralCategory::Two, PluralCategory::Two),
            (3, PluralCategory::Few, PluralCategory::Few),
            (11, PluralCategory::Many, PluralCategory::Many),
            (100, PluralCategory::Other, PluralCategory::Other),
        ] {
            assert_eq!(plural_category(&ar, count), cardinal, "cardinal {count}");
            assert_eq!(ordinal_category(&ar, count), ordinal, "ordinal {count}");
        }
        // Modulo rules use the absolute count like the cardinal rules.
        assert_eq!(ordinal_category(&ar, -103), PluralCategory::Few);
        assert_eq!(
            ordinal_category(&ar, 111),
            PluralCategory::Many,
            "11..=99 modulo 100"
        );

        let en = Locale::parse("en");
        assert_eq!(ordinal_category(&en, 2), PluralCategory::Two);
        assert_eq!(ordinal_category(&en, 3), PluralCategory::Few);
        assert_eq!(ordinal_category(&en, 4), PluralCategory::Other);
        assert_eq!(
            ordinal_category(&Locale::parse("fr"), 1),
            PluralCategory::One
        );
        assert_eq!(
            ordinal_category(&Locale::parse("fr"), 0),
            PluralCategory::Other
        );

        // Rendered ordinals and the bidi helper compose deterministically.
        let mut localizer = Localizer::new(ar.clone());
        let mut catalog = MessageCatalog::new();
        catalog.insert_plural(
            "place",
            &[
                (PluralCategory::Few, "المركز {n}"),
                (PluralCategory::Many, "المركز {n}"),
                (PluralCategory::Other, "المركز {n}"),
            ],
        );
        localizer.add_catalog(ar.clone(), catalog);
        let rendered = localizer.trn("place", 3);
        assert_eq!(rendered, "المركز 3");
        let isolated = isolate_text(&ar, &rendered);
        assert!(
            isolated.starts_with('\u{2067}') && isolated.ends_with('\u{2069}'),
            "Arabic UI strings wrap in a right-to-left isolate"
        );
    }

    /// French zero-as-singular stays consistent when the count
    /// is displayed through the locale's decimal formatter.
    #[test]
    fn french_decimals_interact_with_zero_as_singular() {
        let fr = Locale::parse("fr");
        let mut localizer = Localizer::new(fr.clone());
        let mut catalog = MessageCatalog::new();
        catalog.insert_plural(
            "items",
            &[
                (PluralCategory::One, "{n} article"),
                (PluralCategory::Other, "{n} articles"),
            ],
        );
        localizer.add_catalog(fr, catalog);

        assert_eq!(localizer.trn("items", 0), "0 article", "zero is singular");
        assert_eq!(localizer.trn("items", 1), "1 article");
        assert_eq!(localizer.trn("items", 2), "2 articles");

        // A rounded display count and the plural form agree: 0.4 renders as
        // "0" and therefore selects the singular form.
        assert_eq!(localizer.format_number(0.4, 0), "0");
        let displayed: i64 = localizer
            .format_number(0.4, 0)
            .parse()
            .expect("plain digits");
        assert_eq!(localizer.trn("items", displayed), "0 article");

        // Decimal and grouping separators stay French.
        assert_eq!(localizer.format_number(1.5, 1), "1,5");
        assert_eq!(localizer.format_number(1234.5, 1), "1 234,5");
        assert_eq!(
            localizer.format_number(1.5, 0),
            "2",
            "rounds, not truncates"
        );
    }

    /// Nordic collation tails differ from code-point order.
    #[test]
    fn collation_tailors_nordic_letters_after_z() {
        use std::cmp::Ordering;

        let sv = Locale::parse("sv_SE");
        assert_eq!(collate(&sv, "Zebra", "Ål"), Ordering::Less, "Å after Z");
        assert_eq!(
            collate(&sv, "Ål", "Äppel"),
            Ordering::Less,
            "sv order is Å < Ä < Ö, not code point order"
        );
        assert_eq!(collate(&sv, "Äppel", "Öland"), Ordering::Less);
        assert_eq!(collate(&sv, "Ö", "Ö"), Ordering::Equal);

        let da = Locale::parse("da_DK");
        assert_eq!(
            collate(&da, "Ål", "Æble"),
            Ordering::Greater,
            "da/nb order is Æ < Ø < Å"
        );
        assert_eq!(collate(&da, "Æble", "Øl"), Ordering::Less);

        // The default keeps a stable code-point order after the ASCII
        // letters (no Nordic tail), and case variants tie.
        let en = Locale::parse("en_US");
        assert_eq!(collate(&en, "Zebra", "Ål"), Ordering::Less);
        assert_eq!(collate(&en, "apple", "Apple"), Ordering::Equal);
    }

    /// Polish selects `many` for 21/101 (`one` is exactly
    /// 1), while East Slavic `one` covers every n mod 10 == 1 outside 11.
    #[test]
    fn plural_rules_split_polish_from_east_slavic_one_forms() {
        let pl = Locale::parse("pl");
        assert_eq!(plural_category(&pl, 1), PluralCategory::One);
        for count in [21, 31, 101, 1001] {
            assert_eq!(
                plural_category(&pl, count),
                PluralCategory::Many,
                "pl: {count} takes the many form"
            );
        }
        assert_eq!(plural_category(&pl, 2), PluralCategory::Few);
        assert_eq!(plural_category(&pl, 24), PluralCategory::Few);
        assert_eq!(plural_category(&pl, 12), PluralCategory::Many);
        assert_eq!(plural_category(&pl, 112), PluralCategory::Many);

        for tag in ["ru", "uk"] {
            let locale = Locale::parse(tag);
            for count in [1, 21, 31, 101, 1001] {
                assert_eq!(
                    plural_category(&locale, count),
                    PluralCategory::One,
                    "{tag}: {count} takes the one form"
                );
            }
            for count in [2, 3, 4, 22, 24, 102] {
                assert_eq!(
                    plural_category(&locale, count),
                    PluralCategory::Few,
                    "{tag}: {count}"
                );
            }
            for count in [0, 5, 11, 12, 14, 25, 111, 112] {
                assert_eq!(
                    plural_category(&locale, count),
                    PluralCategory::Many,
                    "{tag}: {count}"
                );
            }
        }
    }

    /// The Romance family is two-form; only French pulls
    /// zero into the singular form, and region tags dispatch on the language.
    #[test]
    fn plural_rules_match_the_romance_family_matrix() {
        for tag in ["es", "it", "pt", "pt-br", "it-ch"] {
            let locale = Locale::parse(tag);
            assert_eq!(
                plural_category(&locale, 0),
                PluralCategory::Other,
                "{tag}: zero is plural"
            );
            assert_eq!(plural_category(&locale, 1), PluralCategory::One, "{tag}");
            assert_eq!(plural_category(&locale, 2), PluralCategory::Other, "{tag}");
        }
        for tag in ["fr", "fr-ca", "fr-ch"] {
            let locale = Locale::parse(tag);
            assert_eq!(
                plural_category(&locale, 0),
                PluralCategory::One,
                "{tag}: zero is singular"
            );
            assert_eq!(plural_category(&locale, 1), PluralCategory::One, "{tag}");
            assert_eq!(plural_category(&locale, 2), PluralCategory::Other, "{tag}");
        }

        // An undetermined tag has no rules of its own, and tags normalize
        // case and region before dispatch.
        assert_eq!(
            plural_category(&Locale::parse("und"), 1),
            PluralCategory::Other
        );
        assert_eq!(
            plural_category(&Locale::parse("AR-eg"), 1),
            PluralCategory::One,
            "region subtags do not change the language rules"
        );
    }

    /// Defensive rendering: a missing category falls back to `other`, and a
    /// plural message with neither the selected category nor `other` renders
    /// empty; `{n}` fills for simple messages too.
    #[test]
    fn plural_forms_fall_back_to_other_when_the_category_is_missing() {
        let mut localizer = Localizer::new(Locale::parse("ar"));
        let mut catalog = MessageCatalog::new();
        catalog.insert_plural("files", &[(PluralCategory::Other, "{n} ملف")]);
        localizer.add_catalog(Locale::parse("ar"), catalog);
        // `few` is not declared: the `other` form renders.
        assert_eq!(localizer.trn("files", 3), "3 ملف");

        // A simple message substitutes `{n}` when a count is supplied.
        let mut simple = MessageCatalog::new();
        simple.insert("units", "{n} units of work");
        localizer.add_catalog(Locale::parse("en"), simple);
        localizer.set_locale(Locale::parse("en"));
        assert_eq!(localizer.trn("units", 5), "5 units of work");

        // Neither the selected category nor `other`: an empty string, not a
        // panic (the key itself is present, so nothing is logged missing).
        let mut bare = MessageCatalog::new();
        bare.insert_plural("items", &[(PluralCategory::One, "one item")]);
        localizer.add_catalog(Locale::parse("ar"), bare);
        localizer.set_locale(Locale::parse("ar"));
        assert_eq!(localizer.trn("items", 5), "");
        assert!(localizer.missing_keys().is_empty());
    }

    /// Ordinal ladders beyond the existing Arabic divergence test: English
    /// stops at 3, French at 1, and unruled locales never leave `other`.
    #[test]
    fn ordinal_rules_cover_english_and_french_ladders() {
        let en = Locale::parse("en");
        assert_eq!(ordinal_category(&en, 1), PluralCategory::One);
        for count in [0, 4, 11, 21, 101] {
            assert_eq!(
                ordinal_category(&en, count),
                PluralCategory::Other,
                "en: {count}"
            );
        }

        let fr = Locale::parse("fr");
        assert_eq!(ordinal_category(&fr, 1), PluralCategory::One);
        for count in [0, 2, 21] {
            assert_eq!(
                ordinal_category(&fr, count),
                PluralCategory::Other,
                "fr: {count}"
            );
        }

        assert_eq!(
            ordinal_category(&Locale::parse("de"), 1),
            PluralCategory::Other,
            "German has no ordinal rules in this model"
        );
    }

    /// Absolute-count selection flows through rendering: negative counts take
    /// their positive category and display their sign.
    #[test]
    fn negative_counts_render_with_their_absolute_category_end_to_end() {
        let mut localizer = Localizer::new(Locale::parse("ru"));
        let mut russian = MessageCatalog::new();
        russian.insert_plural(
            "files",
            &[
                (PluralCategory::One, "{n} файл"),
                (PluralCategory::Few, "{n} файла"),
                (PluralCategory::Many, "{n} файлов"),
            ],
        );
        localizer.add_catalog(Locale::parse("ru"), russian);
        assert_eq!(localizer.trn("files", -21), "-21 файл");
        assert_eq!(localizer.trn("files", -3), "-3 файла");
        assert_eq!(localizer.trn("files", -11), "-11 файлов");

        localizer.add_catalog(Locale::parse("ar"), arabic());
        localizer.set_locale(Locale::parse("ar"));
        assert_eq!(localizer.trn("files", -2), "ملفان", "dual form");
        assert_eq!(localizer.trn("files", -4), "-4 ملفات", "few form");
    }
}