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
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
//! Windows NLS-based ICU backend for azul.
//!
//! Replaces ICU4X (which bundles ~3.3 MB of locale data blobs) with Win32 NLS
//! functions dynamically loaded from `kernel32.dll` at first use:
//! `GetNumberFormatEx`, `GetDateFormatEx`, `GetTimeFormatEx`, `CompareStringEx`.
//!
//! List formatting uses a compact language-keyed conjunction table.
//! Plural rules use the same compact CLDR lookup table as the macOS backend.
//!
//! Requires Windows Vista or later (all target functions are Vista+).

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

use azul_css::AzString;

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

// ─── Win32 inline types (no winapi dep needed) ───────────────────────────────

type HMODULE = *mut core::ffi::c_void;

/// Matches the Win32 `SYSTEMTIME` layout exactly.
#[repr(C)]
struct SystemTime {
    year: u16,
    month: u16,
    day_of_week: u16,
    day: u16,
    hour: u16,
    minute: u16,
    second: u16,
    milliseconds: u16,
}

/// Matches the Win32 `NUMBERFMTW` layout exactly.
/// Only used when we need to override the number of decimal digits.
#[repr(C)]
struct NumberFmt {
    num_digits: u32,
    leading_zero: u32,
    grouping: u32,
    decimal_sep: *mut u16,
    thousand_sep: *mut u16,
    negative_order: u32,
}

// ─── Function pointer types ───────────────────────────────────────────────────

type GetNumberFormatExFn = unsafe extern "system" fn(
    lp_locale_name: *const u16,
    dw_flags: u32,
    lp_value: *const u16,
    lp_format: *const NumberFmt,
    lp_number_str: *mut u16,
    cch_number: i32,
) -> i32;

type GetDateFormatExFn = unsafe extern "system" fn(
    lp_locale_name: *const u16,
    dw_flags: u32,
    lp_date: *const SystemTime,
    lp_format: *const u16,
    lp_date_str: *mut u16,
    cch_date: i32,
    lp_calendar: *const u16,
) -> i32;

type GetTimeFormatExFn = unsafe extern "system" fn(
    lp_locale_name: *const u16,
    dw_flags: u32,
    lp_time: *const SystemTime,
    lp_format: *const u16,
    lp_time_str: *mut u16,
    cch_time: i32,
) -> i32;

type CompareStringExFn = unsafe extern "system" fn(
    lp_locale_name: *const u16,
    dw_cmp_flags: u32,
    lp_string1: *const u16,
    cch_count1: i32,
    lp_string2: *const u16,
    cch_count2: i32,
    lp_version_information: *mut core::ffi::c_void,
    lp_reserved: *mut core::ffi::c_void,
    l_param: isize,
) -> i32;

// ─── Kernel32 bootstrap (always available, no dynamic load needed) ────────────

extern "system" {
    fn LoadLibraryW(lp_lib_file_name: *const u16) -> HMODULE;
    fn GetProcAddress(
        h_module: HMODULE,
        lp_proc_name: *const u8,
    ) -> *mut core::ffi::c_void;
}

// ─── Lazy-loaded NLS function table ──────────────────────────────────────────

struct NlsFns {
    get_number_format_ex: GetNumberFormatExFn,
    get_date_format_ex:   GetDateFormatExFn,
    get_time_format_ex:   GetTimeFormatExFn,
    compare_string_ex:    CompareStringExFn,
}

// SAFETY: these are read-only function pointers after initialization.
unsafe impl Send for NlsFns {}
unsafe impl Sync for NlsFns {}

static NLS: OnceLock<Option<NlsFns>> = OnceLock::new();

fn nls() -> Option<&'static NlsFns> {
    NLS.get_or_init(|| {
        // kernel32.dll is always mapped; this just bumps its refcount.
        let name: Vec<u16> = "kernel32.dll\0".encode_utf16().collect();
        let hmod = unsafe { LoadLibraryW(name.as_ptr()) };
        if hmod.is_null() {
            return None;
        }
        macro_rules! sym {
            ($name:literal) => {{
                let ptr = unsafe {
                    GetProcAddress(hmod, concat!($name, "\0").as_ptr())
                };
                if ptr.is_null() {
                    return None;
                }
                unsafe { core::mem::transmute(ptr) }
            }};
        }
        Some(NlsFns {
            get_number_format_ex: sym!("GetNumberFormatEx"),
            get_date_format_ex:   sym!("GetDateFormatEx"),
            get_time_format_ex:   sym!("GetTimeFormatEx"),
            compare_string_ex:    sym!("CompareStringEx"),
        })
    })
    .as_ref()
}

