1
//! Discovers system-native styling for colors, fonts, and other metrics.
2
//!
3
//! This module provides a best-effort attempt to query the host operating system
4
//! for its UI theme information. This is gated behind the **`io`** feature flag.
5
//!
6
//! **End-user customization (`AZ_RICING`):**
7
//! By default (if the `io` feature is enabled), Azul looks for an
8
//! application-specific stylesheet at `~/.config/azul/styles/<app_name>.css`
9
//! (or `%APPDATA%\azul\styles\<app_name>.css` on Windows) and applies it as
10
//! the last layer of the cascade, letting end-users "rice" any Azul app.
11
//!
12
//! The `AZ_RICING` env var has three modes (case-insensitive):
13
//!
14
//! - unset (default): load the user CSS if present; on Linux, the detection chain is `KDE > GNOME >
15
//!   riced > defaults`.
16
//! - `AZ_RICING=off` (aliases: `disabled`, `none`, `0`): skip the user CSS file and the
17
//!   riced-desktop sources (Hyprland config, pywal cache). Use for kiosk builds or CI runs that
18
//!   mustn't pick up local customization.
19
//! - `AZ_RICING=force` (aliases: `prefer`, `aggressive`, `1`): on Linux, reorder the detection
20
//!   chain so riced-desktop sources win over GNOME/KDE — useful for tiling-WM users whose
21
//!   `XDG_CURRENT_DESKTOP` still says `gnome`. The user CSS file still loads.
22

            
23
#![cfg(feature = "parser")]
24

            
25
use alloc::{
26
    boxed::Box,
27
    string::{String, ToString},
28
    vec::Vec,
29
};
30
use core::fmt::Write;
31

            
32
use crate::{
33
    corety::{AzString, OptionF32, OptionString, OptionU16},
34
    css::Css,
35
    dynamic_selector::{BoolCondition, OsVersion},
36
    parser2::{new_from_str, CssParseWarnMsg},
37
    props::{
38
        basic::{
39
            color::{parse_css_color, ColorU, OptionColorU},
40
            pixel::{OptionPixelValue, PixelValue},
41
        },
42
        style::scrollbar::{
43
            ComputedScrollbarStyle, OverscrollBehavior, ScrollBehavior, ScrollPhysics,
44
        },
45
    },
46
};
47

            
48
// --- End-user customization mode ---
49

            
50
/// User-customization mode controlled by the `AZ_RICING` env var.
51
///
52
/// See the module-level documentation for the full description.
53
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54
pub enum RicingMode {
55
    /// `AZ_RICING=off` (or `disabled` / `none` / `0`). Skip the user
56
    /// CSS file *and* the riced-desktop sources. Vanilla detection.
57
    Off,
58
    /// Unset. Load the user CSS if present; standard detection chain
59
    /// (`KDE > GNOME > riced > defaults` on Linux).
60
    #[default]
61
    Default,
62
    /// `AZ_RICING=force` (or `prefer` / `aggressive` / `1`). Reorder
63
    /// the Linux detection chain so riced-desktop sources win over
64
    /// GNOME/KDE. The user CSS file still loads.
65
    Force,
66
}
67

            
68
/// Read the `AZ_RICING` env var and classify it. Case-insensitive.
69
/// Anything we don't recognise falls through to `Default` so a typo
70
/// degrades gracefully instead of disabling the feature silently.
71
#[must_use]
72
6
pub fn ricing_mode() -> RicingMode {
73
6
    let Ok(raw) = std::env::var("AZ_RICING") else {
74
6
        return RicingMode::Default;
75
    };
76
    match raw.trim().to_ascii_lowercase().as_str() {
77
        "off" | "disabled" | "none" | "0" | "false" => RicingMode::Off,
78
        "force" | "prefer" | "aggressive" | "1" | "true" => RicingMode::Force,
79
        _ => RicingMode::Default,
80
    }
81
6
}
82

            
83
/// True when the user CSS file at `~/.config/azul/styles/<app>.css`
84
/// should be read. False only when `AZ_RICING=off` is set.
85
#[must_use]
86
3
pub fn ricing_enabled() -> bool {
87
3
    !matches!(ricing_mode(), RicingMode::Off)
88
3
}
89

            
90
/// Force a freshly discovered [`SystemStyle`] to the polarity `AZ_THEME`
91
/// pins, swapping in `light` / `dark` as the replacement palette.
92
///
93
/// `AZ_THEME=light|dark` exists so a screenshot or a reftest renders the same
94
/// on any machine. It used to pin only the CASCADE (`@theme` blocks, via
95
/// `dynamic_selector::theme_pinned_by_env`) and the WINDOW theme — but the
96
/// window BACKGROUND, the "is this a full regeneration" decision and the
97
/// display list's no-context fallback all read `SystemStyle` instead. On a
98
/// dark desktop `AZ_THEME=light` therefore rendered light-theme TEXT on the
99
/// desktop's DARK background: unreadable, and shipped to the website as the
100
/// "light" screenshot of the Linux build. A pin that does not reach here is
101
/// not a pin.
102
///
103
/// Only the polarity-dependent visuals move — the palette, the focus ring and
104
/// the scrollbar. The desktop's fonts, metrics, icon and cursor themes are
105
/// what make a capture look like the platform it was taken on, and none of
106
/// them have a light/dark polarity to disagree about. `light` and `dark` are
107
/// closures so the caller picks the palette family that matches what it just
108
/// discovered — Breeze on a KDE session, Adwaita on GNOME — and so neither is
109
/// built when nothing is pinned, which is every normal run.
110
pub fn apply_env_theme_pin(
111
    style: &mut SystemStyle,
112
    light: impl FnOnce() -> SystemStyle,
113
    dark: impl FnOnce() -> SystemStyle,
114
) {
115
    use crate::dynamic_selector::ThemeCondition;
116

            
117
    let Some(pin) = crate::dynamic_selector::theme_pinned_by_env() else {
118
        return;
119
    };
120
    let wanted = match pin {
121
        ThemeCondition::Dark => Theme::Dark,
122
        _ => Theme::Light,
123
    };
124
    if style.theme == wanted {
125
        return;
126
    }
127
    adopt_theme_palette(style, wanted, light, dark);
128
}
129

            
130
/// Gives `style` the palette of `wanted`, keeping non-polar fields and the accent, even if `style.theme` already matches.
131
pub fn adopt_theme_palette(
132
    style: &mut SystemStyle,
133
    wanted: Theme,
134
    light: impl FnOnce() -> SystemStyle,
135
    dark: impl FnOnce() -> SystemStyle,
136
) {
137
    let mut replacement = match wanted {
138
        Theme::Dark => dark(),
139
        Theme::Light => light(),
140
    };
141

            
142
    // An EXPLICIT list of what has a polarity, not "replace the struct and put
143
    // a few things back". These callers run the pin at the END of discovery,
144
    // after `platform`, `language`, `os_version`, the accessibility flags and
145
    // the user's ricing stylesheet have all been filled in, and a wholesale
146
    // replacement would quietly reset every one of them to whatever the
147
    // built-in palette carries.
148
    style.theme = replacement.theme;
149
    style.focus_visuals = replacement.focus_visuals;
150
    // `SystemStyle` implements `Drop` (the FFI double-drop guard), so the one
151
    // boxed field here has to be TAKEN rather than moved out of `replacement`.
152
    style.scrollbar = core::mem::take(&mut replacement.scrollbar);
153

            
154
    // The ACCENT survives: it is the one colour the user picked themselves,
155
    // it is a hue rather than a polarity, and both desktops that report one
156
    // (KDE, the XDG portal) report it independently of light/dark.
157
    let accent = style.colors.accent;
158
    style.colors = replacement.colors;
159
    if accent.is_some() {
160
        style.colors.accent = accent;
161
    }
162
}
163

            
164
// --- Public Data Structures ---
165
#[allow(variant_size_differences)]
166
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
167
// disparity accepted
168
/// Represents the detected platform.
169
#[derive(Debug, Default, Clone, PartialEq, Eq)]
170
#[repr(C, u8)]
171
pub enum Platform {
172
    Windows,
173
    MacOs,
174
    Linux(DesktopEnvironment),
175
    Android,
176
    Ios,
177
    #[default]
178
    Unknown,
179
}
180

            
181
impl Platform {
182
    /// Get the current platform at compile time.
183
    #[inline]
184
    #[must_use]
185
15806
    pub const fn current() -> Self {
186
        #[cfg(target_os = "macos")]
187
        {
188
            Self::MacOs
189
        }
190
        #[cfg(target_os = "windows")]
191
        {
192
            Self::Windows
193
        }
194
        #[cfg(target_os = "linux")]
195
        {
196
15806
            Self::Linux(DesktopEnvironment::Other(AzString::from_const_str(
197
15806
                "unknown",
198
15806
            )))
199
        }
200
        #[cfg(target_os = "android")]
201
        {
202
            Self::Android
203
        }
204
        #[cfg(target_os = "ios")]
205
        {
206
            Self::Ios
207
        }
208
        #[cfg(not(any(
209
            target_os = "macos",
210
            target_os = "windows",
211
            target_os = "linux",
212
            target_os = "android",
213
            target_os = "ios"
214
        )))]
215
        {
216
            Self::Unknown
217
        }
218
15806
    }
219
}
220
#[allow(variant_size_differences)]
221
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
222
// disparity accepted
223
/// Represents the detected Linux Desktop Environment.
224
#[derive(Debug, Clone, PartialEq, Eq)]
225
#[repr(C, u8)]
226
pub enum DesktopEnvironment {
227
    Gnome,
228
    Kde,
229
    Other(AzString),
230
}
231

            
232
/// The overall theme type.
233
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
234
#[repr(C)]
235
pub enum Theme {
236
    #[default]
237
    Light,
238
    Dark,
239
}
240

            
241
/// A unified collection of discovered system style properties.
242
#[derive(Debug, Clone, PartialEq)]
243
#[repr(C)]
244
pub struct SystemStyle {
245
    pub fonts: SystemFonts,
246
    pub metrics: SystemMetrics,
247
    /// Linux-specific customisation (icon theme, cursor theme, GTK theme, ...)
248
    pub linux: LinuxCustomization,
249
    pub platform: Platform,
250
    /// Focus ring / indicator visual style
251
    pub focus_visuals: FocusVisuals,
252
    /// System language/locale in BCP 47 format (e.g., "en-US", "de-DE")
253
    /// Detected from OS settings at startup
254
    pub language: AzString,
255
    /// An optional, user-provided stylesheet loaded from a conventional
256
    /// location (`~/.config/azul/styles/<app_name>.css`), allowing for
257
    /// application-specific "ricing". Only loaded when the "io" feature
258
    /// is enabled and `AZ_RICING` is not set to `off`.
259
    pub app_specific_stylesheet: Option<Box<Css>>,
260
    /// Scrollbar style information (boxed to ensure stable FFI size)
261
    pub scrollbar: Option<Box<ComputedScrollbarStyle>>,
262
    /// Global scroll physics configuration (momentum, friction, rubber-banding).
263
    /// Platform-specific defaults are applied during system style discovery.
264
    /// Applications can override this to change the "feel" of scrolling globally.
265
    pub scroll_physics: ScrollPhysics,
266
    pub theme: Theme,
267
    /// Detected OS version (e.g., Windows 11 22H2, macOS Sonoma, etc.)
268
    pub os_version: OsVersion,
269
    /// User prefers reduced motion (accessibility setting)
270
    pub prefers_reduced_motion: BoolCondition,
271
    /// User prefers high contrast (accessibility setting)
272
    pub prefers_high_contrast: BoolCondition,
273
    /// Detailed accessibility settings (superset of `prefers_reduced_motion` /
274
    /// `prefers_high_contrast`)
275
    pub accessibility: AccessibilitySettings,
276
    /// Which hand the user operates the device with. Touch UIs put their
277
    /// primary controls on that side so the thumb reaches them.
278
    ///
279
    /// This is INDEPENDENT of text direction: an Arabic left-hander reads
280
    /// right-to-left but still reaches with the left hand, and a
281
    /// left-handed English user reads left-to-right. Deriving one from the
282
    /// other is a bug, so they are separate settings.
283
    pub handedness: Handedness,
284
    /// Input interaction timing / distance thresholds from the OS
285
    pub input: InputMetrics,
286
    /// Text rendering / anti-aliasing hints from the OS
287
    pub text_rendering: TextRenderingHints,
288
    /// OS-level scrollbar visibility / click-behaviour preferences
289
    pub scrollbar_preferences: ScrollbarPreferences,
290
    /// Visual hints: icons in menus/buttons, toolbar style, tooltips
291
    pub visual_hints: VisualHints,
292
    /// Animation enable/disable, speed factor, focus indicator behaviour
293
    pub animation: AnimationMetrics,
294
    pub colors: SystemColors,
295
    /// Icon-specific styling options (grayscale, tinting, etc.)
296
    pub icon_style: IconStyleOptions,
297
    /// Audio feedback preferences (event sounds, input sounds)
298
    pub audio: AudioMetrics,
299
    /// FFI double-drop guard. `SystemStyle` owns two heap pointers
300
    /// (`app_specific_stylesheet`, `scrollbar`). The codegen Az wrapper
301
    /// (`AzSystemStyle`) gets an `impl Drop` -> `AzSystemStyle_delete` ->
302
    /// `drop_in_place::<SystemStyle>`, and is nested by value as
303
    /// `AzAppConfig.system_style`. Dropping an `AzAppConfig` by value
304
    /// therefore drops the real `SystemStyle` once (freeing both Boxes) and
305
    /// then re-runs `_delete` on the SAME bytes via drop-glue -> double free.
306
    /// Same class as `GlContextPtr` / `IconProviderHandle` (see core/src/icon.rs).
307
    /// The first `Drop` disarms this flag; the second sees it cleared and
308
    /// neutralizes itself (takes + forgets the already-freed Boxes) so the
309
    /// redundant drop-glue is a no-op. Defaults to `true` (own + free once).
310
    pub run_destructor: bool,
311
}
312

            
313
impl Default for SystemStyle {
314
65721
    fn default() -> Self {
315
65721
        Self {
316
65721
            fonts: SystemFonts::default(),
317
65721
            metrics: SystemMetrics::default(),
318
65721
            linux: LinuxCustomization::default(),
319
65721
            platform: Platform::default(),
320
65721
            focus_visuals: FocusVisuals::default(),
321
65721
            handedness: Handedness::default(),
322
65721
            language: AzString::default(),
323
65721
            app_specific_stylesheet: None,
324
65721
            scrollbar: None,
325
65721
            scroll_physics: ScrollPhysics::default(),
326
65721
            theme: Theme::default(),
327
65721
            os_version: OsVersion::default(),
328
65721
            prefers_reduced_motion: BoolCondition::default(),
329
65721
            prefers_high_contrast: BoolCondition::default(),
330
65721
            accessibility: AccessibilitySettings::default(),
331
65721
            input: InputMetrics::default(),
332
65721
            text_rendering: TextRenderingHints::default(),
333
65721
            scrollbar_preferences: ScrollbarPreferences::default(),
334
65721
            visual_hints: VisualHints::default(),
335
65721
            animation: AnimationMetrics::default(),
336
65721
            colors: SystemColors::default(),
337
65721
            icon_style: IconStyleOptions::default(),
338
65721
            audio: AudioMetrics::default(),
339
65721
            run_destructor: true,
340
65721
        }
341
65721
    }
342
}
343

            
344
impl Drop for SystemStyle {
345
66570
    fn drop(&mut self) {
346
        // Gate the heap frees on `run_destructor` to defuse the codegen
347
        // double-drop (see the `run_destructor` field docs). drop_in_place
348
        // runs THIS method, then the field drop-glue; so:
349
        //  * FIRST drop (flag set): disarm the flag, then let the field drop-glue free the two
350
        //    Boxes exactly once.
351
        //  * SECOND drop on the same bytes (flag cleared by the first): the Boxes are already freed
352
        //    but the fields still hold dangling `Some(ptr)`. Take them out (-> None) and forget the
353
        //    dangling values so the trailing drop-glue is a no-op (never derefs/frees).
354
66570
        if self.run_destructor {
355
66570
            self.run_destructor = false;
356
66570
        } else {
357
            core::mem::forget(self.app_specific_stylesheet.take());
358
            core::mem::forget(self.scrollbar.take());
359
        }
360
66570
    }
361
}
362

            
363
/// Icon-specific styling options for accessibility and theming.
364
///
365
/// These settings affect how icons are rendered, supporting accessibility
366
/// needs like reduced colors and high contrast modes.
367
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
368
#[repr(C)]
369
pub struct IconStyleOptions {
370
    /// If true, icons should be rendered in grayscale (for color-blind users
371
    /// or reduced color preference). Applies a CSS grayscale filter.
372
    pub prefer_grayscale: bool,
373
    /// Optional tint color to apply to icons. Useful for matching icons
374
    /// to the current theme or for high contrast modes.
375
    pub tint_color: OptionColorU,
376
    /// If true, icons should inherit the current text color instead of
377
    /// using their original colors. Works well with font-based icons.
378
    pub inherit_text_color: bool,
379
}
380

            
381
/// System font types that can be resolved at runtime based on OS settings.
382
///
383
/// This enum allows specifying semantic font roles that get resolved to
384
/// actual font families based on the current platform and user preferences.
385
/// For example, `Monospace` resolves to:
386
/// - macOS: SF Mono or Menlo
387
/// - Windows: Cascadia Mono or Consolas
388
/// - Linux: Ubuntu Mono or `DejaVu` Sans Mono
389
///
390
/// Font variants (bold, italic) can be combined with the base type.
391
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
392
#[repr(C)]
393
pub enum SystemFontType {
394
    /// UI font for buttons, labels, menus (SF Pro, Segoe UI, Cantarell)
395
    #[default]
396
    Ui,
397
    /// Bold variant of UI font
398
    UiBold,
399
    /// Monospace font for code (SF Mono, Consolas, Ubuntu Mono)
400
    Monospace,
401
    /// Bold variant of monospace font
402
    MonospaceBold,
403
    /// Italic variant of monospace font
404
    MonospaceItalic,
405
    /// Font for window titles
406
    Title,
407
    /// Bold variant of title font
408
    TitleBold,
409
    /// Font for menu items
410
    Menu,
411
    /// Small/caption font
412
    Small,
413
    /// Serif font for reading content (New York on macOS, Georgia on Windows)
414
    Serif,
415
    /// Bold variant of serif font
416
    SerifBold,
417
}
418

            
419
impl SystemFontType {
420
    /// Parse a `SystemFontType` from a CSS string.
421
    ///
422
    /// Supported formats:
423
    /// - `system:ui`, `system:ui:bold`
424
    /// - `system:monospace`, `system:monospace:bold`, `system:monospace:italic`
425
    /// - `system:title`, `system:title:bold`
426
    /// - `system:menu`
427
    /// - `system:small`
428
    /// - `system:serif`, `system:serif:bold`
429
    #[must_use]
430
18238
    pub fn from_css_str(s: &str) -> Option<Self> {
431
18238
        let s = s.trim();
432
18238
        if !s.starts_with("system:") {
433
15813
            return None;
434
2425
        }
435
2425
        let rest = &s[7..]; // Skip "system:"
436
2425
        match rest {
437
2425
            "ui" => Some(Self::Ui),
438
98
            "ui:bold" => Some(Self::UiBold),
439
80
            "monospace" => Some(Self::Monospace),
440
74
            "monospace:bold" => Some(Self::MonospaceBold),
441
68
            "monospace:italic" => Some(Self::MonospaceItalic),
442
61
            "title" => Some(Self::Title),
443
56
            "title:bold" => Some(Self::TitleBold),
444
51
            "menu" => Some(Self::Menu),
445
46
            "small" => Some(Self::Small),
446
41
            "serif" => Some(Self::Serif),
447
36
            "serif:bold" => Some(Self::SerifBold),
448
31
            _ => None,
449
        }
450
18238
    }
451

            
452
    /// Get the CSS syntax for this system font type.
453
    #[must_use]
454
59
    pub const fn as_css_str(&self) -> &'static str {
455
59
        match self {
456
8
            Self::Ui => "system:ui",
457
5
            Self::UiBold => "system:ui:bold",
458
5
            Self::Monospace => "system:monospace",
459
6
            Self::MonospaceBold => "system:monospace:bold",
460
5
            Self::MonospaceItalic => "system:monospace:italic",
461
5
            Self::Title => "system:title",
462
5
            Self::TitleBold => "system:title:bold",
463
5
            Self::Menu => "system:menu",
464
5
            Self::Small => "system:small",
465
5
            Self::Serif => "system:serif",
466
5
            Self::SerifBold => "system:serif:bold",
467
        }
468
59
    }
