azul-layout 0.0.9

Layout solver + font and image loader the Azul GUI framework
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
//! macOS Foundation-based ICU backend for azul.
//!
//! Replaces ICU4X (which bundles ~3.3 MB of locale data blobs) with
//! `NSNumberFormatter`, `NSDateFormatter`, `NSListFormatter`, and
//! `NSString.localizedCompare:` from the system Foundation framework.
//!
//! Plural rules use a compact CLDR lookup table (~2 KB) instead of
//! the ICU segmenter dictionaries.

use alloc::{string::String, vec::Vec};
use core::cmp::Ordering;

use azul_css::AzString;
use objc2::rc::Retained;
use objc2_foundation::{
    NSArray, NSCalendar, NSCalendarIdentifierGregorian, NSDate,
    NSDateComponents, NSDateFormatter, NSDateFormatterStyle, NSListFormatter, NSLocale, NSNumber,
    NSNumberFormatter, NSNumberFormatterStyle, NSString,
};

use super::{FormatLength, IcuDate, IcuDateTime, IcuResult, IcuTime, ListType, PluralCategory};

// ─── CLDR plural rules ───────────────────────────────────────────────────────
//
// Covers the major plural-rule groups defined in CLDR without bundling any
// data file.  Languages not explicitly listed fall back to English rules.

fn plural_for(n: i64, lang: &str) -> PluralCategory {
    let lang = lang.split(['-', '_']).next().unwrap_or(lang);
    match lang {
        // Arabic: six categories
        "ar" | "arz" | "ckb" => {
            let n100 = n.abs() % 100;
            if n == 0 {
                PluralCategory::Zero
            } else if n == 1 {
                PluralCategory::One
            } else if n == 2 {
                PluralCategory::Two
            } else if (3..=10).contains(&n100) {
                PluralCategory::Few
            } else if (11..=99).contains(&n100) {
                PluralCategory::Many
            } else {
                PluralCategory::Other
            }
        }
        // Welsh: six categories
        "cy" => match n {
            0 => PluralCategory::Zero,
            1 => PluralCategory::One,
            2 => PluralCategory::Two,
            3 => PluralCategory::Few,
            6 => PluralCategory::Many,
            _ => PluralCategory::Other,
        },
        // East Slavic (Russian, Ukrainian, Belarusian, Serbian, Croatian, Bosnian)
        "ru" | "uk" | "be" | "sr" | "hr" | "bs" | "sh" => {
            let n10 = n.abs() % 10;
            let n100 = n.abs() % 100;
            if n10 == 1 && n100 != 11 {
                PluralCategory::One
            } else if (2..=4).contains(&n10) && !(12..=14).contains(&n100) {
                PluralCategory::Few
            } else {
                PluralCategory::Many
            }
        }
        // Polish
        "pl" => {
            let n10 = n.abs() % 10;
            let n100 = n.abs() % 100;
            if n == 1 {
                PluralCategory::One
            } else if (2..=4).contains(&n10) && !(12..=14).contains(&n100) {
                PluralCategory::Few
            } else {
                PluralCategory::Many
            }
        }
        // Czech, Slovak
        "cs" | "sk" => {
            if n == 1 {
                PluralCategory::One
            } else if (2..=4).contains(&n) {
                PluralCategory::Few
            } else {
                PluralCategory::Other
            }
        }
        // Slovenian
        "sl" => {
            let n100 = n.abs() % 100;
            if n100 == 1 {
                PluralCategory::One
            } else if n100 == 2 {
                PluralCategory::Two
            } else if (3..=4).contains(&n100) {
                PluralCategory::Few
            } else {
                PluralCategory::Other
            }
        }
        // Lithuanian
        "lt" => {
            let n10 = n.abs() % 10;
            let n100 = n.abs() % 100;
            if n10 == 1 && !(11..=19).contains(&n100) {
                PluralCategory::One
            } else if (2..=9).contains(&n10) && !(11..=19).contains(&n100) {
                PluralCategory::Few
            } else {
                PluralCategory::Other
            }
        }
        // Latvian
        "lv" => {
            let n10 = n.abs() % 10;
            let n100 = n.abs() % 100;
            if n == 0 {
                PluralCategory::Zero
            } else if n10 == 1 && n100 != 11 {
                PluralCategory::One
            } else {
                PluralCategory::Other
            }
        }
        // Romanian
        "ro" | "mo" => {
            let n100 = n.abs() % 100;
            if n == 1 {
                PluralCategory::One
            } else if n == 0 || (1..=19).contains(&n100) {
                PluralCategory::Few
            } else {
                PluralCategory::Other
            }
        }
        // Maltese
        "mt" => {
            let n100 = n.abs() % 100;
            if n == 1 {
                PluralCategory::One
            } else if n == 0 || (2..=10).contains(&n100) {
                PluralCategory::Few
            } else if (11..=19).contains(&n100) {
                PluralCategory::Many
            } else {
                PluralCategory::Other
            }
        }
        // Hebrew / Yiddish
        "he" | "yi" | "iw" => {
            if n == 1 {
                PluralCategory::One
            } else if n == 2 {
                PluralCategory::Two
            } else if n != 0 && n % 10 == 0 {
                PluralCategory::Many
            } else {
                PluralCategory::Other
            }
        }
        // Irish (Gaelic)
        "ga" => match n {
            1 => PluralCategory::One,
            2 => PluralCategory::Two,
            3..=6 => PluralCategory::Few,
            7..=10 => PluralCategory::Many,
            _ => PluralCategory::Other,
        },
        // French, Kabyle: 0 and 1 are "one"
        "fr" | "ff" | "kab" => {
            if n == 0 || n == 1 {
                PluralCategory::One
            } else {
                PluralCategory::Other
            }
        }
        // Default: English-style (exactly 1 → one, everything else → other)
        _ => {
            if n == 1 {
                PluralCategory::One
            } else {
                PluralCategory::Other
            }
        }
    }
}