// ─── UTF-16 helpers ───────────────────────────────────────────────────────────

fn to_wide(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(core::iter::once(0)).collect()
}

/// Read a null-terminated UTF-16 output buffer returned by NLS functions.
/// `n` is the return value (chars written including null terminator).
fn from_wide_n(buf: &[u16], n: i32) -> String {
    if n <= 0 {
        return String::new();
    }
    let len = (n as usize).saturating_sub(1); // exclude null
    String::from_utf16_lossy(&buf[..len]).to_string()
}

/// Call an NLS formatting function that fills a buffer.
/// `f(buf_ptr, buf_len) -> chars_written_including_null`
fn fmt_buf(f: impl Fn(*mut u16, i32) -> i32) -> Option<String> {
    let mut buf = vec![0u16; 256];
    let n = f(buf.as_mut_ptr(), buf.len() as i32);
    if n <= 0 { None } else { Some(from_wide_n(&buf, n)) }
}

// ─── Win32 flag constants ─────────────────────────────────────────────────────

const DATE_SHORTDATE:  u32 = 0x0000_0001;
const DATE_LONGDATE:   u32 = 0x0000_0002;
const TIME_NOSECONDS:  u32 = 0x0000_0002;

// CompareStringEx return values (0 = failure)
const CSTR_LESS_THAN:    i32 = 1;
const CSTR_EQUAL:        i32 = 2;
const CSTR_GREATER_THAN: i32 = 3;

// ─── CLDR plural rules ────────────────────────────────────────────────────────
//
// Identical to the table in icu_macos.rs — covers major plural-rule groups
// without bundling any data file.

fn plural_for(n: i64, lang: &str) -> PluralCategory {
    let lang = lang.split(['-', '_']).next().unwrap_or(lang);
    match lang {
        "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 }
        }
        "cy" => match n {
            0 => PluralCategory::Zero,
            1 => PluralCategory::One,
            2 => PluralCategory::Two,
            3 => PluralCategory::Few,
            6 => PluralCategory::Many,
            _ => PluralCategory::Other,
        },
        "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 }
        }
        "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 }
        }
        "cs" | "sk" => {
            if n == 1 { PluralCategory::One }
            else if (2..=4).contains(&n) { PluralCategory::Few }
            else { PluralCategory::Other }
        }
        "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 }
        }
        "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 }
        }
        "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 }
        }
        "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 }
        }
        "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 }
        }
        "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 }
        }
        "ga" => match n {
            1 => PluralCategory::One,
            2 => PluralCategory::Two,
            3..=6 => PluralCategory::Few,
            7..=10 => PluralCategory::Many,
            _ => PluralCategory::Other,
        },
        "fr" | "ff" | "kab" => {
            if n <= 1 { PluralCategory::One } else { PluralCategory::Other }
        }
        _ => if n == 1 { PluralCategory::One } else { PluralCategory::Other },
    }
}

// ─── List formatting helpers ──────────────────────────────────────────────────
//
// Windows has no single NLS API for list formatting.  We use a compact
// hardcoded conjunction table covering the most common languages.

fn conjunction_and(lang: &str) -> &'static str {
    match lang {
        "de" => "und",   "fr" => "et",    "es" => "y",    "it" => "e",
        "pt" => "e",     "nl" => "en",    "ru" => "и",    "uk" => "і",
        "be" => "і",     "pl" => "i",     "cs" => "a",    "sk" => "a",
        "sr" => "и",     "hr" => "i",     "bs" => "i",    "sl" => "in",
        "ro" => "și",    "hu" => "és",    "fi" => "ja",   "et" => "ja",
        "lv" => "un",    "lt" => "ir",    "sv" => "och",  "da" => "og",
        "no" | "nb" | "nn" => "og",
        "tr" => "ve",    "ar" => "و",     "he" => "ו",   "ja" => "",
        "zh" => "",    "ko" => "",    "th" => "และ",
        _ => "and",
    }
}