469

            
470
    /// Returns true if this system font type implies bold weight.
471
    /// Used when resolving system fonts to pass the correct weight to fontconfig.
472
    #[must_use]
473
1930
    pub const fn is_bold(&self) -> bool {
474
1906
        matches!(
475
1930
            self,
476
            Self::UiBold | Self::MonospaceBold | Self::TitleBold | Self::SerifBold
477
        )
478
1930
    }
479

            
480
    /// Returns true if this system font type implies italic style.
481
    #[must_use]
482
1934
    pub const fn is_italic(&self) -> bool {
483
1934
        matches!(self, Self::MonospaceItalic)
484
1934
    }
485
}
486

            
487
/// Accessibility settings detected from the operating system.
488
///
489
/// These settings allow apps to adapt their UI for users with accessibility needs.
490
/// Detection methods:
491
/// - macOS: `UIAccessibility` APIs (isBoldTextEnabled, isReduceMotionEnabled, etc.)
492
/// - Windows: `SystemParametersInfo` (`SPI_GETHIGHCONTRAST`, `SPI_GETCLIENTAREAANIMATION`)
493
/// - Linux: gsettings (org.gnome.desktop.interface, org.gnome.desktop.a11y)
494
#[derive(Debug, Default, Clone, Copy, PartialEq)]
495
#[repr(C)]
496
pub struct AccessibilitySettings {
497
    /// Text scaling factor (1.0 = normal, 1.5 = 150%, etc.)
498
    pub text_scale_factor: f32,
499
    /// User prefers bold text for better readability
500
    /// macOS: UIAccessibility.isBoldTextEnabled
501
    /// Windows: N/A (font scaling)
502
    /// Linux: org.gnome.desktop.interface text-scaling-factor
503
    pub prefers_bold_text: bool,
504
    /// User prefers larger text
505
    /// macOS: preferredContentSizeCategory
506
    /// Windows: `SystemParametersInfo` text scale factor
507
    /// Linux: org.gnome.desktop.interface text-scaling-factor
508
    pub prefers_larger_text: bool,
509
    /// User prefers high contrast colors
510
    /// macOS: UIAccessibility.isDarkerSystemColorsEnabled
511
    /// Windows: `SPI_GETHIGHCONTRAST`
512
    /// Linux: org.gnome.desktop.a11y.interface high-contrast
513
    pub prefers_high_contrast: bool,
514
    /// User prefers reduced motion/animations
515
    /// macOS: UIAccessibility.isReduceMotionEnabled
516
    /// Windows: `SPI_GETCLIENTAREAANIMATION` (inverted)
517
    /// Linux: org.gnome.desktop.interface enable-animations (inverted)
518
    pub prefers_reduced_motion: bool,
519
    /// User prefers reduced transparency
520
    /// macOS: UIAccessibility.isReduceTransparencyEnabled
521
    /// Windows: N/A
522
    /// Linux: N/A
523
    pub prefers_reduced_transparency: bool,
524
    /// Screen reader is active (`VoiceOver`, Narrator, Orca)
525
    pub screen_reader_active: bool,
526
    /// User prefers differentiate without color
527
    /// macOS: UIAccessibility.shouldDifferentiateWithoutColor
528
    pub differentiate_without_color: bool,
529
}
530

            
531
/// Common system colors used for UI elements.
532
///
533
/// These colors are queried from the operating system and automatically adapt
534
/// to the current theme (light/dark mode) and accent color settings.
535
///
536
/// On macOS, these correspond to `NSColor` semantic colors.
537
/// On Windows, these come from `UISettings`.
538
/// On Linux/GTK, these come from the GTK theme.
539
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
540
#[repr(C)]
541
pub struct SystemColors {
542
    // === Primary semantic colors ===
543
    /// Primary text color (NSColor.textColor on macOS)
544
    pub text: OptionColorU,
545
    /// Secondary text color for less prominent text (NSColor.secondaryLabelColor)
546
    pub secondary_text: OptionColorU,
547
    /// Tertiary text color for disabled/placeholder text (NSColor.tertiaryLabelColor)
548
    pub tertiary_text: OptionColorU,
549
    /// Background color for content areas (NSColor.textBackgroundColor)
550
    pub background: OptionColorU,
551

            
552
    // === Accent colors ===
553
    /// System accent color chosen by user (NSColor.controlAccentColor on macOS)
554
    pub accent: OptionColorU,
555
    /// Text color on accent backgrounds
556
    pub accent_text: OptionColorU,
557

            
558
    // === Control colors ===
559
    /// Button/control background (NSColor.controlColor)
560
    pub button_face: OptionColorU,
561
    /// Button/control text color (NSColor.controlTextColor)
562
    pub button_text: OptionColorU,
563
    /// Disabled control text color (NSColor.disabledControlTextColor)
564
    pub disabled_text: OptionColorU,
565

            
566
    // === Window colors ===
567
    /// Window background color (NSColor.windowBackgroundColor)
568
    pub window_background: OptionColorU,
569
    /// Under-page background color (NSColor.underPageBackgroundColor)
570
    pub under_page_background: OptionColorU,
571

            
572
    // === Selection colors ===
573
    /// Selection background when window is focused (NSColor.selectedContentBackgroundColor)
574
    pub selection_background: OptionColorU,
575
    /// Selection text color when window is focused
576
    pub selection_text: OptionColorU,
577
    /// Selection background when window is NOT focused
578
    /// (NSColor.unemphasizedSelectedContentBackgroundColor) This is used for :backdrop state
579
    /// styling
580
    pub selection_background_inactive: OptionColorU,
581
    /// Selection text color when window is NOT focused
582
    pub selection_text_inactive: OptionColorU,
583

            
584
    // === Additional semantic colors ===
585
    /// Link color (NSColor.linkColor)
586
    pub link: OptionColorU,
587
    /// Separator/divider color (NSColor.separatorColor)
588
    pub separator: OptionColorU,
589
    /// Grid/table line color (NSColor.gridColor)
590
    pub grid: OptionColorU,
591
    /// Find/search highlight color (NSColor.findHighlightColor)
592
    pub find_highlight: OptionColorU,
593

            
594
    // === Sidebar colors (macOS-specific) ===
595
    /// Sidebar background color
596
    pub sidebar_background: OptionColorU,
597
    /// Selected row in sidebar
598
    pub sidebar_selection: OptionColorU,
599
}
600

            
601
/// Common system font settings.
602
///
603
/// On macOS, these are queried from `NSFont`.
604
/// On Windows, these come from `SystemParametersInfo`.
605
/// On Linux, these come from GTK/gsettings.
606
#[derive(Debug, Default, Clone, PartialEq, Eq)]
607
#[repr(C)]
608
pub struct SystemFonts {
609
    /// The primary font used for UI elements like buttons and labels.
610
    /// On macOS: SF Pro (system font)
611
    /// On Windows: Segoe UI
612
    /// On Linux: Cantarell, Ubuntu, or system default
613
    pub ui_font: OptionString,
614
    /// The default font size for UI elements, in points.
615
    pub ui_font_size: OptionF32,
616
    /// The font used for code or other monospaced text.
617
    /// On macOS: SF Mono or Menlo
618
    /// On Windows: Cascadia Mono or Consolas
619
    /// On Linux: Ubuntu Mono or `DejaVu` Sans Mono
620
    pub monospace_font: OptionString,
621
    /// Monospace font size in points
622
    pub monospace_font_size: OptionF32,
623
    /// Bold variant of the UI font (if different)
624
    pub ui_font_bold: OptionString,
625
    /// Font for window titles
626
    pub title_font: OptionString,
627
    /// Title font size in points
628
    pub title_font_size: OptionF32,
629
    /// Font for menu items
630
    pub menu_font: OptionString,
631
    /// Menu font size in points
632
    pub menu_font_size: OptionF32,
633
    /// Small/caption font for less prominent text
634
    pub small_font: OptionString,
635
    /// Small font size in points
636
    pub small_font_size: OptionF32,
637
}
638

            
639
/// Common system metrics for UI element sizing and spacing.
640
#[derive(Debug, Default, Clone, PartialEq, Eq)]
641
#[repr(C)]
642
pub struct SystemMetrics {
643
    /// The corner radius for standard elements like buttons.
644
    pub corner_radius: OptionPixelValue,
645
    /// The width of standard borders.
646
    pub border_width: OptionPixelValue,
647
    /// The horizontal (left/right) padding for buttons and similar controls.
648
    pub button_padding_horizontal: OptionPixelValue,
649
    /// The vertical (top/bottom) padding for buttons and similar controls.
650
    pub button_padding_vertical: OptionPixelValue,
651
    /// Titlebar layout information (button positions, safe areas, etc.)
652
    pub titlebar: TitlebarMetrics,
653
}
654

            
655
/// Which side of the titlebar the window control buttons are on.
656
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
657
#[repr(C)]
658
pub enum TitlebarButtonSide {
659
    /// Buttons are on the left (macOS default)
660
    Left,
661
    /// Buttons are on the right (Windows, most Linux DEs)
662
    #[default]
663
    Right,
664
}
665

            
666
/// Which window control buttons are available in the titlebar.
667
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
668
#[repr(C)]
669
pub struct TitlebarButtons {
670
    /// Close button is available
671
    pub has_close: bool,
672
    /// Minimize button is available
673
    pub has_minimize: bool,
674
    /// Maximize/zoom button is available
675
    pub has_maximize: bool,
676
    /// Fullscreen button is available (macOS green button behavior)
677
    pub has_fullscreen: bool,
678
}
679

            
680
impl Default for TitlebarButtons {
681
66570
    fn default() -> Self {
682
66570
        Self {
683
66570
            has_close: true,
684
66570
            has_minimize: true,
685
66570
            has_maximize: true,
686
66570
            has_fullscreen: false,
687
66570
        }
688
66570
    }
689
}
690

            
691
/// Safe area insets for devices with notches, rounded corners, or sensor housings.
692
///
693
/// On devices like iPhones with notches or Dynamic Island, the safe area
694
/// indicates regions where content should not be placed to avoid being
695
/// obscured by hardware features.
696
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
697
#[repr(C)]
698
pub struct SafeAreaInsets {
699
    /// Inset from the top edge (notch, camera housing, etc.)
700
    pub top: OptionPixelValue,
701
    /// Inset from the bottom edge (home indicator on iPhone)
702
    pub bottom: OptionPixelValue,
703
    /// Inset from the left edge (rounded corners)
704
    pub left: OptionPixelValue,
705
    /// Inset from the right edge (rounded corners)
706
    pub right: OptionPixelValue,
707
    /// How much of the window the on-screen keyboard currently covers, from
708
    /// the bottom edge. APPENDED for ABI stability.
709
    ///
710
    /// Deliberately NOT folded into `bottom`. The two have different
711
    /// lifetimes and different meanings: `bottom` is the home indicator and is
712
    /// fixed for the life of the window, while this appears and disappears and
713
    /// is animated by the OS. An app that adds them together gets the right
714
    /// answer; one that needs to know why its content shrank cannot recover
715
    /// that from a single number.
716
    ///
717
    /// `None` on desktop and whenever no keyboard is up. Android reports it as
718
    /// `WindowInsets.Type.ime()`, iOS as the intersection of
719
    /// `UIKeyboardFrameEndUserInfoKey` with the view.
720
    pub keyboard: OptionPixelValue,
721
}
722

            
723
/// Metrics for titlebar layout and window chrome.
724
///
725
/// This provides information needed to correctly position custom titlebar
726
/// content when using `WindowDecorations::NoTitle` (expanded title mode).
727
#[derive(Debug, Clone, PartialEq, Eq)]
728
#[repr(C)]
729
pub struct TitlebarMetrics {
730
    /// Which side the window control buttons are on
731
    pub button_side: TitlebarButtonSide,
732
    /// Which buttons are available
733
    pub buttons: TitlebarButtons,
734
    /// Height of the titlebar in pixels
735
    pub height: OptionPixelValue,
736
    /// Width reserved for window control buttons (close/min/max)
737
    /// This is the space to avoid when drawing custom title text
738
    pub button_area_width: OptionPixelValue,
739
    /// Horizontal padding inside the titlebar
740
    pub padding_horizontal: OptionPixelValue,
741
    /// Safe area insets for notched/rounded displays
742
    pub safe_area: SafeAreaInsets,
743
    /// Title text font (from `SystemFonts::title_font`)
744
    pub title_font: OptionString,
745
    /// Title text font size
746
    pub title_font_size: OptionF32,
747
    /// Title text font weight (400 = normal, 600 = semibold, 700 = bold)
748
    pub title_font_weight: OptionU16,
749
    /// The titlebar's own background while the window HAS focus.
750
    ///
751
    /// A titlebar is not painted in the window background: every desktop gives
752
    /// it its own pair of colours and dims them when focus leaves (KDE keeps
753
    /// them in `Colors:Header` and `[Colors:Header][Inactive]`). Without these
754
    /// a client-side decoration can match the platform's geometry and still
755
    /// read as foreign, because the one surface the user compares against the
756
    /// neighbouring native windows is the wrong colour.
757
    pub background_active: OptionColorU,
758
    /// The titlebar's background while the window does NOT have focus.
759
    pub background_inactive: OptionColorU,
760
    /// Title text colour while focused.
761
    pub text_active: OptionColorU,
762
    /// Title text colour while unfocused.
763
    pub text_inactive: OptionColorU,
764
    /// Background a window-control button takes on hover.
765
    pub button_hover_background: OptionColorU,
766
    /// Background the CLOSE button takes on hover — its own colour on every
767
    /// platform (Breeze and Windows both go red), which is why it is not
768
    /// folded into `button_hover_background`.
769
    pub close_button_hover_background: OptionColorU,
770
}
771

            
772
impl Default for TitlebarMetrics {
773
65764
    fn default() -> Self {
774
65764
        Self {
775
65764
            button_side: TitlebarButtonSide::Right,
776
65764
            buttons: TitlebarButtons::default(),
777
65764
            // None = "not detected", like title_font above: SystemMetrics::default()
778
65764
            // must be able to represent an unknown titlebar so PixelValueOrSystem's
779
65764
            // resolve() falls back to system detection instead of these hardcoded
780
65764
            // guesses. (The concrete px values pinned the fallback path unreachable.)
781
65764
            height: OptionPixelValue::None,
782
65764
            button_area_width: OptionPixelValue::None,
783
65764
            padding_horizontal: OptionPixelValue::None,
784
65764
            safe_area: SafeAreaInsets::default(),
785
65764
            title_font: OptionString::None,
786
65764
            title_font_size: OptionF32::Some(13.0),
787
65764
            title_font_weight: OptionU16::Some(600), // Semibold
788
65764
            background_active: OptionColorU::None,
789
65764
            background_inactive: OptionColorU::None,
790
65764
            text_active: OptionColorU::None,
791
65764
            text_inactive: OptionColorU::None,
792
65764
            button_hover_background: OptionColorU::None,
793
65764
            close_button_hover_background: OptionColorU::None,
794
65764
        }
795
65764
    }
796
}
797

            
798
impl TitlebarMetrics {
799
    /// Windows-style titlebar (buttons on right)
800
    #[must_use]
801
86
    pub fn windows() -> Self {
802
86
        Self {
803
86
            button_side: TitlebarButtonSide::Right,
804
86
            buttons: TitlebarButtons {
805
86
                has_close: true,
806
86
                has_minimize: true,
807
86
                has_maximize: true,
808
86
                has_fullscreen: false,
809
86
            },
810
86
            height: OptionPixelValue::Some(PixelValue::px(32.0)),
811
86
            button_area_width: OptionPixelValue::Some(PixelValue::px(138.0)), // 3 buttons * 46px
812
86
            padding_horizontal: OptionPixelValue::Some(PixelValue::px(8.0)),
813
86
            safe_area: SafeAreaInsets::default(),
814
86
            title_font: OptionString::Some("Segoe UI Variable Text".into()),
815
86
            title_font_size: OptionF32::Some(12.0),
816
86
            title_font_weight: OptionU16::Some(400), // Normal
817
86
            background_active: OptionColorU::None,
818
86
            background_inactive: OptionColorU::None,
819
86
            text_active: OptionColorU::None,
820
86
            text_inactive: OptionColorU::None,
821
86
            button_hover_background: OptionColorU::None,
822
86
            close_button_hover_background: OptionColorU::None,
823
86
        }
824
86
    }
825

            
826
    /// macOS-style titlebar (buttons on left, "traffic lights")
827
    #[must_use]
828
27
    pub fn macos() -> Self {
829
27
        Self {
830
27
            button_side: TitlebarButtonSide::Left,
831
27
            buttons: TitlebarButtons {
832
27
                has_close: true,
833
27
                has_minimize: true,
834
27
                has_maximize: false, // macOS has fullscreen instead
835
27
                has_fullscreen: true,
836
27
            },
837
27
            height: OptionPixelValue::Some(PixelValue::px(28.0)),
838
27
            button_area_width: OptionPixelValue::Some(PixelValue::px(78.0)), // 3 buttons with gaps
839
27
            padding_horizontal: OptionPixelValue::Some(PixelValue::px(8.0)),
840
27
            safe_area: SafeAreaInsets::default(),
841
27
            title_font: OptionString::Some(".SF NS".into()),
842
27
            title_font_size: OptionF32::Some(13.0),
843
27
            title_font_weight: OptionU16::Some(600), // Semibold
844
27
            background_active: OptionColorU::None,
845
27
            background_inactive: OptionColorU::None,
846
27
            text_active: OptionColorU::None,
847
27
            text_inactive: OptionColorU::None,
848
27
            button_hover_background: OptionColorU::None,
849
27
            close_button_hover_background: OptionColorU::None,
850
27
        }
851
27
    }
852

            
853
    /// Linux GNOME-style titlebar (buttons on right by default)
854
    #[must_use]
855
241
    pub fn linux_gnome() -> Self {
856
241
        Self {
857
241
            button_side: TitlebarButtonSide::Right, // Default, can be changed in settings
858
241
            buttons: TitlebarButtons {
859
241
                has_close: true,
860
241
                has_minimize: true,
861
241
                has_maximize: true,
862
241
                has_fullscreen: false,
863
241
            },
864
241
            height: OptionPixelValue::Some(PixelValue::px(35.0)),
865
241
            button_area_width: OptionPixelValue::Some(PixelValue::px(100.0)),
866
241
            padding_horizontal: OptionPixelValue::Some(PixelValue::px(12.0)),
867
241
            safe_area: SafeAreaInsets::default(),
868
241
            title_font: OptionString::Some("Cantarell".into()),
869
241
            title_font_size: OptionF32::Some(11.0),
870
241
            title_font_weight: OptionU16::Some(700), // Bold
871
241
            background_active: OptionColorU::None,
872
241
            background_inactive: OptionColorU::None,
873
241
            text_active: OptionColorU::None,
874
241
            text_inactive: OptionColorU::None,
875
241
            button_hover_background: OptionColorU::None,
876
241
            close_button_hover_background: OptionColorU::None,
877
241
        }
878
241
    }
879

            
880
    /// iOS-style safe area (for notched devices)
881
    #[must_use]
882
9
    pub fn ios() -> Self {
883
9
        Self {
884
9
            button_side: TitlebarButtonSide::Left,
885
9
            buttons: TitlebarButtons {
886
9
                has_close: false, // iOS apps don't have close buttons
887
9
                has_minimize: false,
888
9
                has_maximize: false,
889
9
                has_fullscreen: false,
890
9
            },
891
9
            height: OptionPixelValue::Some(PixelValue::px(44.0)),
892
9
            button_area_width: OptionPixelValue::Some(PixelValue::px(0.0)),
893
9
            padding_horizontal: OptionPixelValue::Some(PixelValue::px(16.0)),
894
9
            safe_area: SafeAreaInsets {
895
9
                // iPhone notch safe area
896
9
                top: OptionPixelValue::Some(PixelValue::px(47.0)),
897
9
                bottom: OptionPixelValue::Some(PixelValue::px(34.0)),
898
9
                left: OptionPixelValue::None,
899
9
                right: OptionPixelValue::None,
900
9
                // No keyboard inset at this site: a titlebar/desktop
901
9
                // surface never has an on-screen keyboard over it.
902
9
                keyboard: OptionPixelValue::None,
903
9
            },
904
9
            title_font: OptionString::Some(".SFUI-Semibold".into()),
905
9
            title_font_size: OptionF32::Some(17.0),
906
9
            title_font_weight: OptionU16::Some(600),
907
9
            background_active: OptionColorU::None,
908
9
            background_inactive: OptionColorU::None,
909
9
            text_active: OptionColorU::None,
910
9
            text_inactive: OptionColorU::None,
911
9
            button_hover_background: OptionColorU::None,
912
9
            close_button_hover_background: OptionColorU::None,
913
9
        }
914
9
    }
915

            
916
    /// Android-style titlebar (action bar)
917
    #[must_use]
918
15
    pub fn android() -> Self {
919
15
        Self {
920
15
            button_side: TitlebarButtonSide::Left, // Back button on left
921
15
            buttons: TitlebarButtons {
922
15
                has_close: false,
923
15
                has_minimize: false,
924
15
                has_maximize: false,
925
15
                has_fullscreen: false,
926
15
            },
927
15
            height: OptionPixelValue::Some(PixelValue::px(56.0)),
928
15
            button_area_width: OptionPixelValue::Some(PixelValue::px(48.0)), // Back button
929
15
            padding_horizontal: OptionPixelValue::Some(PixelValue::px(16.0)),
930
15
            safe_area: SafeAreaInsets::default(),
931
15
            title_font: OptionString::Some("Roboto Medium".into()),
932
15
            title_font_size: OptionF32::Some(20.0),
933
15
            title_font_weight: OptionU16::Some(500),
934
15
            background_active: OptionColorU::None,
935
15
            background_inactive: OptionColorU::None,
936
15
            text_active: OptionColorU::None,
937
15
            text_inactive: OptionColorU::None,
938
15
            button_hover_background: OptionColorU::None,
939
15
            close_button_hover_background: OptionColorU::None,
940
15
        }
941
15
    }
942
}
943

            
944
// ── Input interaction metrics ────────────────────────────────────────────
945

            
946
/// Input interaction timing and distance thresholds from the OS.
947
///
948
/// These values are queried from the operating system to match the user's
949
/// configured double-click speed, drag sensitivity, caret blink rate, etc.
950
///
951
/// # Platform APIs
952
/// - **macOS:** `NSEvent.doubleClickInterval`
953
/// - **Windows:** `GetDoubleClickTime()`, `GetSystemMetrics(SM_CXDOUBLECLK)`,
954
///   `GetCaretBlinkTime()`, `SystemParametersInfo(SPI_GETWHEELSCROLLLINES)`
955
/// - **Linux:** XDG Desktop Portal / gsettings
956
#[derive(Debug, Clone, Copy, PartialEq)]
957
#[repr(C)]
958
pub struct InputMetrics {
959
    /// Max milliseconds between clicks to register a double-click.
960
    pub double_click_time_ms: u32,
961
    /// Max pixels the mouse can move between clicks and still count.
962
    pub double_click_distance_px: f32,
963
    /// Pixels the mouse must move while held down before a drag starts.
964
    pub drag_threshold_px: f32,
965
    /// Caret blink rate in milliseconds (0 = no blink).
966
    pub caret_blink_rate_ms: u32,
967
    /// Width of the text caret/cursor in pixels (typically 1–2).
968
    pub caret_width_px: f32,
969
    /// Lines to scroll per mouse wheel notch.
970
    pub wheel_scroll_lines: u32,
971
    /// Milliseconds to wait before a hover triggers (e.g. tooltip delay).
972
    /// Windows: `SystemParametersInfo(SPI_GETMOUSEHOVERTIME)` — default 400.
973
    pub hover_time_ms: u32,
974
}
975

            
976
impl Default for InputMetrics {
977
66087
    fn default() -> Self {
978
66087
        Self {
979
66087
            double_click_time_ms: 500,
980
66087
            double_click_distance_px: 4.0,
981
66087
            drag_threshold_px: 5.0,
982
66087
            caret_blink_rate_ms: 530,
983
66087
            caret_width_px: 1.0,
984
66087
            wheel_scroll_lines: 3,
985
66087
            hover_time_ms: 400,
986
66087
        }
987
66087
    }
988
}
989

            
990
// ── Text rendering hints ─────────────────────────────────────────────────
991

            
992
/// Subpixel rendering layout for font smoothing.
993
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
994
#[repr(C)]
995
pub enum SubpixelType {
996
    /// No subpixel rendering (grayscale anti-aliasing only).
997
    #[default]
998
    None,
999
    /// Horizontal RGB subpixel layout (most common for LCD monitors).
    Rgb,
    /// Horizontal BGR subpixel layout.
    Bgr,
    /// Vertical RGB subpixel layout.
    VRgb,
    /// Vertical BGR subpixel layout.
    VBgr,
}
/// Text rendering configuration from the OS.
///
/// These hints allow the framework to match the host's font smoothing
/// settings for crisp, consistent text rendering.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct TextRenderingHints {
    /// Subpixel rendering type.
    pub subpixel_type: SubpixelType,
    /// Font smoothing gamma (1000 = default, higher = more contrast).
    pub font_smoothing_gamma: u32,
    /// Whether font smoothing (anti-aliasing) is enabled.
    pub font_smoothing_enabled: bool,
    /// User prefers increased text contrast.
    pub increased_contrast: bool,
}
impl Default for TextRenderingHints {
66087
    fn default() -> Self {
66087
        Self {
66087
            subpixel_type: SubpixelType::None,
66087
            font_smoothing_gamma: 1000,
66087
            font_smoothing_enabled: true,
66087
            increased_contrast: false,
66087
        }
66087
    }
}
// ── Focus ring visuals ───────────────────────────────────────────────────
/// Focus ring / indicator visual style.
///
/// When an element receives keyboard focus the OS typically draws a visible
/// ring or border.  These values come from the OS preferences.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct FocusVisuals {
    /// Focus ring / indicator colour.
    /// macOS: `NSColor.keyboardFocusIndicatorColor`
    pub focus_ring_color: OptionColorU,
    /// Width of focus border / ring.
    /// Windows: `SystemParametersInfo(SPI_GETFOCUSBORDERWIDTH)`
    pub focus_border_width: OptionPixelValue,
    /// Height of focus border / ring.
    pub focus_border_height: OptionPixelValue,
}
// ── Scrollbar preferences ────────────────────────────────────────────────
/// When scrollbars should be shown (OS-level preference).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum ScrollbarVisibility {
    /// Always show scrollbars.
    Always,
    /// Show only while scrolling, then fade out.
    #[default]
    WhenScrolling,
    /// Automatic: depends on input device (trackpad → overlay, mouse → always).
    Automatic,
}
/// What happens when clicking the scrollbar track area.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum ScrollbarTrackClick {
    /// Jump to the clicked position.
    JumpToPosition,
    /// Scroll by one page.
    #[default]
    PageUpDown,
}
/// OS-level scrollbar behaviour preferences.
///
/// These are separate from the CSS scrollbar *appearance* (`ComputedScrollbarStyle`).
/// They control *when* scrollbars appear and *how* clicking the track behaves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct ScrollbarPreferences {
    /// How scrollbars should be shown.
    /// macOS: `NSScroller.preferredScrollerStyle`
    pub visibility: ScrollbarVisibility,
    /// What happens when clicking the scrollbar track.
    pub track_click: ScrollbarTrackClick,
}
impl Default for ScrollbarPreferences {
66087
    fn default() -> Self {
66087
        Self {
66087
            visibility: ScrollbarVisibility::WhenScrolling,
66087
            track_click: ScrollbarTrackClick::PageUpDown,
66087
        }
66087
    }
}
// ── Linux-specific customisation ─────────────────────────────────────────
/// Linux-specific customisation settings.
///
/// Read from GTK / KDE / XDG settings on Linux; `Default` (all `None` / 0)
/// on other platforms.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct LinuxCustomization {
    /// GTK theme name (e.g. "Adwaita", "Breeze", "Numix").
    pub gtk_theme: OptionString,
    /// Icon theme name (e.g. "Papirus", "Numix", "Breeze").
    pub icon_theme: OptionString,
    /// Cursor theme name (e.g. "`Breeze_Snow`", "DMZ-Black").
    pub cursor_theme: OptionString,
    /// Cursor size in pixels (0 = unset / use OS default).
    pub cursor_size: u32,
    /// GTK button layout string (e.g. "close,minimize,maximize:menu").
    /// Determines button side and order for CSD titlebars on Linux.
    pub titlebar_button_layout: OptionString,
}
// ── Visual hints (icons in menus / buttons / toolbar style) ──────────────
/// Toolbar display style (icons, text, or both).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum ToolbarStyle {
    /// Show only icons in toolbars.
    #[default]
    IconsOnly,
    /// Show only text labels in toolbars.
    TextOnly,
    /// Show text beside the icon (horizontal).
    TextBesideIcon,
    /// Show text below the icon (vertical).
    TextBelowIcon,
}
/// Visual hints from the OS about how icons and decorations should be shown.
///
/// These preferences differ heavily between Linux desktops (KDE vs GNOME)
/// and are less configurable on macOS / Windows where HIG rules apply.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct VisualHints {
    /// Toolbar display style.
    /// Linux: `org.gnome.desktop.interface toolbar-style`, KDE `ToolButtonStyle`.
    pub toolbar_style: ToolbarStyle,
    /// Show icons on push buttons?  (Common in KDE, rare in Win/Mac.)
    /// Linux: `org.gnome.desktop.interface buttons-have-icons`, KDE `ShowIconsOnPushButtons`.
    pub show_button_images: bool,
    /// Show icons in context menus?  (GNOME defaults off since 3.x; Win/Mac/KDE usually on.)
    /// Linux: `org.gnome.desktop.interface menus-have-icons`.
    pub show_menu_images: bool,
    /// Should tooltips be shown on hover?
    pub show_tooltips: bool,
    /// Flash the window taskbar entry on alert?
    pub flash_on_alert: bool,
}
impl Default for VisualHints {
66087
    fn default() -> Self {
66087
        Self {
66087
            toolbar_style: ToolbarStyle::IconsOnly,
66087
            show_button_images: false,
66087
            show_menu_images: true,
66087
            show_tooltips: true,
66087
            flash_on_alert: true,
66087
        }
66087
    }
}
// ── Animation metrics ────────────────────────────────────────────────────
/// Focus indicator behaviour (always visible vs keyboard-only).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum FocusBehavior {
    /// Focus indicators are always visible when an element has focus.
    #[default]
    AlwaysVisible,
    /// Focus indicators are hidden until the user presses a keyboard key
    /// (Alt, Tab, arrow keys, etc.).  Windows: `SPI_GETKEYBOARDCUES`.
    KeyboardOnly,
}
/// Animation-related preferences from the OS.
///
/// These control whether UI animations (transitions, fades, slides) should
/// play and at what speed.
///
/// # Platform APIs
/// - **Windows:** `SystemParametersInfo(SPI_GETCLIENTAREAANIMATION)`, `SPI_GETKEYBOARDCUES`
/// - **macOS:** `NSWorkspace.accessibilityDisplayShouldReduceMotion`
/// - **Linux:** `org.gnome.desktop.interface enable-animations`, KDE `AnimationDurationFactor`
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct AnimationMetrics {
    /// Global enable/disable for UI animations.
    pub animations_enabled: bool,
    /// Animation speed factor (1.0 = normal, 0.5 = 2× faster, 2.0 = 2× slower).
    /// Primarily used in KDE.
    pub animation_duration_factor: f32,
    /// When to show focus rectangles / rings.
    pub focus_indicator_behavior: FocusBehavior,
}
impl Default for AnimationMetrics {
66087
    fn default() -> Self {
66087
        Self {
66087
            animations_enabled: true,
66087
            animation_duration_factor: 1.0,
66087
            focus_indicator_behavior: FocusBehavior::AlwaysVisible,
66087
        }
66087
    }
}
// ── Audio metrics ────────────────────────────────────────────────────────
/// Audio-feedback preferences from the OS.
///
/// Controls whether the app should make sounds on events (error pings,
/// notifications) or on input (clicks, key presses).
///
/// # Platform APIs
/// - **Windows:** `SystemParametersInfo(SPI_GETBEEP)`
/// - **macOS:** `NSSound.soundEffectAudioVolume`
/// - **Linux:** `org.gnome.desktop.sound event-sounds`, `org.gnome.desktop.sound
///   input-feedback-sounds`
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct AudioMetrics {
    /// Should the app make sounds on events?  (Error ping, notification, etc.)
    pub event_sounds_enabled: bool,
    /// Should the app make sounds on input?  (Clicks, typing feedback.)
    pub input_feedback_sounds_enabled: bool,
}
impl Default for AudioMetrics {
66087
    fn default() -> Self {
66087
        Self {
66087
            event_sounds_enabled: true,
66087
            input_feedback_sounds_enabled: false,
66087
        }
66087
    }
}
/// Apple system font family names for font fallback chains.
///
/// These are the canonical names for Apple's system fonts, which should
/// be used in font fallback chains for proper rendering on Apple platforms.
/// Note: The names here must match what rust-fontconfig indexes from the font metadata.
pub mod apple_fonts {
    /// System Font - Primary system font for macOS
    /// This is how rust-fontconfig indexes the SF Pro font family
    pub const SYSTEM_FONT: &str = "System Font";
    /// SF NS variants as indexed by rust-fontconfig
    pub const SF_NS_ROUNDED: &str = "SF NS Rounded";
    /// SF Compact - System font optimized for watchOS
    /// Optimized for small sizes and narrow columns
    pub const SF_COMPACT: &str = "SF Compact";
    /// SF Mono - Monospaced font used in Xcode
    /// Enables alignment between rows and columns of text
    pub const SF_MONO: &str = "SF NS Mono Light";
    /// New York - Serif font for reading
    /// Performs as traditional reading face at small sizes
    pub const NEW_YORK: &str = "New York";
    /// SF Arabic - Arabic system font
    pub const SF_ARABIC: &str = "SF Arabic";
    /// SF Armenian - Armenian system font
    pub const SF_ARMENIAN: &str = "SF Armenian";
    /// SF Georgian - Georgian system font
    pub const SF_GEORGIAN: &str = "SF Georgian";
    /// SF Hebrew - Hebrew system font with niqqud support
    pub const SF_HEBREW: &str = "SF Hebrew";
    /// Legacy macOS fonts for fallback
    pub const MENLO: &str = "Menlo";
    pub const MENLO_REGULAR: &str = "Menlo Regular";
    pub const MENLO_BOLD: &str = "Menlo Bold";
    pub const MONACO: &str = "Monaco";
    pub const LUCIDA_GRANDE: &str = "Lucida Grande";
    pub const LUCIDA_GRANDE_BOLD: &str = "Lucida Grande Bold";
    pub const HELVETICA_NEUE: &str = "Helvetica Neue";
    pub const HELVETICA_NEUE_BOLD: &str = "Helvetica Neue Bold";
}
/// Windows system font family names.
pub mod windows_fonts {
    /// Modern Windows 11 fonts
    pub const SEGOE_UI_VARIABLE: &str = "Segoe UI Variable";
    pub const SEGOE_UI_VARIABLE_TEXT: &str = "Segoe UI Variable Text";
    pub const SEGOE_UI_VARIABLE_DISPLAY: &str = "Segoe UI Variable Display";
    /// Standard Windows fonts
    pub const SEGOE_UI: &str = "Segoe UI";
    pub const CONSOLAS: &str = "Consolas";
    pub const CASCADIA_CODE: &str = "Cascadia Code";
    pub const CASCADIA_MONO: &str = "Cascadia Mono";
    /// Legacy Windows fonts
    pub const TAHOMA: &str = "Tahoma";
    pub const MS_SANS_SERIF: &str = "MS Sans Serif";
    pub const LUCIDA_CONSOLE: &str = "Lucida Console";
    pub const COURIER_NEW: &str = "Courier New";
}
/// Linux/GTK common font family names.
pub mod linux_fonts {
    /// GNOME default fonts
    pub const CANTARELL: &str = "Cantarell";
    pub const ADWAITA: &str = "Adwaita";
    /// Ubuntu fonts
    pub const UBUNTU: &str = "Ubuntu";
    pub const UBUNTU_MONO: &str = "Ubuntu Mono";
    /// `DejaVu` fonts (widely available)
    pub const DEJAVU_SANS: &str = "DejaVu Sans";
    pub const DEJAVU_SANS_MONO: &str = "DejaVu Sans Mono";
    pub const DEJAVU_SERIF: &str = "DejaVu Serif";
    /// Liberation fonts (metrically compatible with Windows fonts)
    pub const LIBERATION_SANS: &str = "Liberation Sans";
    pub const LIBERATION_MONO: &str = "Liberation Mono";
    pub const LIBERATION_SERIF: &str = "Liberation Serif";
    /// Noto fonts (broad Unicode coverage)
    pub const NOTO_SANS: &str = "Noto Sans";
    pub const NOTO_MONO: &str = "Noto Sans Mono";
    pub const NOTO_SERIF: &str = "Noto Serif";
    /// KDE default fonts
    pub const HACK: &str = "Hack";
    /// Generic fallback names
    pub const MONOSPACE: &str = "Monospace";
    pub const SANS_SERIF: &str = "Sans";
    pub const SERIF: &str = "Serif";
}
impl SystemFontType {
    /// Returns the font fallback chain for this font type on the given platform.
    ///
    /// The returned list contains font family names in order of preference.
    /// The first available font should be used.
    #[must_use]
2408
    pub fn get_fallback_chain(&self, platform: &Platform) -> Vec<&'static str> {
2408
        match platform {
159
            Platform::MacOs | Platform::Ios => self.macos_fallback_chain(),
49
            Platform::Windows => self.windows_fallback_chain(),
2000
            Platform::Linux(_) => self.linux_fallback_chain(),
36
            Platform::Android => self.android_fallback_chain(),
164
            Platform::Unknown => self.generic_fallback_chain(),
        }
2408
    }