// ─── IcuLocalizer ─────────────────────────────────────────────────────────────

/// macOS Foundation-based locale formatter.
///
/// Delegates number, date/time, and list formatting to `NSFormatter` classes
/// that ship with the OS.  Plural rules use a compact CLDR lookup table —
/// no ICU data blobs are linked.
#[derive(Debug)]
pub struct IcuLocalizer {
    locale_string: AzString,
}

impl IcuLocalizer {
    pub fn new(locale_str: &str) -> Self {
        Self { locale_string: AzString::from(locale_str) }
    }

    pub fn from_system_language(system_language: &AzString) -> Self {
        Self::new(system_language.as_str())
    }

    pub fn get_locale(&self) -> AzString {
        self.locale_string.clone()
    }

    pub fn get_language(&self) -> AzString {
        let lang = self.locale_string.as_str()
            .split(['-', '_'])
            .next()
            .unwrap_or(self.locale_string.as_str());
        AzString::from(lang)
    }

    pub fn get_region(&self) -> Option<AzString> {
        self.locale_string.as_str().split(['-', '_']).nth(1).map(AzString::from)
    }

    pub fn set_locale(&mut self, locale_str: &str) -> bool {
        self.locale_string = AzString::from(locale_str);
        true
    }

    /// No-op on macOS: Foundation always uses system-provided locale data,
    /// so externally loaded ICU data blobs are not needed and are silently ignored.
    pub fn load_data_blob(&mut self, _data: Vec<u8>) {
        // no-op: Foundation always uses system locale data
    }

    fn make_ns_locale(&self) -> Retained<NSLocale> {
        unsafe {
            let ident = NSString::from_str(self.locale_string.as_str());
            NSLocale::localeWithLocaleIdentifier(&ident)
        }
    }

    // ── Number formatting ───────────────────────────────────────────────────

    pub fn format_integer(&mut self, value: i64) -> AzString {
        unsafe {
            let fmt = NSNumberFormatter::new();
            fmt.setNumberStyle(NSNumberFormatterStyle::DecimalStyle);
            fmt.setLocale(Some(&self.make_ns_locale()));
            let n = NSNumber::new_i64(value);
            fmt.stringFromNumber(&n)
                .map(|s| AzString::from(s.to_string()))
                .unwrap_or_else(|| AzString::from(value.to_string()))
        }
    }