fn conjunction_or(lang: &str) -> &'static str {
    match lang {
        "de" => "oder",  "fr" => "ou",    "es" => "o",    "it" => "o",
        "pt" => "ou",    "nl" => "of",    "ru" => "или",  "uk" => "або",
        "be" => "або",   "pl" => "lub",   "cs" => "nebo", "sk" => "alebo",
        "sr" => "или",   "hr" => "ili",   "bs" => "ili",  "sl" => "ali",
        "ro" => "sau",   "hu" => "vagy",  "fi" => "tai",  "et" => "või",
        "lv" => "vai",   "lt" => "arba",  "sv" => "eller","da" => "eller",
        "no" | "nb" | "nn" => "eller",
        "tr" => "veya",  "ar" => "أو",    "he" => "או",   "ja" => "",
        "zh" => "",    "ko" => "또는",  "th" => "หรือ",
        _ => "or",
    }
}

fn join_list(items: &[AzString], conjunction: &str) -> String {
    match items.len() {
        0 => String::new(),
        1 => items[0].as_str().to_string(),
        2 => alloc::format!("{} {} {}", items[0].as_str(), conjunction, items[1].as_str()),
        _ => {
            let init: String = items[..items.len() - 1]
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            alloc::format!("{}, {} {}", init, conjunction, items[items.len() - 1].as_str())
        }
    }
}

// ─── NLS collation helper ─────────────────────────────────────────────────────

/// Compare two strings using `CompareStringEx`.
/// Falls back to lexicographic comparison if the NLS call fails (returns 0).
fn compare_nls(f: &NlsFns, locale_wide: &[u16], a: &str, b: &str) -> Ordering {
    let a_w = to_wide(a);
    let b_w = to_wide(b);
    // Pass -1 to let NLS measure the null-terminated strings itself.
    let result = unsafe {
        (f.compare_string_ex)(
            locale_wide.as_ptr(), 0,
            a_w.as_ptr(), -1,
            b_w.as_ptr(), -1,
            core::ptr::null_mut(), core::ptr::null_mut(), 0,
        )
    };
    match result {
        CSTR_LESS_THAN    => Ordering::Less,
        CSTR_EQUAL        => Ordering::Equal,
        CSTR_GREATER_THAN => Ordering::Greater,
        // 0 means the API call failed; fall back to lexicographic order.
        _ => a.cmp(b),
    }
}

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

/// Windows NLS-based locale formatter.
///
/// Delegates number, date/time, and collation to Win32 NLS functions loaded
/// dynamically from `kernel32.dll`.  List formatting uses a compact hardcoded
/// conjunction table.  Plural rules use a compact CLDR lookup table.
/// No ICU data blobs are linked.
#[derive(Debug, Clone)]
pub struct IcuLocalizer {
    locale_string: AzString,
    /// Pre-encoded UTF-16 locale name for NLS calls (cached to avoid re-encoding).
    locale_wide: Vec<u16>,
}