159
    fn macos_fallback_chain(self) -> Vec<&'static str> {
159
        match self {
            // Normal weight: System Font first, then Helvetica Neue.
73
            Self::Ui => vec![
73
                apple_fonts::SYSTEM_FONT,
73
                apple_fonts::HELVETICA_NEUE,
73
                apple_fonts::LUCIDA_GRANDE,
            ],
            // Bold weights: Helvetica Neue first (System Font has no Bold variant in fontconfig).
            Self::UiBold | Self::TitleBold => {
16
                vec![apple_fonts::HELVETICA_NEUE, apple_fonts::LUCIDA_GRANDE]
            }
            // Monospace: Menlo (has a Bold variant), then Monaco.
            Self::Monospace | Self::MonospaceBold | Self::MonospaceItalic => {
30
                vec![apple_fonts::MENLO, apple_fonts::MONACO]
            }
            // Title / Menu / Small: System Font then Helvetica Neue.
            Self::Title | Self::Menu | Self::Small => {
24
                vec![apple_fonts::SYSTEM_FONT, apple_fonts::HELVETICA_NEUE]
            }
            // Serif fonts - Georgia has bold variant
8
            Self::Serif => vec![apple_fonts::NEW_YORK, "Georgia", "Times New Roman"],
8
            Self::SerifBold => vec![
8
                "Georgia", // Georgia Bold exists
8
                "Times New Roman",
            ],
        }
159
    }
49
    fn windows_fallback_chain(self) -> Vec<&'static str> {