    pub fn format_decimal(&mut self, integer_part: i64, decimal_places: i16) -> AzString {
        let dp = decimal_places.max(0) as usize;
        let value = integer_part as f64 * 10f64.powi(-(decimal_places as i32));
        unsafe {
            let fmt = NSNumberFormatter::new();
            fmt.setNumberStyle(NSNumberFormatterStyle::DecimalStyle);
            fmt.setLocale(Some(&self.make_ns_locale()));
            fmt.setMinimumFractionDigits(dp);
            fmt.setMaximumFractionDigits(dp);
            let n = NSNumber::new_f64(value);
            fmt.stringFromNumber(&n)
                .map(|s| AzString::from(s.to_string()))
                .unwrap_or_else(|| AzString::from(format!("{value:.dp$}")))
        }
    }

    // ── Plural rules ────────────────────────────────────────────────────────

    pub fn get_plural_category(&mut self, value: i64) -> PluralCategory {
        let lang = self.locale_string.as_str()
            .split(['-', '_'])
            .next()
            .unwrap_or("en");
        plural_for(value, lang)
    }

    pub fn pluralize(
        &mut self,
        value: i64,
        zero: &str,
        one: &str,
        two: &str,
        few: &str,
        many: &str,
        other: &str,
    ) -> AzString {
        let template = match self.get_plural_category(value) {
            PluralCategory::Zero => zero,
            PluralCategory::One => one,
            PluralCategory::Two => two,
            PluralCategory::Few => few,
            PluralCategory::Many => many,
            PluralCategory::Other => other,
        };
        AzString::from(template.replace("{}", &value.to_string()))
    }

    // ── List formatting ─────────────────────────────────────────────────────

    pub fn format_list(&mut self, items: &[AzString], list_type: ListType) -> AzString {
        if let ListType::Unit = list_type {
            let strs: Vec<&str> = items.iter().map(|s| s.as_str()).collect();
            return AzString::from(strs.join(", "));
        }
        unsafe {
            let ns_strings: Vec<Retained<NSString>> =
                items.iter().map(|s| NSString::from_str(s.as_str())).collect();
            let refs: Vec<&NSString> = ns_strings.iter().map(|s| s.as_ref()).collect();
            let array = NSArray::from_slice(&refs);
            // NSListFormatter::localizedStringByJoiningStrings is a class method
            // that uses the user's current locale — exactly what we want on macOS.
            let result = NSListFormatter::localizedStringByJoiningStrings(&array);
            AzString::from(result.to_string())
        }
    }

    // ── Date / time formatting ──────────────────────────────────────────────

    pub fn format_date(&mut self, date: IcuDate, length: FormatLength) -> IcuResult {
        unsafe {
            match make_ns_date(date.year, date.month as isize, date.day as isize) {
                None => IcuResult::err("Invalid date"),
                Some(ns_date) => {
                    let fmt = NSDateFormatter::new();
                    fmt.setDateStyle(ns_date_style(length));
                    fmt.setTimeStyle(NSDateFormatterStyle::NoStyle);
                    fmt.setLocale(Some(&self.make_ns_locale()));
                    IcuResult::ok(fmt.stringFromDate(&ns_date).to_string())
                }
            }
        }
    }

    pub fn format_time(&mut self, time: IcuTime, include_seconds: bool) -> IcuResult {
        let style = if include_seconds {
            NSDateFormatterStyle::MediumStyle // HH:MM:SS
        } else {
            NSDateFormatterStyle::ShortStyle // HH:MM
        };
        unsafe {
            match make_ns_time(time.hour as isize, time.minute as isize, time.second as isize) {
                None => IcuResult::err("Invalid time"),
                Some(ns_date) => {
                    let fmt = NSDateFormatter::new();
                    fmt.setDateStyle(NSDateFormatterStyle::NoStyle);
                    fmt.setTimeStyle(style);
                    fmt.setLocale(Some(&self.make_ns_locale()));
                    IcuResult::ok(fmt.stringFromDate(&ns_date).to_string())
                }
            }
        }
    }

