rust_widgets 2.9.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Global stylesheet manager for CSS-based widget theming (BLUE13 R1.6).
//!
//! StyleSheetManager holds a global parsed stylesheet and applies matching
//! CSS rules to widget styles. This enables app-wide theming similar to
//! LVGL's `lv_theme_t` but using Rust's type-safe CSS parser.

use crate::style::css::{CssDeclaration, CssParser, CssSelector};
use crate::style::PseudoState;
use crate::style::WidgetStyle;

use crate::compat::Mutex;
use crate::compat::MutexGuard;
use crate::compat::OnceLock;
use crate::compat::{lock, MiniToString, String, Vec};

/// One rule of a registered sheet, with its selector parsed once at registration time.
#[derive(Debug)]
struct ParsedRule {
    /// The selector, matched against `(kind, class, id, state)` on every apply.
    selector: CssSelector,
    /// Cascade weight, captured at registration so `apply_to` does not recompute it per call.
    specificity: u32,
    /// The declarations the selector applies.
    declarations: Vec<CssDeclaration>,
}

/// A registered stylesheet with its raw CSS text, priority, and parsed rules.
///
/// # Why the rules are parsed here
///
/// `apply_to` used to call `CssParser::parse_and_apply`, which re-tokenised the entire sheet and
/// re-parsed every selector for **every control that asked for a style**. A theme registered once
/// was therefore re-parsed thousands of times a frame. Parsing at `register` makes the apply path
/// a selector match plus the declarations it already matched.
#[derive(Debug)]
struct RegisteredSheet {
    /// Name for debugging.
    name: String,
    /// Priority (higher overrides lower).
    priority: u8,
    /// The sheet's rules, in source order.
    rules: Vec<ParsedRule>,
    /// The parse error, when the sheet was accepted but could not be parsed.
    parse_error: Option<String>,
}

/// Global stylesheet manager for CSS-based theming.
///
/// Manages a set of named CSS stylesheets with associated priorities.
/// When applying styles, sheets are processed in ascending priority order
/// so that higher-priority sheets can override lower-priority ones.
#[derive(Debug)]
pub struct StyleSheetManager {
    sheets: Vec<RegisteredSheet>,
}

impl StyleSheetManager {
    /// Create a new empty manager.
    pub fn new() -> Self {
        Self { sheets: Vec::new() }
    }

    /// Register a CSS stylesheet with a name and optional priority.
    /// Higher priority sheets override lower ones when rules conflict.
    pub fn register(&mut self, name: &str, css: &str, priority: u8) {
        // Remove existing sheet with the same name, then add the new one.
        self.sheets.retain(|s| s.name != name);
        let (rules, parse_error) = match CssParser::parse_rules(css) {
            Ok(rules) => (
                rules
                    .into_iter()
                    .filter_map(|rule| {
                        CssParser::parse_selector(&rule.selector_text).map(|selector| ParsedRule {
                            specificity: selector.specificity(),
                            selector,
                            declarations: rule.declarations,
                        })
                    })
                    .collect(),
                None,
            ),
            Err(error) => (Vec::new(), Some(error)),
        };
        self.sheets.push(RegisteredSheet { name: name.to_string(), priority, rules, parse_error });
        // Keep the list in apply order, so `apply_to` neither sorts nor allocates per call.
        self.sheets.sort_by_key(|sheet| sheet.priority);
    }

    /// Remove a registered stylesheet by name.
    /// Returns `true` if a sheet was removed.
    pub fn unregister(&mut self, name: &str) -> bool {
        let len_before = self.sheets.len();
        self.sheets.retain(|s| s.name != name);
        self.sheets.len() < len_before
    }

    /// Apply all matching stylesheet rules to a widget style.
    ///
    /// Sheets are applied in priority order (lower first) so a higher-priority sheet overrides a
    /// lower one. Within the matched set, rules are applied in cascade order — ascending
    /// specificity, then source order — so `.primary` beats a bare `Button` rule even when the
    /// class rule is written first.
    ///
    /// A sheet that failed to parse is **skipped** and reported after the valid sheets have been
    /// applied. Returning early used to throw away every registered sheet at once, and the JSON
    /// loader then discarded the widget's whole style, so one malformed app-wide sheet disabled
    /// the entire CSS layer.
    pub fn apply_to(
        &self,
        kind: &str,
        class: Option<&str>,
        id: Option<&str>,
        state: Option<PseudoState>,
        style: &mut WidgetStyle,
    ) -> Result<(), String> {
        let mut parse_error: Option<String> = None;
        // (specificity, source order, declarations). Rule counts are small, and this path runs at
        // widget construction / stylesheet change, not per frame.
        let mut matched: Vec<(u32, usize, &[CssDeclaration])> = Vec::new();
        let mut source_order = 0usize;

        for sheet in &self.sheets {
            if let Some(error) = &sheet.parse_error {
                if parse_error.is_none() {
                    parse_error = Some(error.clone());
                }
                continue;
            }
            for rule in &sheet.rules {
                if rule.selector.matches(kind, class, id, state) {
                    matched.push((rule.specificity, source_order, &rule.declarations));
                }
                source_order += 1;
            }
        }

        matched.sort_by_key(|(specificity, order, _)| (*specificity, *order));
        for (_, _, declarations) in matched {
            CssParser::apply_declarations(declarations, style)?;
        }

        if let Some(error) = parse_error {
            return Err(error);
        }
        Ok(())
    }