49
        match self {
19
            Self::Ui | Self::UiBold => vec![
19
                windows_fonts::SEGOE_UI_VARIABLE_TEXT,
19
                windows_fonts::SEGOE_UI,
19
                windows_fonts::TAHOMA,
            ],
12
            Self::Monospace | Self::MonospaceBold | Self::MonospaceItalic => vec![
12
                windows_fonts::CASCADIA_MONO,
12
                windows_fonts::CASCADIA_CODE,
12
                windows_fonts::CONSOLAS,
12
                windows_fonts::LUCIDA_CONSOLE,
12
                windows_fonts::COURIER_NEW,
            ],
6
            Self::Title | Self::TitleBold => vec![
6
                windows_fonts::SEGOE_UI_VARIABLE_DISPLAY,
6
                windows_fonts::SEGOE_UI,
            ],
3
            Self::Menu => vec![windows_fonts::SEGOE_UI, windows_fonts::TAHOMA],
3
            Self::Small => vec![windows_fonts::SEGOE_UI],
6
            Self::Serif | Self::SerifBold => vec!["Cambria", "Georgia", "Times New Roman"],
        }
49
    }
2000
    fn linux_fallback_chain(self) -> Vec<&'static str> {
2000
        match self {
1883
            Self::Ui | Self::UiBold => vec![
1883
                linux_fonts::CANTARELL,
1883
                linux_fonts::UBUNTU,
1883
                linux_fonts::NOTO_SANS,
1883
                linux_fonts::DEJAVU_SANS,
1883
                linux_fonts::LIBERATION_SANS,
1883
                linux_fonts::SANS_SERIF,
            ],
45
            Self::Monospace | Self::MonospaceBold | Self::MonospaceItalic => vec![
45
                linux_fonts::UBUNTU_MONO,
45
                linux_fonts::HACK,
45
                linux_fonts::NOTO_MONO,
45
                linux_fonts::DEJAVU_SANS_MONO,
45
                linux_fonts::LIBERATION_MONO,
45
                linux_fonts::MONOSPACE,
            ],
48
            Self::Title | Self::TitleBold | Self::Menu | Self::Small => vec![
48
                linux_fonts::CANTARELL,
48
                linux_fonts::UBUNTU,
48
                linux_fonts::NOTO_SANS,
            ],
24
            Self::Serif | Self::SerifBold => vec![
24
                linux_fonts::NOTO_SERIF,
24
                linux_fonts::DEJAVU_SERIF,
24
                linux_fonts::LIBERATION_SERIF,
24
                linux_fonts::SERIF,
            ],
        }
2000
    }
36
    fn android_fallback_chain(self) -> Vec<&'static str> {
36
        match self {
12
            Self::Ui | Self::UiBold | Self::Title | Self::TitleBold => vec!["Roboto", "Noto Sans"],
            Self::Monospace | Self::MonospaceBold | Self::MonospaceItalic => {
12
                vec!["Roboto Mono", "Droid Sans Mono", "monospace"]
            }
6
            Self::Menu | Self::Small => vec!["Roboto"],
6
            Self::Serif | Self::SerifBold => vec!["Noto Serif", "Droid Serif", "serif"],
        }
36
    }
164
    fn generic_fallback_chain(self) -> Vec<&'static str> {
164
        match self {
            Self::Ui | Self::UiBold | Self::Title | Self::TitleBold | Self::Menu | Self::Small => {
141
                vec!["sans-serif"]
            }
            Self::Monospace | Self::MonospaceBold | Self::MonospaceItalic => {
15
                vec!["monospace"]
            }
8
            Self::Serif | Self::SerifBold => vec!["serif"],
        }
164
    }
}
impl SystemStyle {
    /// Format the `SystemStyle` as a human-readable JSON string for debugging.
    ///
    /// This does NOT use serde — it manually formats the most important fields
    /// so that they can be verified against OS-reported values in a test script.
    #[allow(clippy::too_many_lines)]
    // large but cohesive: single-purpose CSS parser/formatter/dispatch table (one branch per
    // property/variant)
    #[must_use]
23
    pub fn to_json_string(&self) -> AzString {
        use alloc::format;
483
        fn opt_color(c: OptionColorU) -> alloc::string::String {
483
            c.as_ref().map_or_else(
387
                || "null".into(),
96
                |c| format!("\"#{:02x}{:02x}{:02x}{:02x}\"", c.r, c.g, c.b, c.a),
            )
483
        }
230
        fn opt_str(s: &OptionString) -> alloc::string::String {
230
            s.as_ref()
230
                .map_or_else(|| "null".into(), |s| format!("\"{}\"", s.as_str()))
230
        }
46
        fn opt_f32(v: OptionF32) -> alloc::string::String {
46
            v.into_option()
46
                .map_or_else(|| "null".into(), |v| format!("{v:.2}"))
46
        }
23
        fn opt_u16(v: OptionU16) -> alloc::string::String {
23
            v.into_option()
23
                .map_or_else(|| "null".into(), |v| format!("{v}"))
23
        }
69
        fn opt_px(v: &OptionPixelValue) -> alloc::string::String {
69
            v.as_ref().map_or_else(
9
                || "null".into(),
60
                |v| format!("{:.1}", v.to_pixels_internal(0.0, 0.0, 0.0)),
            )
69
        }
23
        let tm = &self.metrics.titlebar;
23
        let inp = &self.input;
23
        let tr = &self.text_rendering;
23
        let acc = &self.accessibility;
23
        let sp = &self.scrollbar_preferences;
23
        let lnx = &self.linux;
23
        let vh = &self.visual_hints;
23
        let anim = &self.animation;
23
        let audio = &self.audio;
23
        let json = format!(
23
            r#"{{
23
  "theme": "{:?}",
23
  "platform": "{:?}",
23
  "os_version": "{:?}:{}",
23
  "language": "{}",
23
  "prefers_reduced_motion": {:?},
23
  "prefers_high_contrast": {:?},
23
  "colors": {{
23
    "text": {},
23
    "secondary_text": {},
23
    "tertiary_text": {},
23
    "background": {},
23
    "accent": {},
23
    "accent_text": {},
23
    "button_face": {},
23
    "button_text": {},
23
    "disabled_text": {},
23
    "window_background": {},
23
    "under_page_background": {},
23
    "selection_background": {},
23
    "selection_text": {},
23
    "selection_background_inactive": {},
23
    "selection_text_inactive": {},
23
    "link": {},
23
    "separator": {},
23
    "grid": {},
23
    "find_highlight": {},
23
    "sidebar_background": {},
23
    "sidebar_selection": {}
23
  }},
23
  "fonts": {{
23
    "ui_font": {},
23
    "ui_font_size": {},
23
    "monospace_font": {},
23
    "title_font": {},
23
    "menu_font": {},
23
    "small_font": {}
23
  }},
23
  "titlebar": {{
23
    "button_side": "{:?}",
23
    "height": {},
23
    "button_area_width": {},
23
    "padding_horizontal": {},
23
    "title_font": {},
23
    "title_font_size": {},
23
    "title_font_weight": {},
23
    "has_close": {},
23
    "has_minimize": {},
23
    "has_maximize": {},
23
    "has_fullscreen": {}
23
  }},
23
  "input": {{
23
    "double_click_time_ms": {},
23
    "double_click_distance_px": {:.1},
23
    "drag_threshold_px": {:.1},
23
    "caret_blink_rate_ms": {},
23
    "caret_width_px": {:.1},
23
    "wheel_scroll_lines": {},
23
    "hover_time_ms": {}
23
  }},
23
  "text_rendering": {{
23
    "font_smoothing_enabled": {},
23
    "subpixel_type": "{:?}",
23
    "font_smoothing_gamma": {},
23
    "increased_contrast": {}
23
  }},
23
  "accessibility": {{
23
    "prefers_bold_text": {},
23
    "prefers_larger_text": {},
23
    "text_scale_factor": {:.2},
23
    "prefers_high_contrast": {},
23
    "prefers_reduced_motion": {},
23
    "prefers_reduced_transparency": {},
23
    "screen_reader_active": {},
23
    "differentiate_without_color": {}
23
  }},
23
  "scrollbar_preferences": {{
23
    "visibility": "{:?}",
23
    "track_click": "{:?}"
23
  }},
23
  "linux": {{
23
    "gtk_theme": {},
23
    "icon_theme": {},
23
    "cursor_theme": {},
23
    "cursor_size": {},
23
    "titlebar_button_layout": {}
23
  }},
23
  "visual_hints": {{
23
    "show_button_images": {},
23
    "show_menu_images": {},
23
    "toolbar_style": "{:?}",
23
    "show_tooltips": {}
23
  }},
23
  "animation": {{
23
    "animations_enabled": {},
23
    "animation_duration_factor": {:.2},
23
    "focus_indicator_behavior": "{:?}"
23
  }},
23
  "audio": {{
23
    "event_sounds_enabled": {},
23
    "input_feedback_sounds_enabled": {}
23
  }}
23
}}"#,
            // top-level
            self.theme,
            self.platform,
            self.os_version.os,
            self.os_version.version_id,
23
            self.language.as_str(),
            self.prefers_reduced_motion,
            self.prefers_high_contrast,
            // colors
23
            opt_color(self.colors.text),
23
            opt_color(self.colors.secondary_text),
23
            opt_color(self.colors.tertiary_text),
23
            opt_color(self.colors.background),
23
            opt_color(self.colors.accent),
23
            opt_color(self.colors.accent_text),
23
            opt_color(self.colors.button_face),
23
            opt_color(self.colors.button_text),
23
            opt_color(self.colors.disabled_text),
23
            opt_color(self.colors.window_background),
23
            opt_color(self.colors.under_page_background),
23
            opt_color(self.colors.selection_background),
23
            opt_color(self.colors.selection_text),
23
            opt_color(self.colors.selection_background_inactive),
23
            opt_color(self.colors.selection_text_inactive),
23
            opt_color(self.colors.link),
23
            opt_color(self.colors.separator),
23
            opt_color(self.colors.grid),
23
            opt_color(self.colors.find_highlight),
23
            opt_color(self.colors.sidebar_background),
23
            opt_color(self.colors.sidebar_selection),
            // fonts
23
            opt_str(&self.fonts.ui_font),
23
            opt_f32(self.fonts.ui_font_size),
23
            opt_str(&self.fonts.monospace_font),
23
            opt_str(&self.fonts.title_font),
23
            opt_str(&self.fonts.menu_font),
23
            opt_str(&self.fonts.small_font),
            // titlebar
            tm.button_side,
23
            opt_px(&tm.height),
23
            opt_px(&tm.button_area_width),
23
            opt_px(&tm.padding_horizontal),
23
            opt_str(&tm.title_font),
23
            opt_f32(tm.title_font_size),
23
            opt_u16(tm.title_font_weight),
            tm.buttons.has_close,
            tm.buttons.has_minimize,
            tm.buttons.has_maximize,
            tm.buttons.has_fullscreen,
            // input
            inp.double_click_time_ms,
            inp.double_click_distance_px,
            inp.drag_threshold_px,
            inp.caret_blink_rate_ms,
            inp.caret_width_px,
            inp.wheel_scroll_lines,
            inp.hover_time_ms,
            // text_rendering
            tr.font_smoothing_enabled,
            tr.subpixel_type,
            tr.font_smoothing_gamma,
            tr.increased_contrast,
            // accessibility
            acc.prefers_bold_text,
            acc.prefers_larger_text,
            acc.text_scale_factor,
            acc.prefers_high_contrast,
            acc.prefers_reduced_motion,
            acc.prefers_reduced_transparency,
            acc.screen_reader_active,
            acc.differentiate_without_color,
            // scrollbar_preferences
            sp.visibility,
            sp.track_click,
            // linux
23
            opt_str(&lnx.gtk_theme),
23
            opt_str(&lnx.icon_theme),
23
            opt_str(&lnx.cursor_theme),
            lnx.cursor_size,
23
            opt_str(&lnx.titlebar_button_layout),
            // visual_hints
            vh.show_button_images,
            vh.show_menu_images,
            vh.toolbar_style,
            vh.show_tooltips,
            // animation
            anim.animations_enabled,
            anim.animation_duration_factor,
            anim.focus_indicator_behavior,
            // audio
            audio.event_sounds_enabled,
            audio.input_feedback_sounds_enabled,
        );
23
        AzString::from(json)
23
    }
    /// Returns a platform-appropriate default system style.
    ///
    /// This returns hard-coded defaults based on the target OS. For actual
    /// runtime detection of the user's theme, colors, and fonts, use the
    /// platform discovery in `azul-dll` (called automatically by `App::create()`).
    #[must_use]
177
    pub fn detect() -> Self {
177
        Self::default_for_platform()
177
    }
    /// Returns hard-coded defaults for the current compile-time platform.
    #[must_use]
204
    pub fn default_for_platform() -> Self {
        #[cfg(target_os = "windows")]
        {
            defaults::windows_11_light()
        }
        #[cfg(target_os = "macos")]
        {
            defaults::macos_modern_light()
        }
        #[cfg(target_os = "linux")]
        {
204
            defaults::gnome_adwaita_light()
        }
        #[cfg(target_os = "android")]
        {
            defaults::android_material_light()
        }
        #[cfg(target_os = "ios")]
        {
            defaults::ios_light()
        }
        #[cfg(not(any(
            target_os = "linux",
            target_os = "windows",
            target_os = "macos",
            target_os = "android",
            target_os = "ios"
        )))]
        {
            Self::default()
        }
204
    }
    /// Alias for `detect` - kept for internal compatibility, not exposed in FFI.
    #[inline]
    #[must_use]
2
    pub fn new() -> Self {
2
        Self::detect()
2
    }
    /// Create a CSS stylesheet for CSD (Client-Side Decorations) titlebar
    ///
    /// This generates CSS rules for the CSD titlebar using system colors,
    /// fonts, and metrics to match the native platform look. Returned rules
    /// carry `rule_priority::SYSTEM`.
    #[must_use]
28
    pub fn create_csd_stylesheet(&self) -> Css {
        use alloc::format;
        use crate::parser2::new_from_str;
        // Build CSS string from SystemStyle
28
        let mut css = String::new();
        // Get system colors with fallbacks
28
        let bg_color = self
28
            .colors
28
            .window_background
28
            .as_option()
28
            .copied()
28
            .unwrap_or(ColorU::new_rgb(240, 240, 240));
28
        let text_color = self
28
            .colors
28
            .text
28
            .as_option()
28
            .copied()
28
            .unwrap_or(ColorU::new_rgb(0, 0, 0));
28
        let accent_color = self
28
            .colors
28
            .accent
28
            .as_option()
28
            .copied()
28
            .unwrap_or(ColorU::new_rgb(0, 120, 215));
28
        let border_color = match self.theme {
4
            Theme::Dark => ColorU::new_rgb(60, 60, 60),
24
            Theme::Light => ColorU::new_rgb(200, 200, 200),
        };
        // Get system metrics with fallbacks
28
        let corner_radius = self
28
            .metrics
28
            .corner_radius
28
            .map(|px| {
                use crate::props::basic::pixel::DEFAULT_FONT_SIZE;
26
                format!(
26
                    "{}px",
26
                    px.to_pixels_internal(1.0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE)
                )
26
            })
28
            .unwrap_or_else(|| "4px".to_string());
        // Titlebar container
28
        let _ = write!(
28
            css,
28
            ".csd-titlebar {{ width: 100%; height: 32px; background: rgb({}, {}, {}); \
28
             border-bottom: 1px solid rgb({}, {}, {}); display: flex; flex-direction: row; \
28
             align-items: center; justify-content: space-between; padding: 0 8px; cursor: grab; \
28
             user-select: none; }} ",
            bg_color.r, bg_color.g, bg_color.b, border_color.r, border_color.g, border_color.b,
        );
        // Title text
28
        let _ = write!(
28
            css,
28
            ".csd-title {{ color: rgb({}, {}, {}); font-size: 13px; flex-grow: 1; text-align: \
28
             center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: \
28
             none; }} ",
            text_color.r, text_color.g, text_color.b,
        );
        // Button container
28
        css.push_str(".csd-buttons { display: flex; flex-direction: row; gap: 4px; } ");
        // Buttons
28
        let _ = write!(
28
            css,
28
            ".csd-button {{ width: 32px; height: 24px; border-radius: {}; background: \
28
             transparent; color: rgb({}, {}, {}); font-size: 16px; line-height: 24px; text-align: \
28
             center; cursor: pointer; user-select: none; }} ",
            corner_radius, text_color.r, text_color.g, text_color.b,
        );
        // Button hover state
28
        let hover_color = match self.theme {
4
            Theme::Dark => ColorU::new_rgb(60, 60, 60),
24
            Theme::Light => ColorU::new_rgb(220, 220, 220),
        };
28
        let _ = write!(
28
            css,
28
            ".csd-button:hover {{ background: rgb({}, {}, {}); }} ",
            hover_color.r, hover_color.g, hover_color.b,
        );
        // Close button hover (red on all platforms)
28
        css.push_str(
28
            ".csd-close:hover { background: rgb(232, 17, 35); color: rgb(255, 255, 255); } ",
        );
        // Platform-specific button styling
28
        match self.platform {
4
            Platform::MacOs => {
4
                // macOS traffic light buttons (left side)
4
                css.push_str(".csd-buttons { position: absolute; left: 8px; } ");
4
                css.push_str(
4
                    ".csd-close { background: rgb(255, 95, 86); width: 12px; height: 12px; \
4
                     border-radius: 50%; } ",
4
                );
4
                css.push_str(
4
                    ".csd-minimize { background: rgb(255, 189, 46); width: 12px; height: 12px; \
4
                     border-radius: 50%; } ",
4
                );
4
                css.push_str(
4
                    ".csd-maximize { background: rgb(40, 201, 64); width: 12px; height: 12px; \
4
                     border-radius: 50%; } ",
4
                );
4
            }
7
            Platform::Linux(_) => {
7
                // Linux - title on left, buttons on right
7
                css.push_str(".csd-title { text-align: left; } ");
7
            }
17
            _ => {
17
                // Windows and others - standard layout
17
            }
        }
        // Parse CSS string into a Css.
28
        let (mut parsed_css, _warnings) = new_from_str(&css);
        // Tag every rule as system-level so author CSS overrides win.
191
        for rule in parsed_css.rules.as_mut() {
191
            rule.priority = crate::css::rule_priority::SYSTEM;
191
        }
28
        parsed_css