impl IcuLocalizer {
    pub fn new(locale_str: &str) -> Self {
        Self {
            locale_string: AzString::from(locale_str),
            locale_wide: to_wide(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);
        self.locale_wide = to_wide(locale_str);
        true
    }

    pub fn load_data_blob(&mut self, _data: Vec<u8>) {
        // no-op: NLS always uses system locale data
    }

    fn lang(&self) -> &str {
        self.locale_string.as_str()
            .split(['-', '_'])
            .next()
            .unwrap_or("en")
    }

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

    pub fn format_integer(&mut self, value: i64) -> AzString {
        let Some(f) = nls() else {
            return AzString::from(value.to_string());
        };
        // Pass value as string without decimal point → NLS outputs 0 decimal digits.
        let value_w = to_wide(&value.to_string());
        let locale_ptr = self.locale_wide.as_ptr();
        let result = fmt_buf(|buf, len| unsafe {
            (f.get_number_format_ex)(locale_ptr, 0, value_w.as_ptr(), core::ptr::null(), buf, len)
        });
        AzString::from(result.unwrap_or_else(|| value.to_string()))
    }

    pub fn format_decimal(&mut self, integer_part: i64, decimal_places: i16) -> AzString {
        // Build the numeric string with a period as decimal separator (required by NLS).
        let dp = decimal_places.max(0) as usize;
        let v = integer_part as f64 * 10f64.powi(-(decimal_places as i32));
        let value_str = alloc::format!("{v:.dp$}");
        let Some(f) = nls() else {
            return AzString::from(value_str);
        };
        let value_w = to_wide(&value_str);
        let locale_ptr = self.locale_wide.as_ptr();
        let result = fmt_buf(|buf, len| unsafe {
            (f.get_number_format_ex)(locale_ptr, 0, value_w.as_ptr(), core::ptr::null(), buf, len)
        });
        AzString::from(result.unwrap_or(value_str))
    }

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

    pub fn get_plural_category(&mut self, value: i64) -> PluralCategory {
        plural_for(value, self.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 {
        let lang = self.lang();
        let s = match list_type {
            ListType::Unit => items.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "),
            ListType::And  => join_list(items, conjunction_and(lang)),
            ListType::Or   => join_list(items, conjunction_or(lang)),
        };
        AzString::from(s)
    }

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

    pub fn format_date(&mut self, date: IcuDate, length: FormatLength) -> IcuResult {
        let Some(f) = nls() else {
            return IcuResult::err("NLS unavailable");
        };
        let st = SystemTime {
            year: date.year.clamp(1601, 30827) as u16,
            month: date.month as u16,
            day_of_week: 0,
            day: date.day as u16,
            hour: 0, minute: 0, second: 0, milliseconds: 0,
        };
        let flags = match length {
            FormatLength::Short | FormatLength::Medium => DATE_SHORTDATE,
            FormatLength::Long => DATE_LONGDATE,
        };
        let locale_ptr = self.locale_wide.as_ptr();
        match fmt_buf(|buf, len| unsafe {
            (f.get_date_format_ex)(
                locale_ptr, flags, &st,
                core::ptr::null(), buf, len, core::ptr::null(),
            )
        }) {
            Some(s) => IcuResult::ok(s),
            None    => IcuResult::err("GetDateFormatEx failed"),
        }
    }

    pub fn format_time(&mut self, time: IcuTime, include_seconds: bool) -> IcuResult {
        let Some(f) = nls() else {
            return IcuResult::err("NLS unavailable");
        };
        let st = SystemTime {
            year: 2000, month: 1, day_of_week: 0, day: 1,
            hour: time.hour as u16,
            minute: time.minute as u16,
            second: time.second as u16,
            milliseconds: 0,
        };
        let flags = if include_seconds { 0 } else { TIME_NOSECONDS };
        let locale_ptr = self.locale_wide.as_ptr();
        match fmt_buf(|buf, len| unsafe {
            (f.get_time_format_ex)(locale_ptr, flags, &st, core::ptr::null(), buf, len)
        }) {
            Some(s) => IcuResult::ok(s),
            None    => IcuResult::err("GetTimeFormatEx failed"),
        }
    }

    pub fn format_datetime(&mut self, datetime: IcuDateTime, length: FormatLength) -> IcuResult {
        // Windows has no single "date+time" NLS function; format each part separately.
        let date_str = match self.format_date(datetime.date, length) {
            IcuResult::Ok(s) => s,
            e => return e,
        };
        let time_str = match self.format_time(datetime.time, true) {
            IcuResult::Ok(s) => s,
            e => return e,
        };
        IcuResult::ok(alloc::format!("{} {}", date_str.as_str(), time_str.as_str()))
    }

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

    pub fn compare(&mut self, a: &str, b: &str) -> Ordering {
        let Some(f) = nls() else {
            return a.cmp(b);
        };
        compare_nls(f, &self.locale_wide, a, b)
    }

    pub fn sort_strings(&mut self, strings: &mut [AzString]) {
        // Clone the locale_wide to avoid borrow issues inside the closure.
        let locale_wide = self.locale_wide.clone();
        if let Some(f) = nls() {
            strings.sort_by(|a, b| {
                compare_nls(f, &locale_wide, a.as_str(), b.as_str())
            });
        } else {
            strings.sort_by(|a, b| a.as_str().cmp(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
    }

    pub fn get_sort_key(&mut self, s: &str) -> Vec<u8> {
        // NLS sort keys require LCMapStringEx (LCMAP_SORTKEY); not worth the extra
        // dynamic symbol for cache-key use cases.  Return UTF-8 bytes as a proxy.
        s.as_bytes().to_vec()
    }
}

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