    /// Clear all registered stylesheets.
    pub fn clear(&mut self) {
        self.sheets.clear();
    }

    /// Returns the number of registered sheets.
    pub fn len(&self) -> usize {
        self.sheets.len()
    }

    /// Returns true if no sheets are registered.
    pub fn is_empty(&self) -> bool {
        self.sheets.is_empty()
    }
}

crate::impl_default_via_new!(StyleSheetManager);

/// Get the global stylesheet manager instance (thread-safe).
///
/// This lazily initializes a singleton `StyleSheetManager` behind a `Mutex`,
/// allowing safe access from multiple threads.
pub fn global_stylesheet_manager() -> MutexGuard<'static, StyleSheetManager> {
    static MANAGER: OnceLock<Mutex<StyleSheetManager>> = OnceLock::new();
    lock(MANAGER.get_or_init(|| Mutex::new(StyleSheetManager::new())))
}

/// Serialises tests that register into, clear, or otherwise depend on the
/// process-wide stylesheet manager.
///
/// The manager is shared state, so two tests that each register a sheet (or one
/// that clears the registry while another applies a rule) race and observe each
/// other's writes. Same precedent as the theme guard: shared state in a
/// process-wide singleton needs explicit serialisation in tests, not a hope that
/// the scheduling happens to work out. Compiled only for tests.
#[cfg(test)]
pub(crate) fn stylesheet_test_guard() -> crate::compat::MutexGuard<'static, ()> {
    static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
    lock(GUARD.get_or_init(|| Mutex::new(())))
}

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

    /// Helper: create a basic WidgetStyle with known values for testing.
    fn make_style() -> WidgetStyle {
        WidgetStyle::default()
    }

    #[test]
    fn stylesheet_register_and_apply() {
        let mut manager = StyleSheetManager::new();
        let css = r#"
            Button {
                background-color: #ff0000;
                text-color: #ffffff;
            }
        "#;
        manager.register("test-sheet", css, 0);

        let mut style = make_style();
        manager.apply_to("Button", None, None, None, &mut style).expect("apply_to should succeed");

        assert_eq!(
            style.background_color,
            Some(Color::rgb(255, 0, 0)),
            "background_color should be red"
        );
        assert_eq!(style.text_color, Some(Color::rgb(255, 255, 255)), "text_color should be white");
    }

    #[test]
    fn stylesheet_priority() {
        let mut manager = StyleSheetManager::new();

        // Low priority: red background
        let css_low = r#"
            Button {
                background-color: #ff0000;
                text-color: #000000;
            }
        "#;
        manager.register("low", css_low, 0);

        // High priority: blue background (should override red)
        let css_high = r#"
            Button {
                background-color: #0000ff;
            }
        "#;
        manager.register("high", css_high, 100);

        let mut style = make_style();
        manager.apply_to("Button", None, None, None, &mut style).expect("apply_to should succeed");

        // background-color comes from high-priority sheet (blue overrides red)
        assert_eq!(
            style.background_color,
            Some(Color::rgb(0, 0, 255)),
            "high-priority blue should override low-priority red"
        );
        // text_color comes from low-priority sheet (high didn't set it)
        assert_eq!(
            style.text_color,
            Some(Color::rgb(0, 0, 0)),
            "text_color from low-priority sheet should be preserved"
        );
    }

    #[test]
    fn stylesheet_unregister() {
        let mut manager = StyleSheetManager::new();
        manager.register("theme", "Button { background-color: #00ff00; }", 0);
        assert!(!manager.is_empty(), "manager should not be empty after register");

        let removed = manager.unregister("theme");
        assert!(removed, "unregister should return true when sheet exists");
        assert!(manager.is_empty(), "manager should be empty after unregister");

        // Removing a non-existent sheet returns false.
        let removed_again = manager.unregister("nonexistent");
        assert!(!removed_again, "unregister should return false for unknown name");
    }

    #[test]
    fn stylesheet_clear() {
        let mut manager = StyleSheetManager::new();
        manager.register("a", "Button { background-color: #ff0000; }", 0);
        manager.register("b", "Label { text-color: #00ff00; }", 1);
        assert_eq!(manager.len(), 2, "should have 2 sheets");

        manager.clear();
        assert_eq!(manager.len(), 0, "should be empty after clear");
        assert!(manager.is_empty(), "is_empty should be true");
    }

    #[test]
    fn global_manager_thread_safe() {
        // Serialised: this test asserts the registry is empty afterwards, so it
        // must not race a sheet another test registers concurrently.
        let _guard = stylesheet_test_guard();
        // Get the global manager and verify it works.
        {
            let mut mgr = global_stylesheet_manager();
            mgr.clear();
            mgr.register("global-test", "Button { border-color: #ff00ff; }", 0);
        }

        // Verify the sheet is accessible (unregister to clean up).
        {
            let mut mgr = global_stylesheet_manager();
            let removed = mgr.unregister("global-test");
            assert!(removed, "should find the sheet registered in previous scope");
            assert!(mgr.is_empty(), "manager should be clean after unregister");
        }
    }

    #[test]
    fn stylesheet_register_replaces_existing() {
        let mut manager = StyleSheetManager::new();
        manager.register("sheet", "Button { background-color: #ff0000; }", 0);
        manager.register("sheet", "Button { background-color: #00ff00; }", 0);

        assert_eq!(manager.len(), 1, "re-registering same name should replace, not add");

        let mut style = make_style();
        manager.apply_to("Button", None, None, None, &mut style).expect("apply_to should succeed");

        assert_eq!(
            style.background_color,
            Some(Color::rgb(0, 255, 0)),
            "should use the latest registered CSS for the same name"
        );
    }

    #[test]
    fn stylesheet_class_selector_match() {
        let mut manager = StyleSheetManager::new();
        let css = r#"
            .primary {
                background-color: #ff8800;
            }
        "#;
        manager.register("class-test", css, 0);

        let mut style = make_style();
        manager
            .apply_to("Button", Some("primary"), None, None, &mut style)
            .expect("apply_to should succeed");

        assert_eq!(
            style.background_color,
            Some(Color::rgb(0xff, 0x88, 0x00)),
            "class selector .primary should match"
        );
    }

    #[test]
    fn stylesheet_no_match_does_not_apply() {
        let mut manager = StyleSheetManager::new();
        let css = r#"
            Label {
                background-color: #ff0000;
            }
        "#;
        manager.register("no-match", css, 0);

        let mut style = make_style();
        manager.apply_to("Button", None, None, None, &mut style).expect("apply_to should succeed");

        assert_eq!(style.background_color, None, "Label CSS should not apply to Button");
    }

    /// A malformed sheet is reported but must not cancel the valid sheets registered next to it.
    #[test]
    fn a_broken_sheet_does_not_discard_the_valid_sheets() {
        let mut manager = StyleSheetManager::new();
        manager.register("bad", "Button { background-color: #ff0000; ", 0);
        manager.register("good", "Button { text-color: #123456; }", 1);

        let mut style = make_style();
        let result = manager.apply_to("Button", None, None, None, &mut style);

        assert!(result.is_err(), "the malformed sheet must still be reported");
        assert_eq!(
            style.text_color,
            Some(Color::rgb(0x12, 0x34, 0x56)),
            "the valid sheet must still apply"
        );
    }

    /// The CSS cascade applies the more specific rule last, even when it is written first.
    #[test]
    fn a_class_rule_overrides_a_kind_rule_written_after_it() {
        let mut manager = StyleSheetManager::new();
        manager.register(
            "cascade",
            ".primary { background-color: #ff8800; } Button { background-color: #0000ff; }",
            0,
        );

        let mut style = make_style();
        manager
            .apply_to("Button", Some("primary"), None, None, &mut style)
            .expect("apply_to should succeed");

        assert_eq!(
            style.background_color,
            Some(Color::rgb(0xff, 0x88, 0x00)),
            "`.primary` has higher specificity than `Button` and must win"
        );
    }

    #[test]
    fn stylesheet_invalid_css_returns_error() {
        let mut manager = StyleSheetManager::new();
        // Missing closing brace — invalid CSS.
        manager.register("bad", "Button { background-color: #ff0000; ", 0);

        let mut style = make_style();
        let result = manager.apply_to("Button", None, None, None, &mut style);
        assert!(result.is_err(), "invalid CSS should produce an error");
    }
}