28
    }
}
/// Detect the Linux desktop environment from environment variables.
///
/// Checks `XDG_CURRENT_DESKTOP`, `DESKTOP_SESSION`, and specific env markers
/// to identify GNOME, KDE, XFCE, Cinnamon, MATE, Hyprland, Sway, i3, etc.
#[must_use]
2
pub fn detect_linux_desktop_env() -> DesktopEnvironment {
    // Check XDG_CURRENT_DESKTOP first (most reliable)
2
    if let Ok(desktop) = std::env::var("XDG_CURRENT_DESKTOP") {
        let desktop_lower = desktop.to_lowercase();
        if desktop_lower.contains("gnome") {
            return DesktopEnvironment::Gnome;
        }
        if desktop_lower.contains("kde") || desktop_lower.contains("plasma") {
            return DesktopEnvironment::Kde;
        }
        if desktop_lower.contains("xfce") {
            return DesktopEnvironment::Other(AzString::from_const_str("XFCE"));
        }
        if desktop_lower.contains("unity") {
            return DesktopEnvironment::Other(AzString::from_const_str("Unity"));
        }
        if desktop_lower.contains("cinnamon") {
            return DesktopEnvironment::Other(AzString::from_const_str("Cinnamon"));
        }
        if desktop_lower.contains("mate") {
            return DesktopEnvironment::Other(AzString::from_const_str("MATE"));
        }
        if desktop_lower.contains("lxde") || desktop_lower.contains("lxqt") {
            return DesktopEnvironment::Other(AzString::from(desktop.to_uppercase()));
        }
        if desktop_lower.contains("budgie") {
            return DesktopEnvironment::Other(AzString::from_const_str("Budgie"));
        }
        if desktop_lower.contains("pantheon") {
            return DesktopEnvironment::Other(AzString::from_const_str("Pantheon"));
        }
        if desktop_lower.contains("deepin") {
            return DesktopEnvironment::Other(AzString::from_const_str("Deepin"));
        }
        if desktop_lower.contains("hyprland") {
            return DesktopEnvironment::Other(AzString::from_const_str("Hyprland"));
        }
        if desktop_lower.contains("sway") {
            return DesktopEnvironment::Other(AzString::from_const_str("Sway"));
        }
        if desktop_lower.contains("i3") {
            return DesktopEnvironment::Other(AzString::from_const_str("i3"));
        }
        return DesktopEnvironment::Other(AzString::from(desktop));
2
    }
    // Check DESKTOP_SESSION as fallback
2
    if let Ok(session) = std::env::var("DESKTOP_SESSION") {
        let session_lower = session.to_lowercase();
        if session_lower.contains("gnome") {
            return DesktopEnvironment::Gnome;
        }
        if session_lower.contains("plasma") || session_lower.contains("kde") {
            return DesktopEnvironment::Kde;
        }
        if session_lower.contains("xfce") {
            return DesktopEnvironment::Other(AzString::from_const_str("XFCE"));
        }
        if session_lower.contains("cinnamon") {
            return DesktopEnvironment::Other(AzString::from_const_str("Cinnamon"));
        }
        return DesktopEnvironment::Other(AzString::from(session));
2
    }
    // Check for specific environment markers
2
    if std::env::var("GNOME_DESKTOP_SESSION_ID").is_ok() {
        return DesktopEnvironment::Gnome;
2
    }
2
    if std::env::var("KDE_FULL_SESSION").is_ok() {
        return DesktopEnvironment::Kde;
2
    }
2
    if std::env::var("HYPRLAND_INSTANCE_SIGNATURE").is_ok() {
        return DesktopEnvironment::Other(AzString::from_const_str("Hyprland"));
2
    }
2
    if std::env::var("SWAYSOCK").is_ok() {
        return DesktopEnvironment::Other(AzString::from_const_str("Sway"));
2
    }
2
    if std::env::var("I3SOCK").is_ok() {
        return DesktopEnvironment::Other(AzString::from_const_str("i3"));
2
    }
2
    DesktopEnvironment::Other(AzString::from_const_str("Unknown"))
2
}
/// Detect the system language as a BCP 47 tag.
///
/// Checks `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, and `LANG` in priority order.
/// Returns `"en-US"` if detection fails. For runtime detection via native
/// OS APIs, the platform discovery in `azul-dll` overrides this.
#[must_use]
2
pub fn detect_system_language() -> AzString {
2
    let env_vars = ["LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"];
8
    for var in &env_vars {
8
        if let Ok(value) = std::env::var(var) {
2
            let value = value.trim();
2
            if value.is_empty() || value == "C" || value == "POSIX" {
                continue;
2
            }
            // Parse locale format: "de_DE.UTF-8" or "de_DE" or "de"
2
            let lang = value
2
                .split('.')  // Remove .UTF-8 suffix
2
                .next()
2
                .unwrap_or(value)
2
                .split(':')  // LANGUAGE can be "de:en_US:en"
2
                .next()
2
                .unwrap_or(value);
2
            if !lang.is_empty() {
2
                return AzString::from(lang.replace('_', "-"));
            }
6
        }
    }
    AzString::from_const_str("en-US")
2
}
pub mod defaults {
    //! A collection of hard-coded system style defaults that mimic the appearance
    //! of various operating systems and desktop environments.
    //!
    //! These are used as a
    //! fallback when the "io" feature is disabled, ensuring deterministic styles
    //! for testing and environments where system calls are not desired.
    use super::{
        AccessibilitySettings, AnimationMetrics, AudioMetrics, FocusVisuals, Handedness,
        InputMetrics, LinuxCustomization, ScrollbarPreferences, TextRenderingHints, VisualHints,
    };
    use crate::{
        corety::{AzString, OptionF32, OptionString},
        dynamic_selector::{BoolCondition, OsVersion},
        props::{
            basic::{
                color::{ColorU, OptionColorU},
                pixel::{OptionPixelValue, PixelValue},
            },
            layout::{
                dimensions::LayoutWidth,
                spacing::{LayoutPaddingLeft, LayoutPaddingRight},
            },
            style::{
                background::StyleBackgroundContent,
                scrollbar::{
                    ComputedScrollbarStyle, OverflowScrolling, OverscrollBehavior, ScrollBehavior,
                    ScrollPhysics, ScrollbarInfo, SCROLLBAR_ANDROID_DARK, SCROLLBAR_ANDROID_LIGHT,
                    SCROLLBAR_CLASSIC_DARK, SCROLLBAR_CLASSIC_LIGHT, SCROLLBAR_IOS_DARK,
                    SCROLLBAR_IOS_LIGHT, SCROLLBAR_MACOS_DARK, SCROLLBAR_MACOS_LIGHT,
                    SCROLLBAR_WINDOWS_DARK, SCROLLBAR_WINDOWS_LIGHT,
                },
            },
        },
        system::{
            DesktopEnvironment, IconStyleOptions, Platform, SystemColors, SystemFonts,
            SystemMetrics, SystemStyle, Theme, TitlebarMetrics,
        },
    };
    // --- Custom Scrollbar Style Constants for Nostalgia ---
    /// A scrollbar style mimicking the classic Windows 95/98/2000/XP look.
    pub const SCROLLBAR_WINDOWS_CLASSIC: ScrollbarInfo = ScrollbarInfo {
        width: LayoutWidth::Px(PixelValue::const_px(17)),
        padding_left: LayoutPaddingLeft {
            inner: PixelValue::const_px(0),
        },
        padding_right: LayoutPaddingRight {
            inner: PixelValue::const_px(0),
        },
        track: StyleBackgroundContent::Color(ColorU {
            r: 223,
            g: 223,
            b: 223,
            a: 255,
        }), // Scrollbar trough color
        thumb: StyleBackgroundContent::Color(ColorU {
            r: 208,
            g: 208,
            b: 208,
            a: 255,
        }), // Button face color
        button: StyleBackgroundContent::Color(ColorU {
            r: 208,
            g: 208,
            b: 208,
            a: 255,
        }),
        corner: StyleBackgroundContent::Color(ColorU {
            r: 223,
            g: 223,
            b: 223,
            a: 255,
        }),
        resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
        clip_to_container_border: false,
        scroll_behavior: ScrollBehavior::Auto,
        overscroll_behavior_x: OverscrollBehavior::None,
        overscroll_behavior_y: OverscrollBehavior::None,
        overflow_scrolling: OverflowScrolling::Auto,
    };
    /// A scrollbar style mimicking the macOS "Aqua" theme from the early 2000s.
    pub const SCROLLBAR_MACOS_AQUA: ScrollbarInfo = ScrollbarInfo {
        width: LayoutWidth::Px(PixelValue::const_px(15)),
        padding_left: LayoutPaddingLeft {
            inner: PixelValue::const_px(0),
        },
        padding_right: LayoutPaddingRight {
            inner: PixelValue::const_px(0),
        },
        track: StyleBackgroundContent::Color(ColorU {
            r: 238,
            g: 238,
            b: 238,
            a: 128,
        }), // Translucent track
        thumb: StyleBackgroundContent::Color(ColorU {
            r: 105,
            g: 173,
            b: 255,
            a: 255,
        }), // "Gel" blue
        button: StyleBackgroundContent::Color(ColorU {
            r: 105,
            g: 173,
            b: 255,
            a: 255,
        }),
        corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
        resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
        clip_to_container_border: true,
        scroll_behavior: ScrollBehavior::Smooth,
        overscroll_behavior_x: OverscrollBehavior::Auto,
        overscroll_behavior_y: OverscrollBehavior::Auto,
        overflow_scrolling: OverflowScrolling::Auto,
    };
    /// A scrollbar style mimicking the KDE Oxygen theme.
    pub const SCROLLBAR_KDE_OXYGEN: ScrollbarInfo = ScrollbarInfo {
        width: LayoutWidth::Px(PixelValue::const_px(14)),
        padding_left: LayoutPaddingLeft {
            inner: PixelValue::const_px(2),
        },
        padding_right: LayoutPaddingRight {
            inner: PixelValue::const_px(2),
        },
        track: StyleBackgroundContent::Color(ColorU {
            r: 242,
            g: 242,
            b: 242,
            a: 255,
        }),
        thumb: StyleBackgroundContent::Color(ColorU {
            r: 177,
            g: 177,
            b: 177,
            a: 255,
        }),
        button: StyleBackgroundContent::Color(ColorU {
            r: 216,
            g: 216,
            b: 216,
            a: 255,
        }),
        corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
        resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
        clip_to_container_border: false,
        scroll_behavior: ScrollBehavior::Auto,
        overscroll_behavior_x: OverscrollBehavior::Auto,
        overscroll_behavior_y: OverscrollBehavior::Auto,
        overflow_scrolling: OverflowScrolling::Auto,
    };
    /// Helper to convert a detailed `ScrollbarInfo` into the simplified `ComputedScrollbarStyle`.
366
    fn scrollbar_info_to_computed(info: &ScrollbarInfo) -> ComputedScrollbarStyle {
        ComputedScrollbarStyle {
366
            width: Some(info.width.clone()),
            // A platform preset states its own handle geometry below; the
            // generic converter keeps the renderer's derived defaults.
366
            handle_width: None,
366
            handle_radius: None,
366
            thumb_color: match info.thumb {
366
                StyleBackgroundContent::Color(c) => Some(c),
                _ => None,
            },
366
            track_color: match info.track {
366
                StyleBackgroundContent::Color(c) => Some(c),
                _ => None,
            },
        }
366
    }
    // --- Windows Styles ---
    /// Windows 11 light mode defaults (Segoe UI Variable, `WinUI` 3 colors).
    #[must_use]
41
    pub fn windows_11_light() -> SystemStyle {
41
        SystemStyle {
41
            theme: Theme::Light,
41
            platform: Platform::Windows,
41
            colors: SystemColors {
41
                text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
41
                background: OptionColorU::Some(ColorU::new_rgb(243, 243, 243)),
41
                accent: OptionColorU::Some(ColorU::new_rgb(0, 95, 184)),
41
                window_background: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
41
                selection_background: OptionColorU::Some(ColorU::new_rgb(0, 120, 215)),
41
                selection_text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
41
                ..Default::default()
41
            },
41
            fonts: SystemFonts {
41
                ui_font: OptionString::Some("Segoe UI Variable Text".into()),
41
                ui_font_size: OptionF32::Some(9.0),
41
                monospace_font: OptionString::Some("Consolas".into()),
41
                ..Default::default()
41
            },
41
            metrics: SystemMetrics {
41
                corner_radius: OptionPixelValue::Some(PixelValue::px(4.0)),
41
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
41
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(12.0)),
41
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(6.0)),
41
                titlebar: TitlebarMetrics::windows(),
41
            },
41
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
41
                &SCROLLBAR_WINDOWS_LIGHT,
41
            ))),
41
            app_specific_stylesheet: None,
41
            run_destructor: true,
41
            icon_style: IconStyleOptions::default(),
41
            language: AzString::from_const_str("en-US"),
41
            os_version: OsVersion::WIN_11,
41
            prefers_reduced_motion: BoolCondition::False,
41
            prefers_high_contrast: BoolCondition::False,
41
            scroll_physics: ScrollPhysics::windows(),
41
            linux: LinuxCustomization::default(),
41
            focus_visuals: FocusVisuals::default(),
41
            handedness: Handedness::default(),
41
            accessibility: AccessibilitySettings::default(),
41
            input: InputMetrics::default(),
41
            text_rendering: TextRenderingHints::default(),
41
            scrollbar_preferences: ScrollbarPreferences::default(),
41
            visual_hints: VisualHints::default(),
41
            animation: AnimationMetrics::default(),
41
            audio: AudioMetrics::default(),
41
        }
41
    }
    /// Windows 11 dark mode defaults (Segoe UI Variable, `WinUI` 3 dark colors).
    #[must_use]
20
    pub fn windows_11_dark() -> SystemStyle {
20
        SystemStyle {
20
            theme: Theme::Dark,
20
            platform: Platform::Windows,
20
            colors: SystemColors {
20
                text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
20
                background: OptionColorU::Some(ColorU::new_rgb(32, 32, 32)),
20
                accent: OptionColorU::Some(ColorU::new_rgb(0, 120, 215)),
20
                window_background: OptionColorU::Some(ColorU::new_rgb(25, 25, 25)),
20
                selection_background: OptionColorU::Some(ColorU::new_rgb(0, 120, 215)),
20
                selection_text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
20
                ..Default::default()
20
            },
20
            fonts: SystemFonts {
20
                ui_font: OptionString::Some("Segoe UI Variable Text".into()),
20
                ui_font_size: OptionF32::Some(9.0),
20
                monospace_font: OptionString::Some("Consolas".into()),
20
                ..Default::default()
20
            },
20
            metrics: SystemMetrics {
20
                corner_radius: OptionPixelValue::Some(PixelValue::px(4.0)),
20
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
20
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(12.0)),
20
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(6.0)),
20
                titlebar: TitlebarMetrics::windows(),
20
            },
20
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
20
                &SCROLLBAR_WINDOWS_DARK,
20
            ))),
20
            app_specific_stylesheet: None,
20
            run_destructor: true,
20
            icon_style: IconStyleOptions::default(),
20
            language: AzString::from_const_str("en-US"),
20
            os_version: OsVersion::WIN_11,
20
            prefers_reduced_motion: BoolCondition::False,
20
            prefers_high_contrast: BoolCondition::False,
20
            scroll_physics: ScrollPhysics::windows(),
20
            linux: LinuxCustomization::default(),
20
            focus_visuals: FocusVisuals::default(),
20
            handedness: Handedness::default(),
20
            accessibility: AccessibilitySettings::default(),
20
            input: InputMetrics::default(),
20
            text_rendering: TextRenderingHints::default(),
20
            scrollbar_preferences: ScrollbarPreferences::default(),
20
            visual_hints: VisualHints::default(),
20
            animation: AnimationMetrics::default(),
20
            audio: AudioMetrics::default(),
20
        }
20
    }
    /// Windows 7 Aero theme defaults (Segoe UI, classic Aero colors).
    #[must_use]
11
    pub fn windows_7_aero() -> SystemStyle {
11
        SystemStyle {
11
            theme: Theme::Light,
11
            platform: Platform::Windows,
11
            colors: SystemColors {
11
                text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
11
                background: OptionColorU::Some(ColorU::new_rgb(240, 240, 240)),
11
                accent: OptionColorU::Some(ColorU::new_rgb(51, 153, 255)),
11
                window_background: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
11
                selection_background: OptionColorU::Some(ColorU::new_rgb(51, 153, 255)),
11
                selection_text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
11
                ..Default::default()
11
            },
11
            fonts: SystemFonts {
11
                ui_font: OptionString::Some("Segoe UI".into()),
11
                ui_font_size: OptionF32::Some(9.0),
11
                monospace_font: OptionString::Some("Consolas".into()),
11
                ..Default::default()
11
            },
11
            metrics: SystemMetrics {
11
                corner_radius: OptionPixelValue::Some(PixelValue::px(6.0)),
11
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
11
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(10.0)),
11
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(5.0)),
11
                titlebar: TitlebarMetrics::windows(),
11
            },
11
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
11
                &SCROLLBAR_CLASSIC_LIGHT,
11
            ))),
11
            app_specific_stylesheet: None,
11
            run_destructor: true,
11
            icon_style: IconStyleOptions::default(),
11
            language: AzString::from_const_str("en-US"),
11
            os_version: OsVersion::WIN_7,
11
            prefers_reduced_motion: BoolCondition::False,
11
            prefers_high_contrast: BoolCondition::False,
11
            scroll_physics: ScrollPhysics::windows(),
11
            linux: LinuxCustomization::default(),
11
            focus_visuals: FocusVisuals::default(),
11
            handedness: Handedness::default(),
11
            accessibility: AccessibilitySettings::default(),
11
            input: InputMetrics::default(),
11
            text_rendering: TextRenderingHints::default(),
11
            scrollbar_preferences: ScrollbarPreferences::default(),
11
            visual_hints: VisualHints::default(),
11
            animation: AnimationMetrics::default(),
11
            audio: AudioMetrics::default(),
11
        }
11
    }
    /// Windows XP Luna theme defaults (Tahoma, classic Luna blue).
    #[must_use]
11
    pub fn windows_xp_luna() -> SystemStyle {
11
        SystemStyle {
11
            theme: Theme::Light,
11
            platform: Platform::Windows,
11
            colors: SystemColors {
11
                text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
11
                background: OptionColorU::Some(ColorU::new_rgb(236, 233, 216)),
11
                accent: OptionColorU::Some(ColorU::new_rgb(49, 106, 197)),
11
                window_background: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
11
                selection_background: OptionColorU::Some(ColorU::new_rgb(49, 106, 197)),
11
                selection_text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
11
                ..Default::default()
11
            },
11
            fonts: SystemFonts {
11
                ui_font: OptionString::Some("Tahoma".into()),
11
                ui_font_size: OptionF32::Some(8.0),
11
                monospace_font: OptionString::Some("Lucida Console".into()),
11
                ..Default::default()
11
            },
11
            metrics: SystemMetrics {
11
                corner_radius: OptionPixelValue::Some(PixelValue::px(3.0)),
11
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
11
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(8.0)),
11
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(4.0)),
11
                titlebar: TitlebarMetrics::windows(),
11
            },
11
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
11
                &SCROLLBAR_WINDOWS_CLASSIC,
11
            ))),
11
            app_specific_stylesheet: None,
11
            run_destructor: true,
11
            icon_style: IconStyleOptions::default(),
11
            language: AzString::from_const_str("en-US"),
11
            os_version: OsVersion::WIN_XP,
11
            prefers_reduced_motion: BoolCondition::False,
11
            prefers_high_contrast: BoolCondition::False,
11
            scroll_physics: ScrollPhysics::windows(),
11
            linux: LinuxCustomization::default(),
11
            focus_visuals: FocusVisuals::default(),
11
            handedness: Handedness::default(),
11
            accessibility: AccessibilitySettings::default(),
11
            input: InputMetrics::default(),
11
            text_rendering: TextRenderingHints::default(),
11
            scrollbar_preferences: ScrollbarPreferences::default(),
11
            visual_hints: VisualHints::default(),
11
            animation: AnimationMetrics::default(),
11
            audio: AudioMetrics::default(),
11
        }
11
    }
    // --- macOS Styles ---
    /// Modern macOS light mode defaults (SF Pro, rounded corners).
    #[must_use]
7
    pub fn macos_modern_light() -> SystemStyle {
7
        SystemStyle {
7
            platform: Platform::MacOs,
7
            theme: Theme::Light,
7
            colors: SystemColors {
7
                text: OptionColorU::Some(ColorU::new(0, 0, 0, 221)),
7
                background: OptionColorU::Some(ColorU::new_rgb(242, 242, 247)),
7
                accent: OptionColorU::Some(ColorU::new_rgb(0, 122, 255)),
7
                window_background: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
7
                // Default macOS selection uses accent color with transparency
7
                selection_background: OptionColorU::Some(ColorU::new(0, 122, 255, 128)),
7
                selection_text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
7
                ..Default::default()
7
            },
7
            fonts: SystemFonts {
7
                ui_font: OptionString::Some(".SF NS".into()),
7
                ui_font_size: OptionF32::Some(13.0),
7
                monospace_font: OptionString::Some("Menlo".into()),
7
                ..Default::default()
7
            },
7
            metrics: SystemMetrics {
7
                corner_radius: OptionPixelValue::Some(PixelValue::px(8.0)),
7
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
7
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(16.0)),
7
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(6.0)),
7
                titlebar: TitlebarMetrics::macos(),
7
            },
7
            scrollbar: Some(Box::new(scrollbar_info_to_computed(&SCROLLBAR_MACOS_LIGHT))),
7
            app_specific_stylesheet: None,
7
            run_destructor: true,
7
            icon_style: IconStyleOptions::default(),
7
            language: AzString::from_const_str("en-US"),
7
            os_version: OsVersion::MACOS_SONOMA,