    pub fn format_datetime(&mut self, datetime: IcuDateTime, length: FormatLength) -> IcuResult {
        unsafe {
            match make_ns_datetime(
                datetime.date.year,
                datetime.date.month as isize,
                datetime.date.day as isize,
                datetime.time.hour as isize,
                datetime.time.minute as isize,
                datetime.time.second as isize,
            ) {
                None => IcuResult::err("Invalid datetime"),
                Some(ns_date) => {
                    let fmt = NSDateFormatter::new();
                    fmt.setDateStyle(ns_date_style(length));
                    fmt.setTimeStyle(NSDateFormatterStyle::ShortStyle);
                    fmt.setLocale(Some(&self.make_ns_locale()));
                    IcuResult::ok(fmt.stringFromDate(&ns_date).to_string())
                }
            }
        }
    }

    // ── Collation ───────────────────────────────────────────────────────────

    pub fn compare(&mut self, a: &str, b: &str) -> Ordering {
        unsafe {
            let a_ns = NSString::from_str(a);
            let b_ns = NSString::from_str(b);
            Ordering::from(a_ns.localizedCompare(&b_ns))
        }
    }

    pub fn sort_strings(&mut self, strings: &mut [AzString]) {
        strings.sort_by(|a, b| self.compare(a.as_str(), b.as_str()));
    }

    pub fn sorted_strings(&mut self, strings: &[AzString]) -> Vec<AzString> {
        let mut v = strings.to_vec();
        self.sort_strings(&mut v);
        v
    }

    pub fn strings_equal(&mut self, a: &str, b: &str) -> bool {
        self.compare(a, b) == Ordering::Equal
    }

    /// Returns raw UTF-8 bytes of the string as an identity key.
    ///
    /// **Note:** Foundation does not expose raw collation sort keys, so this
    /// does *not* produce locale-aware ordering.  The result is suitable for
    /// identity / cache-key use cases only — it will not sort the same way
    /// as [`compare`](Self::compare).
    pub fn get_sort_key(&mut self, s: &str) -> Vec<u8> {
        s.as_bytes().to_vec()
    }
}

impl Default for IcuLocalizer {
    fn default() -> Self {
        Self::new("en-US")
    }
}

impl Clone for IcuLocalizer {
    fn clone(&self) -> Self {
        Self { locale_string: self.locale_string.clone() }
    }
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

fn ns_date_style(length: FormatLength) -> NSDateFormatterStyle {
    match length {
        FormatLength::Short => NSDateFormatterStyle::ShortStyle,
        FormatLength::Medium => NSDateFormatterStyle::MediumStyle,
        FormatLength::Long => NSDateFormatterStyle::LongStyle,
    }
}

unsafe fn gregorian() -> Option<Retained<NSCalendar>> {
    NSCalendar::calendarWithIdentifier(NSCalendarIdentifierGregorian)
}

unsafe fn make_ns_date(year: i32, month: isize, day: isize) -> Option<Retained<NSDate>> {
    let cal = gregorian()?;
    let c = NSDateComponents::new();
    c.setYear(year as isize);
    c.setMonth(month);
    c.setDay(day);
    cal.dateFromComponents(&c)
}

unsafe fn make_ns_time(hour: isize, minute: isize, second: isize) -> Option<Retained<NSDate>> {
    let cal = gregorian()?;
    let c = NSDateComponents::new();
    // Set a known-good date so dateFromComponents doesn't fail
    // when only time components are provided.
    c.setYear(2000);
    c.setMonth(1);
    c.setDay(1);
    c.setHour(hour);
    c.setMinute(minute);
    c.setSecond(second);
    cal.dateFromComponents(&c)
}

unsafe fn make_ns_datetime(
    year: i32,
    month: isize,
    day: isize,
    hour: isize,
    minute: isize,
    second: isize,
) -> Option<Retained<NSDate>> {
    let cal = gregorian()?;
    let c = NSDateComponents::new();
    c.setYear(year as isize);
    c.setMonth(month);
    c.setDay(day);
    c.setHour(hour);
    c.setMinute(minute);
    c.setSecond(second);
    cal.dateFromComponents(&c)
}