7
            prefers_reduced_motion: BoolCondition::False,
7
            prefers_high_contrast: BoolCondition::False,
7
            scroll_physics: ScrollPhysics::macos(),
7
            linux: LinuxCustomization::default(),
7
            focus_visuals: FocusVisuals::default(),
7
            handedness: Handedness::default(),
7
            accessibility: AccessibilitySettings::default(),
7
            input: InputMetrics::default(),
7
            text_rendering: TextRenderingHints::default(),
7
            scrollbar_preferences: ScrollbarPreferences::default(),
7
            visual_hints: VisualHints::default(),
7
            animation: AnimationMetrics::default(),
7
            audio: AudioMetrics::default(),
7
        }
7
    }
    /// Modern macOS dark mode defaults (SF Pro, dark background).
    #[must_use]
7
    pub fn macos_modern_dark() -> SystemStyle {
7
        SystemStyle {
7
            platform: Platform::MacOs,
7
            theme: Theme::Dark,
7
            colors: SystemColors {
7
                text: OptionColorU::Some(ColorU::new(255, 255, 255, 221)),
7
                background: OptionColorU::Some(ColorU::new_rgb(28, 28, 30)),
7
                accent: OptionColorU::Some(ColorU::new_rgb(10, 132, 255)),
7
                window_background: OptionColorU::Some(ColorU::new_rgb(44, 44, 46)),
7
                // Default macOS selection uses accent color with transparency
7
                selection_background: OptionColorU::Some(ColorU::new(10, 132, 255, 128)),
7
                selection_text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
7
                ..Default::default()
7
            },
7
            fonts: SystemFonts {
7
                ui_font: OptionString::Some(".SF NS".into()),
7
                ui_font_size: OptionF32::Some(13.0),
7
                monospace_font: OptionString::Some("SF Mono".into()),
7
                monospace_font_size: OptionF32::Some(12.0),
7
                title_font: OptionString::Some(".SF NS".into()),
7
                title_font_size: OptionF32::Some(13.0),
7
                menu_font: OptionString::Some(".SF NS".into()),
7
                menu_font_size: OptionF32::Some(13.0),
7
                small_font: OptionString::Some(".SF NS".into()),
7
                small_font_size: OptionF32::Some(11.0),
7
                ..Default::default()
7
            },
7
            metrics: SystemMetrics {
7
                corner_radius: OptionPixelValue::Some(PixelValue::px(8.0)),
7
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
7
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(16.0)),
7
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(6.0)),
7
                titlebar: TitlebarMetrics::macos(),
7
            },
7
            scrollbar: Some(Box::new(scrollbar_info_to_computed(&SCROLLBAR_MACOS_DARK))),
7
            app_specific_stylesheet: None,
7
            run_destructor: true,
7
            icon_style: IconStyleOptions::default(),
7
            language: AzString::from_const_str("en-US"),
7
            os_version: OsVersion::MACOS_SONOMA,
7
            prefers_reduced_motion: BoolCondition::False,
7
            prefers_high_contrast: BoolCondition::False,
7
            scroll_physics: ScrollPhysics::macos(),
7
            linux: LinuxCustomization::default(),
7
            focus_visuals: FocusVisuals::default(),
7
            handedness: Handedness::default(),
7
            accessibility: AccessibilitySettings::default(),
7
            input: InputMetrics::default(),
7
            text_rendering: TextRenderingHints::default(),
7
            scrollbar_preferences: ScrollbarPreferences::default(),
7
            visual_hints: VisualHints::default(),
7
            animation: AnimationMetrics::default(),
7
            audio: AudioMetrics::default(),
7
        }
7
    }
    /// Classic macOS Aqua theme defaults (Lucida Grande, gel scrollbars).
    #[must_use]
11
    pub fn macos_aqua() -> SystemStyle {
11
        SystemStyle {
11
            platform: Platform::MacOs,
11
            theme: Theme::Light,
11
            colors: SystemColors {
11
                text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
11
                background: OptionColorU::Some(ColorU::new_rgb(229, 229, 229)),
11
                accent: OptionColorU::Some(ColorU::new_rgb(63, 128, 234)),
11
                window_background: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
11
                ..Default::default()
11
            },
11
            fonts: SystemFonts {
11
                ui_font: OptionString::Some("Lucida Grande".into()),
11
                ui_font_size: OptionF32::Some(13.0),
11
                monospace_font: OptionString::Some("Monaco".into()),
11
                monospace_font_size: OptionF32::Some(12.0),
11
                ..Default::default()
11
            },
11
            metrics: SystemMetrics {
11
                corner_radius: OptionPixelValue::Some(PixelValue::px(12.0)),
11
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
11
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(16.0)),
11
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(6.0)),
11
                titlebar: TitlebarMetrics::macos(),
11
            },
11
            scrollbar: Some(Box::new(scrollbar_info_to_computed(&SCROLLBAR_MACOS_AQUA))),
11
            app_specific_stylesheet: None,
11
            run_destructor: true,
11
            icon_style: IconStyleOptions::default(),
11
            language: AzString::from_const_str("en-US"),
11
            os_version: OsVersion::MACOS_TIGER,
11
            prefers_reduced_motion: BoolCondition::False,
11
            prefers_high_contrast: BoolCondition::False,
11
            scroll_physics: ScrollPhysics::macos(),
11
            linux: LinuxCustomization::default(),
11
            focus_visuals: FocusVisuals::default(),
11
            handedness: Handedness::default(),
11
            accessibility: AccessibilitySettings::default(),
11
            input: InputMetrics::default(),
11
            text_rendering: TextRenderingHints::default(),
11
            scrollbar_preferences: ScrollbarPreferences::default(),
11
            visual_hints: VisualHints::default(),
11
            animation: AnimationMetrics::default(),
11
            audio: AudioMetrics::default(),
11
        }
11
    }
    // --- Linux Styles ---
    /// GNOME Adwaita light theme defaults (Cantarell font).
    #[must_use]
212
    pub fn gnome_adwaita_light() -> SystemStyle {
212
        SystemStyle {
212
            platform: Platform::Linux(DesktopEnvironment::Gnome),
212
            theme: Theme::Light,
212
            colors: SystemColors {
212
                text: OptionColorU::Some(ColorU::new_rgb(46, 52, 54)),
212
                background: OptionColorU::Some(ColorU::new_rgb(249, 249, 249)),
212
                accent: OptionColorU::Some(ColorU::new_rgb(53, 132, 228)),
212
                window_background: OptionColorU::Some(ColorU::new_rgb(237, 237, 237)),
212
                ..Default::default()
212
            },
212
            fonts: SystemFonts {
212
                ui_font: OptionString::Some("Cantarell".into()),
212
                ui_font_size: OptionF32::Some(11.0),
212
                monospace_font: OptionString::Some("Monospace".into()),
212
                ..Default::default()
212
            },
212
            metrics: SystemMetrics {
212
                corner_radius: OptionPixelValue::Some(PixelValue::px(4.0)),
212
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
212
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(12.0)),
212
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(8.0)),
212
                titlebar: TitlebarMetrics::linux_gnome(),
212
            },
212
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
212
                &SCROLLBAR_CLASSIC_LIGHT,
212
            ))),
212
            app_specific_stylesheet: None,
212
            run_destructor: true,
212
            icon_style: IconStyleOptions::default(),
212
            language: AzString::from_const_str("en-US"),
212
            os_version: OsVersion::LINUX_6_0,
212
            prefers_reduced_motion: BoolCondition::False,
212
            prefers_high_contrast: BoolCondition::False,
212
            scroll_physics: ScrollPhysics::default(),
212
            linux: LinuxCustomization::default(),
212
            focus_visuals: FocusVisuals::default(),
212
            handedness: Handedness::default(),
212
            accessibility: AccessibilitySettings::default(),
212
            input: InputMetrics::default(),
212
            text_rendering: TextRenderingHints::default(),
212
            scrollbar_preferences: ScrollbarPreferences::default(),
212
            visual_hints: VisualHints::default(),
212
            animation: AnimationMetrics::default(),
212
            audio: AudioMetrics::default(),
212
        }
212
    }
    /// GNOME Adwaita dark theme defaults (Cantarell font, dark background).
    #[must_use]
9
    pub fn gnome_adwaita_dark() -> SystemStyle {
9
        SystemStyle {
9
            platform: Platform::Linux(DesktopEnvironment::Gnome),
9
            theme: Theme::Dark,
9
            colors: SystemColors {
9
                text: OptionColorU::Some(ColorU::new_rgb(238, 238, 236)),
9
                background: OptionColorU::Some(ColorU::new_rgb(36, 36, 36)),
9
                accent: OptionColorU::Some(ColorU::new_rgb(53, 132, 228)),
9
                window_background: OptionColorU::Some(ColorU::new_rgb(48, 48, 48)),
9
                ..Default::default()
9
            },
9
            fonts: SystemFonts {
9
                ui_font: OptionString::Some("Cantarell".into()),
9
                ui_font_size: OptionF32::Some(11.0),
9
                monospace_font: OptionString::Some("Monospace".into()),
9
                ..Default::default()
9
            },
9
            metrics: SystemMetrics {
9
                corner_radius: OptionPixelValue::Some(PixelValue::px(4.0)),
9
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
9
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(12.0)),
9
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(8.0)),
9
                titlebar: TitlebarMetrics::linux_gnome(),
9
            },
9
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
9
                &SCROLLBAR_CLASSIC_DARK,
9
            ))),
9
            app_specific_stylesheet: None,
9
            run_destructor: true,
9
            icon_style: IconStyleOptions::default(),
9
            language: AzString::from_const_str("en-US"),
9
            os_version: OsVersion::LINUX_6_0,
9
            prefers_reduced_motion: BoolCondition::False,
9
            prefers_high_contrast: BoolCondition::False,
9
            scroll_physics: ScrollPhysics::default(),
9
            linux: LinuxCustomization::default(),
9
            focus_visuals: FocusVisuals::default(),
9
            handedness: Handedness::default(),
9
            accessibility: AccessibilitySettings::default(),
9
            input: InputMetrics::default(),
9
            text_rendering: TextRenderingHints::default(),
9
            scrollbar_preferences: ScrollbarPreferences::default(),
9
            visual_hints: VisualHints::default(),
9
            animation: AnimationMetrics::default(),
9
            audio: AudioMetrics::default(),
9
        }
9
    }
    /// GTK2 Clearlooks theme defaults (`DejaVu` Sans, orange accent).
    #[must_use]
11
    pub fn gtk2_clearlooks() -> SystemStyle {
11
        SystemStyle {
11
            platform: Platform::Linux(DesktopEnvironment::Gnome),
11
            theme: Theme::Light,
11
            colors: SystemColors {
11
                text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
11
                background: OptionColorU::Some(ColorU::new_rgb(239, 239, 239)),
11
                accent: OptionColorU::Some(ColorU::new_rgb(245, 121, 0)),
11
                ..Default::default()
11
            },
11
            fonts: SystemFonts {
11
                ui_font: OptionString::Some("DejaVu Sans".into()),
11
                ui_font_size: OptionF32::Some(10.0),
11
                monospace_font: OptionString::Some("DejaVu Sans Mono".into()),
11
                ..Default::default()
11
            },
11
            metrics: SystemMetrics {
11
                corner_radius: OptionPixelValue::Some(PixelValue::px(4.0)),
11
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
11
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(10.0)),
11
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(6.0)),
11
                titlebar: TitlebarMetrics::linux_gnome(),
11
            },
11
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
11
                &SCROLLBAR_CLASSIC_LIGHT,
11
            ))),
11
            app_specific_stylesheet: None,
11
            run_destructor: true,
11
            icon_style: IconStyleOptions::default(),
11
            language: AzString::from_const_str("en-US"),
11
            os_version: OsVersion::LINUX_2_6,
11
            prefers_reduced_motion: BoolCondition::False,
11
            prefers_high_contrast: BoolCondition::False,
11
            scroll_physics: ScrollPhysics::default(),
11
            linux: LinuxCustomization::default(),
11
            focus_visuals: FocusVisuals::default(),
11
            handedness: Handedness::default(),
11
            accessibility: AccessibilitySettings::default(),
11
            input: InputMetrics::default(),
11
            text_rendering: TextRenderingHints::default(),
11
            scrollbar_preferences: ScrollbarPreferences::default(),
11
            visual_hints: VisualHints::default(),
11
            animation: AnimationMetrics::default(),
11
            audio: AudioMetrics::default(),
11
        }
11
    }
    /// KDE Breeze LIGHT defaults — the stock `BreezeLight` colour scheme, so a
    /// KDE session that reads back nothing still looks like KDE rather than
    /// like GNOME.
    ///
    /// The values are Breeze's own `kdeglobals` groups: `Colors:Window` for the
    /// window chrome, `Colors:View` for content surfaces, `Colors:Button` for
    /// controls and `Colors:Selection` for highlights. `discover_kde_style`
    /// overwrites each one it can actually read; these are what survives when
    /// `kreadconfig` is absent or the user never customised the scheme.
    #[must_use]
7
    pub fn kde_breeze_light() -> SystemStyle {
7
        SystemStyle {
7
            platform: Platform::Linux(DesktopEnvironment::Kde),
7
            theme: Theme::Light,
7
            colors: SystemColors {
7
                // Colors:View — content surfaces (the text edit, the list).
7
                text: OptionColorU::Some(ColorU::new_rgb(35, 38, 41)),
7
                background: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
7
                // Colors:Window — dialogs and panels behind the content.
7
                window_background: OptionColorU::Some(ColorU::new_rgb(239, 240, 241)),
7
                under_page_background: OptionColorU::Some(ColorU::new_rgb(239, 240, 241)),
7
                // Colors:Selection — Breeze's signature blue.
7
                accent: OptionColorU::Some(ColorU::new_rgb(61, 174, 233)),
7
                accent_text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
7
                selection_background: OptionColorU::Some(ColorU::new_rgb(61, 174, 233)),
7
                selection_text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
7
                // Colors:Button.
7
                button_face: OptionColorU::Some(ColorU::new_rgb(252, 252, 252)),
7
                button_text: OptionColorU::Some(ColorU::new_rgb(35, 38, 41)),
7
                // ForegroundInactive is what Breeze greys disabled text with.
7
                disabled_text: OptionColorU::Some(ColorU::new_rgb(112, 125, 138)),
7
                secondary_text: OptionColorU::Some(ColorU::new_rgb(112, 125, 138)),
7
                link: OptionColorU::Some(ColorU::new_rgb(41, 128, 185)),
7
                separator: OptionColorU::Some(ColorU::new_rgb(227, 229, 231)),
7
                ..Default::default()
7
            },
7
            fonts: SystemFonts {
7
                ui_font: OptionString::Some("Noto Sans".into()),
7
                ui_font_size: OptionF32::Some(10.0),
7
                monospace_font: OptionString::Some("Hack".into()),
7
                // Breeze uses the general font for menus and a 8pt face for
7
                // secondary text (`smallestReadableFont`).
7
                menu_font: OptionString::Some("Noto Sans".into()),
7
                menu_font_size: OptionF32::Some(10.0),
7
                small_font: OptionString::Some("Noto Sans".into()),
7
                small_font_size: OptionF32::Some(8.0),
7
                ..Default::default()
7
            },
7
            metrics: SystemMetrics {
7
                corner_radius: OptionPixelValue::Some(PixelValue::px(3.0)),
7
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
7
                // Breeze `Metrics`: buttons are tighter than Adwaita's.
7
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(8.0)),
7
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(4.0)),
7
                titlebar: TitlebarMetrics::linux_gnome(),
7
            },
7
            scrollbar: Some(Box::new(scrollbar_info_to_computed(&SCROLLBAR_KDE_OXYGEN))),
7
            app_specific_stylesheet: None,
7
            run_destructor: true,
7
            icon_style: IconStyleOptions::default(),
7
            language: AzString::from_const_str("en-US"),
7
            os_version: OsVersion::LINUX_6_0,
7
            prefers_reduced_motion: BoolCondition::False,
7
            prefers_high_contrast: BoolCondition::False,
7
            scroll_physics: ScrollPhysics::default(),
7
            linux: LinuxCustomization::default(),
7
            focus_visuals: FocusVisuals::default(),
7
            handedness: Handedness::default(),
7
            accessibility: AccessibilitySettings::default(),
7
            input: InputMetrics::default(),
7
            text_rendering: TextRenderingHints::default(),
7
            scrollbar_preferences: ScrollbarPreferences::default(),
7
            visual_hints: VisualHints::default(),
7
            animation: AnimationMetrics::default(),
7
            audio: AudioMetrics::default(),
7
        }
7
    }
    /// KDE Breeze DARK defaults — the stock `BreezeDark` colour scheme.
    ///
    /// The counterpart to [`kde_breeze_light`], and the reason it exists: a
    /// KDE dark session used to fall back to GNOME Adwaita Dark, which is a
    /// different grey (`#242424` vs Breeze's `#2a2e32`) with a different
    /// accent — so a dark KDE desktop rendered visibly not-KDE. Values are
    /// Breeze's own `kdeglobals` groups, same mapping as the light preset.
    #[must_use]
    pub fn kde_breeze_dark() -> SystemStyle {
        SystemStyle {
            platform: Platform::Linux(DesktopEnvironment::Kde),
            theme: Theme::Dark,
            colors: SystemColors {
                // Colors:View.
                text: OptionColorU::Some(ColorU::new_rgb(252, 252, 252)),
                background: OptionColorU::Some(ColorU::new_rgb(27, 30, 32)),
                // Colors:Window.
                window_background: OptionColorU::Some(ColorU::new_rgb(42, 46, 50)),
                under_page_background: OptionColorU::Some(ColorU::new_rgb(42, 46, 50)),
                // Colors:Selection — the same Breeze blue in both themes.
                accent: OptionColorU::Some(ColorU::new_rgb(61, 174, 233)),
                accent_text: OptionColorU::Some(ColorU::new_rgb(252, 252, 252)),
                selection_background: OptionColorU::Some(ColorU::new_rgb(61, 174, 233)),
                selection_text: OptionColorU::Some(ColorU::new_rgb(252, 252, 252)),
                // Colors:Button.
                button_face: OptionColorU::Some(ColorU::new_rgb(49, 54, 59)),
                button_text: OptionColorU::Some(ColorU::new_rgb(252, 252, 252)),
                disabled_text: OptionColorU::Some(ColorU::new_rgb(161, 169, 177)),
                secondary_text: OptionColorU::Some(ColorU::new_rgb(161, 169, 177)),
                link: OptionColorU::Some(ColorU::new_rgb(29, 153, 243)),
                separator: OptionColorU::Some(ColorU::new_rgb(49, 54, 59)),
                ..Default::default()
            },
            fonts: SystemFonts {
                ui_font: OptionString::Some("Noto Sans".into()),
                ui_font_size: OptionF32::Some(10.0),
                monospace_font: OptionString::Some("Hack".into()),
                menu_font: OptionString::Some("Noto Sans".into()),
                menu_font_size: OptionF32::Some(10.0),
                small_font: OptionString::Some("Noto Sans".into()),
                small_font_size: OptionF32::Some(8.0),
                ..Default::default()
            },
            metrics: SystemMetrics {
                corner_radius: OptionPixelValue::Some(PixelValue::px(3.0)),
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(8.0)),
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(4.0)),
                titlebar: TitlebarMetrics::linux_gnome(),
            },
            // `SCROLLBAR_KDE_OXYGEN` is a LIGHT scrollbar (track #f2f2f2,
            // thumb #b1b1b1): correct for Breeze Light, glaring on a dark
            // desktop. The dark preset takes the dark classic bar, exactly as
            // `gnome_adwaita_dark` does.
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
                &SCROLLBAR_CLASSIC_DARK,
            ))),
            app_specific_stylesheet: None,
            run_destructor: true,
            icon_style: IconStyleOptions::default(),
            language: AzString::from_const_str("en-US"),
            os_version: OsVersion::LINUX_6_0,
            prefers_reduced_motion: BoolCondition::False,
            prefers_high_contrast: BoolCondition::False,
            scroll_physics: ScrollPhysics::default(),
            linux: LinuxCustomization::default(),
            focus_visuals: FocusVisuals::default(),
            handedness: Handedness::default(),
            accessibility: AccessibilitySettings::default(),
            input: InputMetrics::default(),
            text_rendering: TextRenderingHints::default(),
            scrollbar_preferences: ScrollbarPreferences::default(),
            visual_hints: VisualHints::default(),
            animation: AnimationMetrics::default(),
            audio: AudioMetrics::default(),
        }
    }
    // --- Mobile Styles ---
    /// Android Material Design light theme defaults (Roboto font).
    #[must_use]
6
    pub fn android_material_light() -> SystemStyle {
6
        SystemStyle {
6
            platform: Platform::Android,
6
            theme: Theme::Light,
6
            colors: SystemColors {
6
                text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
6
                background: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
6
                accent: OptionColorU::Some(ColorU::new_rgb(98, 0, 238)),
6
                ..Default::default()
6
            },
6
            fonts: SystemFonts {
6
                ui_font: OptionString::Some("Roboto".into()),
6
                ui_font_size: OptionF32::Some(14.0),
6
                monospace_font: OptionString::Some("Droid Sans Mono".into()),
6
                ..Default::default()
6
            },
6
            metrics: SystemMetrics {
6
                corner_radius: OptionPixelValue::Some(PixelValue::px(12.0)),
6
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
6
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(16.0)),
6
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(10.0)),
6
                titlebar: TitlebarMetrics::android(),
6
            },
6
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
6
                &SCROLLBAR_ANDROID_LIGHT,
6
            ))),
6
            app_specific_stylesheet: None,
6
            run_destructor: true,
6
            icon_style: IconStyleOptions::default(),
6
            language: AzString::from_const_str("en-US"),
6
            os_version: OsVersion::ANDROID_14,
6
            prefers_reduced_motion: BoolCondition::False,
6
            prefers_high_contrast: BoolCondition::False,
6
            scroll_physics: ScrollPhysics::android(),
6
            linux: LinuxCustomization::default(),
6
            focus_visuals: FocusVisuals::default(),
6
            handedness: Handedness::default(),
6
            accessibility: AccessibilitySettings::default(),
6
            input: InputMetrics::default(),
6
            text_rendering: TextRenderingHints::default(),
6
            scrollbar_preferences: ScrollbarPreferences::default(),
6
            visual_hints: VisualHints::default(),
6
            animation: AnimationMetrics::default(),
6
            audio: AudioMetrics::default(),
6
        }
6
    }
    /// Android Holo dark theme defaults (Roboto font, dark background).
    #[must_use]
7
    pub fn android_holo_dark() -> SystemStyle {
7
        SystemStyle {
7
            platform: Platform::Android,
7
            theme: Theme::Dark,
7
            colors: SystemColors {
7
                text: OptionColorU::Some(ColorU::new_rgb(255, 255, 255)),
7
                background: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
7
                accent: OptionColorU::Some(ColorU::new_rgb(51, 181, 229)),
7
                ..Default::default()
7
            },
7
            fonts: SystemFonts {
7
                ui_font: OptionString::Some("Roboto".into()),
7
                ui_font_size: OptionF32::Some(14.0),
7
                monospace_font: OptionString::Some("Droid Sans Mono".into()),
7
                ..Default::default()
7
            },
7
            metrics: SystemMetrics {
7
                corner_radius: OptionPixelValue::Some(PixelValue::px(2.0)),
7
                border_width: OptionPixelValue::Some(PixelValue::px(1.0)),
7
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(12.0)),
7
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(8.0)),
7
                titlebar: TitlebarMetrics::android(),
7
            },
7
            scrollbar: Some(Box::new(scrollbar_info_to_computed(
7
                &SCROLLBAR_ANDROID_DARK,
7
            ))),
7
            app_specific_stylesheet: None,
7
            run_destructor: true,
7
            icon_style: IconStyleOptions::default(),
7
            language: AzString::from_const_str("en-US"),
7
            os_version: OsVersion::ANDROID_ICE_CREAM_SANDWICH,
7
            prefers_reduced_motion: BoolCondition::False,
7
            prefers_high_contrast: BoolCondition::False,
7
            scroll_physics: ScrollPhysics::android(),
7
            linux: LinuxCustomization::default(),
7
            focus_visuals: FocusVisuals::default(),
7
            handedness: Handedness::default(),
7
            accessibility: AccessibilitySettings::default(),
7
            input: InputMetrics::default(),
7
            text_rendering: TextRenderingHints::default(),
7
            scrollbar_preferences: ScrollbarPreferences::default(),
7
            visual_hints: VisualHints::default(),
7
            animation: AnimationMetrics::default(),
7
            audio: AudioMetrics::default(),
7
        }
7
    }
    /// iOS light theme defaults (SF UI font, rounded corners).
    #[must_use]
6
    pub fn ios_light() -> SystemStyle {
6
        SystemStyle {
6
            platform: Platform::Ios,
6
            theme: Theme::Light,
6
            colors: SystemColors {
6
                text: OptionColorU::Some(ColorU::new_rgb(0, 0, 0)),
6
                background: OptionColorU::Some(ColorU::new_rgb(242, 242, 247)),
6
                accent: OptionColorU::Some(ColorU::new_rgb(0, 122, 255)),
6
                ..Default::default()
6
            },
6
            fonts: SystemFonts {
6
                ui_font: OptionString::Some(".SFUI-Display-Regular".into()),
6
                ui_font_size: OptionF32::Some(17.0),
6
                monospace_font: OptionString::Some("Menlo".into()),
6
                ..Default::default()
6
            },
6
            metrics: SystemMetrics {
6
                corner_radius: OptionPixelValue::Some(PixelValue::px(10.0)),
6
                border_width: OptionPixelValue::Some(PixelValue::px(0.5)),
6
                button_padding_horizontal: OptionPixelValue::Some(PixelValue::px(20.0)),
6
                button_padding_vertical: OptionPixelValue::Some(PixelValue::px(12.0)),
6
                titlebar: TitlebarMetrics::ios(),
6
            },
6
            scrollbar: Some(Box::new(scrollbar_info_to_computed(&SCROLLBAR_IOS_LIGHT))),
6
            app_specific_stylesheet: None,
6
            run_destructor: true,
6
            icon_style: IconStyleOptions::default(),
6
            language: AzString::from_const_str("en-US"),
6
            os_version: OsVersion::IOS_17,
6
            prefers_reduced_motion: BoolCondition::False,
6
            prefers_high_contrast: BoolCondition::False,
6
            scroll_physics: ScrollPhysics::ios(),
6
            linux: LinuxCustomization::default(),
6
            focus_visuals: FocusVisuals::default(),
6
            handedness: Handedness::default(),
6
            accessibility: AccessibilitySettings::default(),
6
            input: InputMetrics::default(),
6
            text_rendering: TextRenderingHints::default(),
6
            scrollbar_preferences: ScrollbarPreferences::default(),
6
            visual_hints: VisualHints::default(),
6
            animation: AnimationMetrics::default(),
6
            audio: AudioMetrics::default(),
6
        }
6
    }
}
#[cfg(test)]
mod autotest_generated {
    use super::*;
    use crate::css::rule_priority;
    const ALL_FONT_TYPES: [SystemFontType; 11] = [
        SystemFontType::Ui,
        SystemFontType::UiBold,
        SystemFontType::Monospace,
        SystemFontType::MonospaceBold,
        SystemFontType::MonospaceItalic,
        SystemFontType::Title,
        SystemFontType::TitleBold,
        SystemFontType::Menu,
        SystemFontType::Small,
        SystemFontType::Serif,
        SystemFontType::SerifBold,
    ];
    fn all_platforms() -> Vec<Platform> {
        vec![
            Platform::Windows,
            Platform::MacOs,
            Platform::Linux(DesktopEnvironment::Gnome),
            Platform::Linux(DesktopEnvironment::Kde),
            Platform::Linux(DesktopEnvironment::Other(AzString::from_const_str(
                "Hyprland",
            ))),
            Platform::Android,
            Platform::Ios,
            Platform::Unknown,
        ]
    }
    /// Every hard-coded default style, so the smoke tests can sweep all of them.
    fn all_default_styles() -> Vec<(&'static str, SystemStyle)> {
        vec![
            ("windows_11_light", defaults::windows_11_light()),
            ("windows_11_dark", defaults::windows_11_dark()),
            ("windows_7_aero", defaults::windows_7_aero()),
            ("windows_xp_luna", defaults::windows_xp_luna()),
            ("macos_modern_light", defaults::macos_modern_light()),
            ("macos_modern_dark", defaults::macos_modern_dark()),
            ("macos_aqua", defaults::macos_aqua()),
            ("gnome_adwaita_light", defaults::gnome_adwaita_light()),
            ("gnome_adwaita_dark", defaults::gnome_adwaita_dark()),
            ("gtk2_clearlooks", defaults::gtk2_clearlooks()),
            ("kde_breeze_light", defaults::kde_breeze_light()),
            ("android_material_light", defaults::android_material_light()),
            ("android_holo_dark", defaults::android_holo_dark()),
            ("ios_light", defaults::ios_light()),
        ]
    }
    // ── SystemFontType::from_css_str — parser ────────────────────────────
    #[test]
    fn from_css_str_valid_minimal() {
        assert_eq!(
            SystemFontType::from_css_str("system:ui"),
            Some(SystemFontType::Ui)
        );
        assert_eq!(
            SystemFontType::from_css_str("system:monospace:italic"),
            Some(SystemFontType::MonospaceItalic)
        );
    }
    #[test]
    fn from_css_str_empty_input_returns_none() {
        assert_eq!(SystemFontType::from_css_str(""), None);
    }
    #[test]
    fn from_css_str_whitespace_only_returns_none() {
        for s in ["   ", "\t\n", "\r\n\r\n", "\t \t \n"] {
            assert_eq!(SystemFontType::from_css_str(s), None, "input {s:?}");
        }
    }
    #[test]
    fn from_css_str_prefix_only_is_none_and_does_not_panic_on_slice() {
        // Exactly 7 bytes: `&s[7..]` slices right at the end of the string.
        assert_eq!(SystemFontType::from_css_str("system:"), None);
        assert_eq!(SystemFontType::from_css_str("  system:  "), None);
        assert_eq!(SystemFontType::from_css_str("system::"), None);
    }
    #[test]
    fn from_css_str_garbage_returns_none() {
        for s in [
            ";;;",
            "{}{}",
            "\0\u{1}\u{2}\u{7f}",
            "system",
            "systemui",
            "system;ui",
            "system:ui:",
            ":system:ui",
            "font-family: system:ui;",
            "\\system:ui",
            "system:ui\0",
            "system:\u{0}ui",
        ] {
            assert_eq!(SystemFontType::from_css_str(s), None, "input {s:?}");
        }
    }
    #[test]
    fn from_css_str_leading_trailing_junk() {
        // Surrounding ASCII whitespace is trimmed …
        assert_eq!(
            SystemFontType::from_css_str("  system:ui  "),
            Some(SystemFontType::Ui)
        );
        assert_eq!(
            SystemFontType::from_css_str("\t\nsystem:monospace\r\n"),
            Some(SystemFontType::Monospace)
        );
        // … but any other junk is rejected outright.
        assert_eq!(SystemFontType::from_css_str("system:ui;garbage"), None);
        assert_eq!(SystemFontType::from_css_str("garbage system:ui"), None);
        assert_eq!(SystemFontType::from_css_str("system:ui system:ui"), None);
        assert_eq!(SystemFontType::from_css_str("system: ui"), None);
        assert_eq!(SystemFontType::from_css_str("system:ui:bold:extra"), None);
    }
    #[test]
    fn from_css_str_is_case_sensitive() {
        // Documents current behaviour: unlike `AZ_RICING`, the font keyword
        // is matched case-sensitively, so upper/mixed case is rejected.
        for s in [
            "SYSTEM:UI",
            "System:Ui",
            "system:UI",
            "System:ui",
            "sYsTeM:ui",
        ] {
            assert_eq!(SystemFontType::from_css_str(s), None, "input {s:?}");
        }
    }
    #[test]
    fn from_css_str_boundary_numbers() {
        for s in [
            "0",
            "-0",
            "9223372036854775807",
            "-9223372036854775808",
            "NaN",
            "inf",
            "-inf",
            "1e400",
            "system:0",
            "system:-1",
            "system:NaN",
            "system:inf",
            "system:9223372036854775807",
        ] {
            assert_eq!(SystemFontType::from_css_str(s), None, "input {s:?}");
        }
    }
    #[test]
    fn from_css_str_unicode_does_not_panic() {
        for s in [
            "\u{1F600}",
            "system:\u{1F600}",
            "system:ui\u{0301}", // combining acute accent
            "\u{1F600}system:ui",
            "systém:ui",         // non-ASCII inside the prefix
            "system:ui",   // fullwidth latin
            "system:\u{202E}ui", // right-to-left override
            "system:\u{FFFD}",
            "system:ui\u{200B}", // zero-width space (not trimmed)
        ] {
            assert_eq!(SystemFontType::from_css_str(s), None, "input {s:?}");
        }
    }
    #[test]
    fn from_css_str_extremely_long_input_does_not_hang() {
        let long = format!("system:{}", "u".repeat(1_000_000));
        assert_eq!(SystemFontType::from_css_str(&long), None);
        // A valid keyword with a megabyte of trailing junk is still invalid.
        let long_suffix = format!("system:ui{}", "x".repeat(1_000_000));
        assert_eq!(SystemFontType::from_css_str(&long_suffix), None);
        // A megabyte of whitespace around a valid keyword still parses.
        let padded = format!("{}system:ui{}", " ".repeat(100_000), " ".repeat(100_000));
        assert_eq!(
            SystemFontType::from_css_str(&padded),
            Some(SystemFontType::Ui)
        );
    }
    #[test]
    fn from_css_str_deeply_nested_input_does_not_stack_overflow() {
        let nested = format!("system:{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert_eq!(SystemFontType::from_css_str(&nested), None);
        let brackets = format!("system:{}", "[".repeat(10_000));
        assert_eq!(SystemFontType::from_css_str(&brackets), None);
    }
    // ── SystemFontType round-trip / getters ──────────────────────────────
    #[test]
    fn font_type_css_str_round_trips() {
        for ty in ALL_FONT_TYPES {
            let s = ty.as_css_str();
            assert_eq!(
                SystemFontType::from_css_str(s),
                Some(ty),
                "round-trip of {ty:?}"
            );
            // Padding must not change the decoded value.
            assert_eq!(
                SystemFontType::from_css_str(&format!("  {s}\t")),
                Some(ty),
                "padded round-trip of {ty:?}"
            );
        }
    }
    #[test]
    fn font_type_css_str_is_well_formed_and_unique() {
        let mut seen: Vec<&'static str> = Vec::new();
        for ty in ALL_FONT_TYPES {
            let s = ty.as_css_str();
            assert!(s.starts_with("system:"), "{ty:?} -> {s:?}");
            assert!(s.len() > "system:".len(), "{ty:?} has an empty keyword");
            assert_eq!(s.trim(), s, "{ty:?} -> {s:?} has surrounding whitespace");
            assert!(s.is_ascii(), "{ty:?} -> {s:?} is not ASCII");
            seen.push(s);
        }
        seen.sort_unstable();
        assert!(
            seen.windows(2).all(|w| w[0] != w[1]),
            "as_css_str() is not injective: {seen:?}"
        );
    }
    #[test]
    fn font_type_default_is_ui() {
        let d = SystemFontType::default();
        assert_eq!(d, SystemFontType::Ui);
        assert_eq!(d.as_css_str(), "system:ui");
        assert!(!d.is_bold());
        assert!(!d.is_italic());
    }
    // ── SystemFontType::is_bold / is_italic — predicates ─────────────────
    #[test]
    fn is_bold_matches_exactly_the_bold_variants() {
        assert!(SystemFontType::UiBold.is_bold());
        assert!(SystemFontType::MonospaceBold.is_bold());
        assert!(SystemFontType::TitleBold.is_bold());
        assert!(SystemFontType::SerifBold.is_bold());
        assert!(!SystemFontType::Ui.is_bold());
        assert!(!SystemFontType::Monospace.is_bold());
        assert!(!SystemFontType::MonospaceItalic.is_bold());
        assert!(!SystemFontType::Title.is_bold());
        assert!(!SystemFontType::Menu.is_bold());
        assert!(!SystemFontType::Small.is_bold());
        assert!(!SystemFontType::Serif.is_bold());
    }
    #[test]
    fn is_italic_matches_exactly_the_italic_variant() {
        assert!(SystemFontType::MonospaceItalic.is_italic());
        for ty in ALL_FONT_TYPES {
            if ty != SystemFontType::MonospaceItalic {
                assert!(!ty.is_italic(), "{ty:?} must not be italic");
            }
        }
    }
    #[test]
    fn predicates_agree_with_the_css_keyword() {
        for ty in ALL_FONT_TYPES {
            let s = ty.as_css_str();
            assert_eq!(ty.is_bold(), s.ends_with(":bold"), "{ty:?} -> {s:?}");
            assert_eq!(ty.is_italic(), s.ends_with(":italic"), "{ty:?} -> {s:?}");
            // No variant is both bold and italic.
            assert!(
                !(ty.is_bold() && ty.is_italic()),
                "{ty:?} is bold *and* italic"
            );
        }
    }
    // ── SystemFontType::get_fallback_chain (+ private per-OS chains) ─────
    #[test]
    fn fallback_chains_are_non_empty_and_deduplicated() {
        for platform in all_platforms() {
            for ty in ALL_FONT_TYPES {
                let chain = ty.get_fallback_chain(&platform);
                assert!(
                    !chain.is_empty(),
                    "{ty:?} on {platform:?} has an empty chain"
                );
                assert!(
                    chain.iter().all(|f| !f.trim().is_empty()),
                    "{ty:?} on {platform:?} has a blank family: {chain:?}"
                );
                let mut sorted = chain.clone();
                sorted.sort_unstable();
                assert!(
                    sorted.windows(2).all(|w| w[0] != w[1]),
                    "{ty:?} on {platform:?} lists a duplicate family: {chain:?}"
                );
            }
        }
    }
    #[test]
    fn fallback_chain_is_deterministic() {
        for platform in all_platforms() {
            for ty in ALL_FONT_TYPES {
                assert_eq!(
                    ty.get_fallback_chain(&platform),
                    ty.get_fallback_chain(&platform),
                    "{ty:?} on {platform:?} is not deterministic"
                );
            }
        }
    }
    #[test]
    fn ios_shares_the_macos_fallback_chain() {
        for ty in ALL_FONT_TYPES {
            assert_eq!(
                ty.get_fallback_chain(&Platform::Ios),
                ty.get_fallback_chain(&Platform::MacOs),
                "{ty:?}"
            );
        }
    }
    #[test]
    fn linux_fallback_chain_ignores_the_desktop_environment() {
        let gnome = Platform::Linux(DesktopEnvironment::Gnome);
        let kde = Platform::Linux(DesktopEnvironment::Kde);
        let other = Platform::Linux(DesktopEnvironment::Other(AzString::from_const_str("")));
        for ty in ALL_FONT_TYPES {
            let a = ty.get_fallback_chain(&gnome);
            assert_eq!(a, ty.get_fallback_chain(&kde), "{ty:?}");
            assert_eq!(a, ty.get_fallback_chain(&other), "{ty:?}");
        }
    }
    #[test]
    fn unknown_platform_falls_back_to_generic_css_families() {
        for ty in ALL_FONT_TYPES {
            let chain = ty.get_fallback_chain(&Platform::Unknown);
            assert_eq!(chain.len(), 1, "{ty:?} -> {chain:?}");
            let expected = if ty.is_italic()
                || matches!(
                    ty,
                    SystemFontType::Monospace | SystemFontType::MonospaceBold
                ) {
                "monospace"
            } else if matches!(ty, SystemFontType::Serif | SystemFontType::SerifBold) {
                "serif"
            } else {
                "sans-serif"
            };
            assert_eq!(chain[0], expected, "{ty:?}");
        }
    }
    #[test]
    fn monospace_variants_share_one_chain_per_platform() {
        for platform in all_platforms() {
            let base = SystemFontType::Monospace.get_fallback_chain(&platform);
            assert_eq!(
                SystemFontType::MonospaceBold.get_fallback_chain(&platform),
                base,
                "{platform:?}"
            );
            assert_eq!(
                SystemFontType::MonospaceItalic.get_fallback_chain(&platform),
                base,
                "{platform:?}"
            );
        }
    }
    // ── Platform::current ────────────────────────────────────────────────
    #[test]
    fn platform_current_is_deterministic_and_matches_target_os() {
        let a = Platform::current();
        assert_eq!(a, Platform::current());
        #[cfg(target_os = "linux")]
        assert!(matches!(a, Platform::Linux(_)), "{a:?}");
        #[cfg(target_os = "windows")]
        assert_eq!(a, Platform::Windows);
        #[cfg(target_os = "macos")]
        assert_eq!(a, Platform::MacOs);
        #[cfg(target_os = "android")]
        assert_eq!(a, Platform::Android);
        #[cfg(target_os = "ios")]
        assert_eq!(a, Platform::Ios);
        // `current()` never reports the fallback on a supported OS.
        #[cfg(any(
            target_os = "linux",
            target_os = "windows",
            target_os = "macos",
            target_os = "android",
            target_os = "ios"
        ))]
        assert_ne!(a, Platform::Unknown);
        // Default is the "we don't know" variant, not the compiled-for one.
        assert_eq!(Platform::default(), Platform::Unknown);
    }
    // ── TitlebarMetrics constructors ─────────────────────────────────────
    #[test]
    fn titlebar_metrics_have_sane_geometry() {
        // NB: TitlebarMetrics::default() is deliberately the "unknown" variant (all-None,
        // so SystemMetrics::default() can represent "not detected" and resolve() falls
        // back) — it is NOT a rendering profile, so it is excluded here. The platform
        // constructors below are the ones that must carry concrete, sane geometry.
        let all = [
            ("windows", TitlebarMetrics::windows()),
            ("macos", TitlebarMetrics::macos()),
            ("linux_gnome", TitlebarMetrics::linux_gnome()),
            ("ios", TitlebarMetrics::ios()),
            ("android", TitlebarMetrics::android()),
        ];
        for (name, tm) in all {
            let height = tm
                .height
                .as_ref()
                .map(|p| p.to_pixels_internal(0.0, 0.0, 0.0))
                .expect("titlebar height must be set");
            assert!(
                height.is_finite() && height > 0.0,
                "{name}: height {height}"
            );
            let button_area = tm
                .button_area_width
                .as_ref()
                .map(|p| p.to_pixels_internal(0.0, 0.0, 0.0))
                .expect("button area width must be set");
            assert!(
                button_area.is_finite() && button_area >= 0.0,
                "{name}: button_area_width {button_area}"
            );
            let padding = tm
                .padding_horizontal
                .as_ref()
                .map(|p| p.to_pixels_internal(0.0, 0.0, 0.0))
                .expect("padding must be set");
            assert!(
                padding.is_finite() && padding >= 0.0,
                "{name}: padding {padding}"
            );
            let size = tm
                .title_font_size
                .into_option()
                .expect("font size must be set");
            assert!(size.is_finite() && size > 0.0, "{name}: font size {size}");
            let weight = tm
                .title_font_weight
                .into_option()
                .expect("font weight must be set");
            assert!((100..=900).contains(&weight), "{name}: weight {weight}");
        }
    }
    #[test]
    fn titlebar_metrics_match_their_platform_conventions() {
        let win = TitlebarMetrics::windows();
        assert_eq!(win.button_side, TitlebarButtonSide::Right);
        assert!(win.buttons.has_close && win.buttons.has_minimize && win.buttons.has_maximize);
        assert!(!win.buttons.has_fullscreen);
        // macOS: traffic lights on the left, zoom replaced by fullscreen.
        let mac = TitlebarMetrics::macos();
        assert_eq!(mac.button_side, TitlebarButtonSide::Left);
        assert!(mac.buttons.has_fullscreen);
        assert!(!mac.buttons.has_maximize);
        assert_eq!(
            TitlebarMetrics::linux_gnome().button_side,
            TitlebarButtonSide::Right
        );
        // Mobile: no window controls at all.
        for (name, tm) in [
            ("ios", TitlebarMetrics::ios()),
            ("android", TitlebarMetrics::android()),
        ] {
            let b = tm.buttons;
            assert!(
                !b.has_close && !b.has_minimize && !b.has_maximize && !b.has_fullscreen,
                "{name} must not expose window controls"
            );
        }
        // Only iOS declares a notch safe area.
        let ios = TitlebarMetrics::ios();
        assert!(ios.safe_area.top.is_some());
        assert!(ios.safe_area.bottom.is_some());
        assert_eq!(
            TitlebarMetrics::windows().safe_area,
            SafeAreaInsets::default()
        );
    }
    // ── SystemStyle::new / detect / default_for_platform ─────────────────
    #[test]
    fn system_style_new_detect_and_default_for_platform_agree() {
        let a = SystemStyle::new();
        let b = SystemStyle::detect();
        let c = SystemStyle::default_for_platform();
        assert_eq!(a, b);
        assert_eq!(b, c);
    }
    #[test]
    fn system_style_constructors_arm_the_ffi_drop_guard() {
        // `run_destructor` is the double-drop guard; every freshly built style
        // (and every clone of one) must own its heap pointers.
        assert!(SystemStyle::default().run_destructor);
        assert!(SystemStyle::new().run_destructor);
        assert!(SystemStyle::detect().run_destructor);
        for (name, style) in all_default_styles() {
            assert!(
                style.run_destructor,
                "{name} does not own its heap pointers"
            );
            assert!(
                style.clone().run_destructor,
                "clone of {name} lost the guard"
            );
        }
    }
    #[test]
    fn system_style_default_is_empty_but_valid() {
        let d = SystemStyle::default();
        assert_eq!(d.platform, Platform::Unknown);
        assert_eq!(d.theme, Theme::Light);
        assert!(d.app_specific_stylesheet.is_none());
        assert!(d.scrollbar.is_none());
        assert!(d.language.as_str().is_empty());
        assert!(d.colors.text.is_none());
    }
    // ── defaults::* (+ the private scrollbar_info_to_computed helper) ─────
    #[test]
    fn default_styles_are_fully_populated() {
        for (name, style) in all_default_styles() {
            assert!(style.colors.text.is_some(), "{name}: no text color");
            assert!(
                style.colors.background.is_some(),
                "{name}: no background color"
            );
            assert!(style.colors.accent.is_some(), "{name}: no accent color");
            assert!(style.fonts.ui_font.is_some(), "{name}: no UI font");
            assert!(
                style.fonts.monospace_font.is_some(),
                "{name}: no monospace font"
            );
            assert!(
                !style.language.as_str().is_empty(),
                "{name}: empty language"
            );
            assert_ne!(
                style.platform,
                Platform::Unknown,
                "{name}: unknown platform"
            );
            let size = style
                .fonts
                .ui_font_size
                .into_option()
                .expect("ui font size");
            assert!(
                size.is_finite() && size > 0.0,
                "{name}: ui font size {size}"
            );
            let radius = style
                .metrics
                .corner_radius
                .as_ref()
                .map(|p| p.to_pixels_internal(0.0, 0.0, 0.0))
                .expect("corner radius");
            assert!(
                radius.is_finite() && radius >= 0.0,
                "{name}: corner radius {radius}"
            );
        }
    }
    #[test]
    fn default_styles_carry_a_fully_resolved_scrollbar() {
        // Exercises the private `scrollbar_info_to_computed` helper: every
        // built-in ScrollbarInfo uses solid colors, so nothing may map to None.
        for (name, style) in all_default_styles() {
            let sb = style
                .scrollbar
                .as_ref()
                .unwrap_or_else(|| panic!("{name}: no scrollbar"));
            assert!(sb.width.is_some(), "{name}: scrollbar width lost");
            assert!(sb.thumb_color.is_some(), "{name}: thumb color lost");
            assert!(sb.track_color.is_some(), "{name}: track color lost");
        }
    }
    #[test]
    fn light_and_dark_default_styles_differ() {
        assert_ne!(defaults::windows_11_light(), defaults::windows_11_dark());
        assert_ne!(
            defaults::macos_modern_light(),
            defaults::macos_modern_dark()
        );
        assert_ne!(
            defaults::gnome_adwaita_light(),
            defaults::gnome_adwaita_dark()
        );
        assert_ne!(
            defaults::android_material_light(),
            defaults::android_holo_dark()
        );
        assert_eq!(defaults::windows_11_dark().theme, Theme::Dark);
        assert_eq!(defaults::macos_modern_dark().theme, Theme::Dark);
        assert_eq!(defaults::gnome_adwaita_dark().theme, Theme::Dark);
        assert_eq!(defaults::android_holo_dark().theme, Theme::Dark);
        assert_eq!(
            defaults::kde_breeze_light().platform,
            Platform::Linux(DesktopEnvironment::Kde)
        );
        assert_eq!(defaults::ios_light().platform, Platform::Ios);
    }
    #[test]
    fn default_style_constructors_are_deterministic() {
        for _ in 0..3 {
            assert_eq!(defaults::windows_xp_luna(), defaults::windows_xp_luna());
            assert_eq!(defaults::macos_aqua(), defaults::macos_aqua());
            assert_eq!(defaults::gtk2_clearlooks(), defaults::gtk2_clearlooks());
            assert_eq!(defaults::windows_7_aero(), defaults::windows_7_aero());
        }
    }
    // ── SystemStyle::to_json_string ──────────────────────────────────────
    #[test]
    fn to_json_string_has_balanced_braces_for_every_default() {
        let mut styles = all_default_styles();
        styles.push(("default", SystemStyle::default()));
        for (name, style) in styles {
            let json = style.to_json_string();
            let s = json.as_str();
            assert!(s.starts_with('{'), "{name}: does not start with '{{'");
            assert!(s.ends_with('}'), "{name}: does not end with '}}'");
            let open = s.chars().filter(|c| *c == '{').count();
            let close = s.chars().filter(|c| *c == '}').count();
            assert_eq!(open, close, "{name}: unbalanced braces");
            for key in [
                "\"theme\"",
                "\"platform\"",
                "\"colors\"",
                "\"fonts\"",
                "\"titlebar\"",
                "\"input\"",
                "\"accessibility\"",
                "\"audio\"",
            ] {
                assert!(s.contains(key), "{name}: missing {key}");
            }
        }
    }
    #[test]
    fn to_json_string_reports_known_values() {
        let json = defaults::windows_11_light().to_json_string();
        let s = json.as_str();
        assert!(s.contains("\"theme\": \"Light\""), "{s}");
        assert!(s.contains("\"platform\": \"Windows\""), "{s}");
        assert!(s.contains("\"language\": \"en-US\""), "{s}");
        // text = rgb(0,0,0) -> "#000000ff" (alpha is included)
        assert!(s.contains("\"text\": \"#000000ff\""), "{s}");
        // Windows titlebar height is 32px, formatted with one decimal.
        assert!(s.contains("\"height\": 32.0"), "{s}");
        // Unset colors serialize as JSON null, not as an empty string.
        assert!(s.contains("\"grid\": null"), "{s}");
    }
    #[test]
    fn to_json_string_survives_nan_and_infinite_metrics() {
        let mut style = SystemStyle::default();
        style.accessibility.text_scale_factor = f32::NAN;
        style.animation.animation_duration_factor = f32::INFINITY;
        style.input.double_click_distance_px = f32::NEG_INFINITY;
        style.input.drag_threshold_px = f32::MAX;
        style.input.caret_width_px = f32::MIN_POSITIVE;
        style.input.double_click_time_ms = u32::MAX;
        style.input.caret_blink_rate_ms = u32::MAX;
        style.input.wheel_scroll_lines = u32::MAX;
        style.input.hover_time_ms = u32::MAX;
        style.text_rendering.font_smoothing_gamma = u32::MAX;
        style.linux.cursor_size = u32::MAX;
        // Must not panic; the extreme values are formatted, not truncated away.
        let json = style.to_json_string();
        let s = json.as_str();
        assert!(!s.is_empty());
        assert!(s.contains(&format!("\"cursor_size\": {}", u32::MAX)), "{s}");
        assert!(
            s.contains(&format!("\"double_click_time_ms\": {}", u32::MAX)),
            "{s}"
        );
    }
    #[test]
    fn to_json_string_survives_extreme_pixel_metrics() {
        let mut style = SystemStyle::default();
        style.metrics.titlebar.height = OptionPixelValue::Some(PixelValue::px(f32::NAN));
        style.metrics.titlebar.button_area_width =
            OptionPixelValue::Some(PixelValue::px(f32::INFINITY));
        style.metrics.titlebar.padding_horizontal =
            OptionPixelValue::Some(PixelValue::px(f32::NEG_INFINITY));
        style.metrics.titlebar.title_font_size = OptionF32::Some(f32::MAX);
        style.metrics.titlebar.title_font_weight = OptionU16::Some(u16::MAX);
        let json = style.to_json_string();
        assert!(!json.as_str().is_empty());
        // PixelValue stores fixed-point isize, so NaN saturates to 0 and the
        // infinities saturate to the isize bounds — the JSON stays finite.
        let nan_px = PixelValue::px(f32::NAN).to_pixels_internal(0.0, 0.0, 0.0);
        assert_eq!(nan_px, 0.0);
        assert!(PixelValue::px(f32::INFINITY)
            .to_pixels_internal(0.0, 0.0, 0.0)
            .is_finite());
        assert!(PixelValue::px(f32::NEG_INFINITY)
            .to_pixels_internal(0.0, 0.0, 0.0)
            .is_finite());
    }
    #[test]
    fn to_json_string_survives_hostile_strings() {
        // Quote / backslash / newline / unicode in an OS-reported string must
        // not panic the formatter.
        let mut style = SystemStyle::default();
        style.language = AzString::from("\"\\\n\t\u{1F600}");
        style.fonts.ui_font = OptionString::Some(AzString::from("a\"b\\c"));
        style.linux.gtk_theme = OptionString::Some(AzString::from("\u{202E}evil"));
        let json = style.to_json_string();
        let s = json.as_str();
        assert!(!s.is_empty());
        assert!(s.contains("\"language\":"), "{s}");
    }
    #[test]
    fn to_json_string_is_deterministic() {
        let style = defaults::gnome_adwaita_dark();
        assert_eq!(style.to_json_string(), style.to_json_string());
        assert_ne!(
            defaults::gnome_adwaita_dark().to_json_string(),
            defaults::gnome_adwaita_light().to_json_string()
        );
    }
    // ── SystemStyle::create_csd_stylesheet ───────────────────────────────
    #[test]
    fn csd_stylesheet_rules_all_carry_system_priority() {
        let mut styles = all_default_styles();
        styles.push(("default", SystemStyle::default()));
        for (name, style) in styles {
            let css = style.create_csd_stylesheet();
            let rules = css.rules.as_slice();
            assert!(!rules.is_empty(), "{name}: produced no rules");
            for rule in rules {
                assert_eq!(
                    rule.priority,
                    rule_priority::SYSTEM,
                    "{name}: rule escaped the SYSTEM layer"
                );
            }
            // System rules must lose against author CSS.
            const _: () = assert!(rule_priority::SYSTEM < rule_priority::AUTHOR);
        }
    }
    #[test]
    fn csd_stylesheet_uses_fallback_colors_when_the_system_reports_none() {
        // All colors unset -> the hard-coded fallbacks must still produce CSS.
        let css = SystemStyle::default().create_csd_stylesheet();
        assert!(!css.rules.as_slice().is_empty());
        assert_ne!(css, Css::default());
    }
    #[test]
    fn csd_stylesheet_is_platform_specific() {
        let mac = defaults::macos_modern_light().create_csd_stylesheet();
        let win = defaults::windows_11_light().create_csd_stylesheet();
        let lin = defaults::gnome_adwaita_light().create_csd_stylesheet();
        assert_ne!(mac, win);
        assert_ne!(win, lin);
        assert_ne!(mac, lin);
        // macOS appends the traffic-light rules on top of the shared ones.
        assert!(mac.rules.as_slice().len() > win.rules.as_slice().len());
    }
    #[test]
    fn csd_stylesheet_survives_extreme_corner_radius() {
        for radius in [
            PixelValue::px(f32::NAN),
            PixelValue::px(f32::INFINITY),
            PixelValue::px(f32::NEG_INFINITY),
            PixelValue::px(f32::MAX),
            PixelValue::px(-1.0),
            PixelValue::percent(f32::MAX),
            PixelValue::em(f32::MIN),
        ] {
            let mut style = defaults::windows_11_light();
            style.metrics.corner_radius = OptionPixelValue::Some(radius);
            let css = style.create_csd_stylesheet();
            assert!(
                !css.rules.as_slice().is_empty(),
                "radius {radius:?} produced no rules"
            );
            for rule in css.rules.as_slice() {
                assert_eq!(rule.priority, rule_priority::SYSTEM);
            }
        }
    }
    #[test]
    fn csd_stylesheet_is_deterministic() {
        let style = defaults::kde_breeze_light();
        assert_eq!(style.create_csd_stylesheet(), style.create_csd_stylesheet());
    }
    // ── AZ_RICING / environment probes ───────────────────────────────────
    //
    // These functions read process-global environment variables. The tests
    // below deliberately do NOT mutate the environment (`set_var` races with
    // every other test thread in the same binary), so they assert the
    // invariants that must hold for *any* ambient environment.
    #[test]
    fn ricing_mode_is_deterministic_and_total() {
        let mode = ricing_mode();
        assert_eq!(mode, ricing_mode(), "ricing_mode() is not deterministic");
        assert!(
            matches!(
                mode,
                RicingMode::Off | RicingMode::Default | RicingMode::Force
            ),
            "{mode:?}"
        );
        assert_eq!(RicingMode::default(), RicingMode::Default);
    }
    #[test]
    fn ricing_enabled_is_the_inverse_of_off() {
        assert_eq!(ricing_enabled(), ricing_mode() != RicingMode::Off);
        assert_eq!(ricing_enabled(), ricing_enabled());
    }
    #[test]
    fn detect_linux_desktop_env_is_deterministic() {
        let a = detect_linux_desktop_env();
        assert_eq!(a, detect_linux_desktop_env());
        // Unless the ambient env explicitly sets an *empty* desktop string
        // (which the function forwards verbatim), the `Other` label is either
        // a const name or the non-empty env value.
        let blank_env = |k: &str| std::env::var(k).map(|v| v.is_empty()).unwrap_or(false);
        if !blank_env("XDG_CURRENT_DESKTOP") && !blank_env("DESKTOP_SESSION") {
            if let DesktopEnvironment::Other(ref name) = a {
                assert!(!name.as_str().is_empty(), "empty desktop-environment label");
            }
        }
    }
    #[test]
    fn detect_system_language_is_a_normalized_tag() {
        let lang = detect_system_language();
        let s = lang.as_str();
        assert!(!s.is_empty(), "language tag must never be empty");
        // The encoding suffix (".UTF-8"), the LANGUAGE list separator (':')
        // and the POSIX underscore must all be normalized away.
        assert!(!s.contains('.'), "{s:?} still carries an encoding suffix");
        assert!(!s.contains(':'), "{s:?} still carries a locale list");
        assert!(!s.contains('_'), "{s:?} is not BCP 47 (underscore)");
        assert_eq!(lang, detect_system_language(), "not deterministic");
    }
}
/// Which hand operates the device (see [`SystemStyle::handedness`]).
///
/// INDEPENDENT of text direction: an Arabic left-hander reads right-to-left
/// but still reaches with the left hand, and a left-handed English user
/// reads left-to-right. Deriving one from the other is a bug.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(C)]
pub enum Handedness {
    /// Primary touch controls on the right (the default).
    #[default]
    RightHanded,
    /// Primary touch controls on the left.
    LeftHanded,
}
// NOTE: no explicit `is_left_handed()` here - the codegen already emits an
// `isLeftHanded()` predicate for every enum variant, and a hand-written one
// collides with it (PHP refuses the duplicate, other bindings get ambiguous
// dispatch). Match on the variant instead.