Skip to main content

repose_core/
locals.rs

1//! # Theming and locals
2//!
3//! Repose uses thread‑local “composition locals” for global UI parameters:
4//!
5//! - `Theme` - colors for surfaces, text, controls, etc.
6//! - `Density` - dp->px device scale factor (platform sets this).
7//! - `UiScale` - app-controlled UI scale multiplier (defaults to 1.0).
8//! - `TextScale` - user text scaling (defaults to 1.0).
9//! - `TextDirection` - LTR or RTL (defaults to LTR).
10//!
11//! Locals can be overridden for a subtree with `with_*`. If no local is set,
12//! getters fall back to global defaults (which an app can set each frame).
13
14use std::ops::Deref;
15
16use std::any::{Any, TypeId};
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::hash::{Hash, Hasher};
20use std::sync::OnceLock;
21
22use parking_lot::RwLock;
23
24use std::rc::Rc;
25
26use crate::Color;
27use crate::animation::{AnimationSpec, Easing, SpringSpec};
28use crate::indication::IndicationNodeFactory;
29use web_time::Duration;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
32pub enum TextDirection {
33    #[default]
34    Ltr,
35    Rtl,
36}
37
38thread_local! {
39    static LOCALS_STACK: RefCell<Vec<HashMap<TypeId, Box<dyn Any>>>> = RefCell::new(Vec::new());
40}
41
42#[derive(Clone, Copy)]
43pub(crate) enum LocalId {
44    Theme,
45    Density,
46    UiScale,
47    TextScale,
48    TextDirection,
49    WindowInsets,
50    WindowSizeClass,
51    ContainerWidth,
52    ContainerHeight,
53    ContentColor,
54    TextSize,
55    Indication,
56    InputMode,
57}
58
59impl LocalId {
60    fn index(self) -> usize {
61        self as usize
62    }
63}
64
65#[derive(Clone, Copy, Debug, Default)]
66struct Defaults {
67    theme: Theme,
68    text_direction: TextDirection,
69    ui_scale: UiScale,
70    text_scale: TextScale,
71    density: Density,
72    window_insets: WindowInsets,
73    window_size_class: WindowSizeClass,
74    /// Logical window container size in dp (defaults match a phone portrait).
75    container_width: f32,
76    container_height: f32,
77}
78
79static DEFAULTS: OnceLock<RwLock<Defaults>> = OnceLock::new();
80
81fn defaults() -> &'static RwLock<Defaults> {
82    DEFAULTS.get_or_init(|| {
83        RwLock::new(Defaults {
84            container_width: 360.0,
85            container_height: 800.0,
86            ..Default::default()
87        })
88    })
89}
90
91/// Set the global default theme used when no local Theme is active.
92pub fn set_theme_default(t: Theme) {
93    let changed = {
94        let mut defaults = defaults().write();
95        let changed = fingerprint_theme(&defaults.theme) != fingerprint_theme(&t);
96        defaults.theme = t;
97        changed
98    };
99    if changed {
100        crate::request_frame();
101    }
102}
103
104/// Set the global default text direction used when no local TextDirection is active.
105pub fn set_text_direction_default(d: TextDirection) {
106    let changed = {
107        let mut defaults = defaults().write();
108        let changed = defaults.text_direction != d;
109        defaults.text_direction = d;
110        changed
111    };
112    if changed {
113        crate::request_frame();
114    }
115}
116
117/// Set the global default UI scale used when no local UiScale is active.
118pub fn set_ui_scale_default(s: UiScale) {
119    let value = UiScale(s.0.max(0.0));
120    let changed = {
121        let mut defaults = defaults().write();
122        let changed = defaults.ui_scale.0.to_bits() != value.0.to_bits();
123        defaults.ui_scale = value;
124        changed
125    };
126    if changed {
127        crate::request_frame();
128    }
129}
130
131/// Set the global default text scale used when no local TextScale is active.
132pub fn set_text_scale_default(s: TextScale) {
133    let value = TextScale(s.0.max(0.0));
134    let changed = {
135        let mut defaults = defaults().write();
136        let changed = defaults.text_scale.0.to_bits() != value.0.to_bits();
137        defaults.text_scale = value;
138        changed
139    };
140    if changed {
141        crate::request_frame();
142    }
143}
144
145/// Set the global default device density (dp->px) used when no local Density is active.
146/// Platform runners should call this whenever the window scale factor changes.
147pub fn set_density_default(d: Density) {
148    let value = Density {
149        scale: d.scale.max(0.0),
150    };
151    let changed = {
152        let mut defaults = defaults().write();
153        let changed = defaults.density.scale.to_bits() != value.scale.to_bits();
154        defaults.density = value;
155        changed
156    };
157    if changed {
158        crate::request_frame();
159    }
160}
161
162pub use crate::units::{Dp, DpOffset, DpRect, DpSize, Px, Sp, UnitExt};
163
164/// Effective dp→px scale: device density × app UI scale.
165#[inline]
166pub fn effective_density_scale() -> f32 {
167    (density().scale * ui_scale().0).max(0.0001)
168}
169
170/// Convert [`Dp`] into [`Px`] using current Density * UiScale.
171#[inline]
172pub fn dp_to_px(dp: Dp) -> Px {
173    dp.to_px()
174}
175
176/// Convert [`Px`] into [`Dp`] using current Density * UiScale.
177#[inline]
178pub fn px_to_dp(px: Px) -> Dp {
179    px.to_dp()
180}
181
182fn with_locals_frame<R>(f: impl FnOnce() -> R) -> R {
183    struct Guard;
184    impl Drop for Guard {
185        fn drop(&mut self) {
186            let frame = LOCALS_STACK
187                .try_with(|stack| {
188                    stack
189                        .try_borrow_mut()
190                        .ok()
191                        .and_then(|mut stack| stack.pop())
192                })
193                .ok()
194                .flatten();
195            drop(frame);
196        }
197    }
198    LOCALS_STACK.with(|stack| stack.borrow_mut().push(HashMap::new()));
199    let _guard = Guard;
200    f()
201}
202
203fn set_local_boxed(t: TypeId, value: Box<dyn Any>) {
204    let old = LOCALS_STACK
205        .try_with(|stack| {
206            let mut stack = stack.try_borrow_mut().ok()?;
207            let old = stack.last_mut()?.insert(t, value);
208            Some(old)
209        })
210        .ok()
211        .flatten();
212    drop(old);
213}
214
215fn get_local<T: 'static + Copy>() -> Option<T> {
216    LOCALS_STACK.with(|stack| {
217        for frame in stack.borrow().iter().rev() {
218            if let Some(value) = frame.get(&TypeId::of::<T>())
219                && let Some(value) = value.downcast_ref::<T>()
220            {
221                return Some(*value);
222            }
223        }
224        None
225    })
226}
227
228fn record_local<T: 'static>(id: LocalId, value: &T, fingerprint: impl FnOnce(&T) -> u64) {
229    crate::scope_cache::record_scope_local_read(id.index(), fingerprint(value));
230}
231
232fn fingerprint_color(value: &Color) -> u64 {
233    let mut hasher = std::collections::hash_map::DefaultHasher::new();
234    value.0.hash(&mut hasher);
235    value.1.hash(&mut hasher);
236    value.2.hash(&mut hasher);
237    value.3.hash(&mut hasher);
238    hasher.finish()
239}
240
241fn fingerprint_theme(value: &Theme) -> u64 {
242    let mut hasher = std::collections::hash_map::DefaultHasher::new();
243    format!("{value:?}").hash(&mut hasher);
244    hasher.finish()
245}
246
247fn fingerprint_text_size(value: Option<Sp>) -> u64 {
248    value.map(|size| size.0.to_bits() as u64).unwrap_or(0)
249}
250
251fn fingerprint_input_mode(value: crate::input::InputMode) -> u64 {
252    let mut hasher = std::collections::hash_map::DefaultHasher::new();
253    std::mem::discriminant(&value).hash(&mut hasher);
254    hasher.finish()
255}
256
257fn fingerprint_f32(value: f32) -> u64 {
258    value.to_bits() as u64
259}
260
261fn fingerprint_window_insets(value: &WindowInsets) -> u64 {
262    let mut hasher = std::collections::hash_map::DefaultHasher::new();
263    value.top.to_bits().hash(&mut hasher);
264    value.bottom.to_bits().hash(&mut hasher);
265    value.left.to_bits().hash(&mut hasher);
266    value.right.to_bits().hash(&mut hasher);
267    value.ime_bottom.to_bits().hash(&mut hasher);
268    hasher.finish()
269}
270
271fn fingerprint_window_size_class(value: &WindowSizeClass) -> u64 {
272    let mut hasher = std::collections::hash_map::DefaultHasher::new();
273    value.width.hash(&mut hasher);
274    value.height.hash(&mut hasher);
275    hasher.finish()
276}
277
278fn fingerprint_text_direction(value: &TextDirection) -> u64 {
279    let mut hasher = std::collections::hash_map::DefaultHasher::new();
280    std::mem::discriminant(value).hash(&mut hasher);
281    hasher.finish()
282}
283
284fn fingerprint_indication(value: &Option<Rc<dyn IndicationNodeFactory>>) -> u64 {
285    value
286        .as_ref()
287        .map(|value| Rc::as_ptr(value) as *const () as usize as u64)
288        .unwrap_or(0)
289}
290
291#[derive(Clone, Copy, Debug)]
292#[must_use]
293pub struct ColorScheme {
294    pub primary: Color,
295    pub on_primary: Color,
296    pub primary_container: Color,
297    pub on_primary_container: Color,
298
299    pub secondary: Color,
300    pub on_secondary: Color,
301    pub secondary_container: Color,
302    pub on_secondary_container: Color,
303
304    pub tertiary: Color,
305    pub on_tertiary: Color,
306    pub tertiary_container: Color,
307    pub on_tertiary_container: Color,
308
309    pub error: Color,
310    pub on_error: Color,
311    pub error_container: Color,
312    pub on_error_container: Color,
313
314    pub background: Color,
315    pub on_background: Color,
316    pub surface: Color,
317    pub on_surface: Color,
318    pub surface_variant: Color,
319    pub on_surface_variant: Color,
320    pub surface_container_lowest: Color,
321    pub surface_container_low: Color,
322    pub surface_container: Color,
323    pub surface_container_high: Color,
324    pub surface_container_highest: Color,
325    pub surface_bright: Color,
326    pub surface_dim: Color,
327    pub surface_tint: Color,
328
329    pub inverse_surface: Color,
330    pub inverse_on_surface: Color,
331    pub inverse_primary: Color,
332
333    pub outline: Color,
334    pub outline_variant: Color,
335
336    pub scrim: Color,
337    pub shadow: Color,
338    pub focus: Color,
339}
340
341impl ColorScheme {
342    pub fn dark() -> Self {
343        Self {
344            primary: Color::from_hex("#69FDBE"),
345            on_primary: Color::from_hex("#003020"),
346            primary_container: Color::from_hex("#004D40"),
347            on_primary_container: Color::from_hex("#6FF7F6"),
348
349            secondary: Color::from_hex("#B3C9A7"),
350            on_secondary: Color::from_hex("#1C3519"),
351            secondary_container: Color::from_hex("#334D2E"),
352            on_secondary_container: Color::from_hex("#CCE8B3"),
353
354            tertiary: Color::from_hex("#FFC9C1"),
355            on_tertiary: Color::from_hex("#3F1619"),
356            tertiary_container: Color::from_hex("#5D1F22"),
357            on_tertiary_container: Color::from_hex("#FFDBD8"),
358
359            error: Color::from_hex("#F2B8B5"),
360            on_error: Color::from_hex("#601410"),
361            error_container: Color::from_hex("#8C1D18"),
362            on_error_container: Color::from_hex("#F9DEDC"),
363
364            background: Color::from_hex("#1A1C1E"),
365            on_background: Color::from_hex("#E6E1E5"),
366            surface: Color::from_hex("#1A1C1E"),
367            on_surface: Color::from_hex("#E6E1E5"),
368            surface_variant: Color::from_hex("#44474E"),
369            on_surface_variant: Color::from_hex("#C4C6CE"),
370            surface_container_lowest: Color::from_hex("#0A0A0C"),
371            surface_container_low: Color::from_hex("#141115"),
372            surface_container: Color::from_hex("#19131A"),
373            surface_container_high: Color::from_hex("#1F1B22"),
374            surface_container_highest: Color::from_hex("#2A2930"),
375            surface_bright: Color::from_hex("#26292F"),
376            surface_dim: Color::from_hex("#1A1C1E"),
377            surface_tint: Color::from_hex("#69FDBE"),
378
379            inverse_surface: Color::from_hex("#E6E1E5"),
380            inverse_on_surface: Color::from_hex("#2A2930"),
381            inverse_primary: Color::from_hex("#005048"),
382
383            outline: Color::from_hex("#74777F"),
384            outline_variant: Color::from_hex("#44474E"),
385
386            scrim: Color::from_hex("#000000"),
387            shadow: Color::from_hex("#000000"),
388            focus: Color::from_hex("#006A6A"),
389        }
390    }
391
392    pub fn light() -> Self {
393        Self {
394            primary: Color::from_hex("#006A6A"),
395            on_primary: Color::WHITE,
396            primary_container: Color::from_hex("#9EF0EC"),
397            on_primary_container: Color::from_hex("#002020"),
398
399            secondary: Color::from_hex("#586146"),
400            on_secondary: Color::WHITE,
401            secondary_container: Color::from_hex("#D8E3B8"),
402            on_secondary_container: Color::from_hex("#161C0A"),
403
404            tertiary: Color::from_hex("#744639"),
405            on_tertiary: Color::WHITE,
406            tertiary_container: Color::from_hex("#FFD9CD"),
407            on_tertiary_container: Color::from_hex("#2C0E07"),
408
409            error: Color::from_hex("#BA1A1A"),
410            on_error: Color::WHITE,
411            error_container: Color::from_hex("#FFDAD6"),
412            on_error_container: Color::from_hex("#410002"),
413
414            background: Color::from_hex("#FEF7FF"),
415            on_background: Color::from_hex("#1A1C1E"),
416            surface: Color::from_hex("#FEF7FF"),
417            on_surface: Color::from_hex("#1A1C1E"),
418            surface_variant: Color::from_hex("#E1E3DE"),
419            on_surface_variant: Color::from_hex("#44474E"),
420            surface_container_lowest: Color::WHITE,
421            surface_container_low: Color::from_hex("#F4F5F0"),
422            surface_container: Color::from_hex("#EEF0E9"),
423            surface_container_high: Color::from_hex("#E9EAE4"),
424            surface_container_highest: Color::from_hex("#E3E5DF"),
425            surface_bright: Color::from_hex("#FEF7FF"),
426            surface_dim: Color::from_hex("#DEDAD0"),
427            surface_tint: Color::from_hex("#006A6A"),
428
429            inverse_surface: Color::from_hex("#2F3033"),
430            inverse_on_surface: Color::from_hex("#F1F0F4"),
431            inverse_primary: Color::from_hex("#69FDBE"),
432
433            outline: Color::from_hex("#74777F"),
434            outline_variant: Color::from_hex("#C4C6CE"),
435
436            scrim: Color::from_hex("#000000"),
437            shadow: Color::from_hex("#000000"),
438            focus: Color::from_hex("#1D4ED8"),
439        }
440    }
441
442    /// Compose `ColorScheme.contentColorFor(backgroundColor)`.
443    /// Maps a scheme container/background role to its paired on-* content color.
444    pub fn content_color_for(self, background: Color) -> Option<Color> {
445        if background == self.primary {
446            Some(self.on_primary)
447        } else if background == self.primary_container {
448            Some(self.on_primary_container)
449        } else if background == self.secondary {
450            Some(self.on_secondary)
451        } else if background == self.secondary_container {
452            Some(self.on_secondary_container)
453        } else if background == self.tertiary {
454            Some(self.on_tertiary)
455        } else if background == self.tertiary_container {
456            Some(self.on_tertiary_container)
457        } else if background == self.background {
458            Some(self.on_background)
459        } else if background == self.surface
460            || background == self.surface_bright
461            || background == self.surface_dim
462            || background == self.surface_container
463            || background == self.surface_container_low
464            || background == self.surface_container_high
465            || background == self.surface_container_highest
466        {
467            Some(self.on_surface)
468        } else if background == self.inverse_surface {
469            Some(self.inverse_on_surface)
470        } else if background == self.error {
471            Some(self.on_error)
472        } else if background == self.error_container {
473            Some(self.on_error_container)
474        } else {
475            None
476        }
477    }
478}
479
480impl Default for ColorScheme {
481    fn default() -> Self {
482        Self::dark()
483    }
484}
485
486/// Material type scale. All sizes are [`Sp`] (Compose `Typography` uses `TextUnit`).
487#[derive(Clone, Copy, Debug)]
488#[must_use]
489pub struct Typography {
490    pub display_large: Sp,
491    pub display_medium: Sp,
492    pub display_small: Sp,
493    pub headline_large: Sp,
494    pub headline_medium: Sp,
495    pub headline_small: Sp,
496    pub title_large: Sp,
497    pub title_medium: Sp,
498    pub title_small: Sp,
499    pub body_large: Sp,
500    pub body_medium: Sp,
501    pub body_small: Sp,
502    pub label_large: Sp,
503    pub label_medium: Sp,
504    pub label_small: Sp,
505}
506
507impl Default for Typography {
508    fn default() -> Self {
509        Self {
510            display_large: Sp(57.0),
511            display_medium: Sp(45.0),
512            display_small: Sp(36.0),
513            headline_large: Sp(32.0),
514            headline_medium: Sp(28.0),
515            headline_small: Sp(24.0),
516            title_large: Sp(22.0),
517            title_medium: Sp(16.0),
518            title_small: Sp(14.0),
519            body_large: Sp(16.0),
520            body_medium: Sp(14.0),
521            body_small: Sp(12.0),
522            label_large: Sp(14.0),
523            label_medium: Sp(12.0),
524            label_small: Sp(11.0),
525        }
526    }
527}
528
529/// Corner radii in [`Dp`].
530#[derive(Clone, Copy, Debug)]
531#[must_use]
532pub struct Shapes {
533    pub extra_small: Dp,
534    pub small: Dp,
535    pub medium: Dp,
536    pub large: Dp,
537    pub extra_large: Dp,
538}
539
540impl Default for Shapes {
541    fn default() -> Self {
542        Self {
543            extra_small: Dp(4.0),
544            small: Dp(8.0),
545            medium: Dp(12.0),
546            large: Dp(16.0),
547            extra_large: Dp(28.0),
548        }
549    }
550}
551
552/// Layout gaps in [`Dp`].
553#[derive(Clone, Copy, Debug)]
554#[must_use]
555pub struct Spacing {
556    pub xs: Dp,
557    pub sm: Dp,
558    pub md: Dp,
559    pub lg: Dp,
560    pub xl: Dp,
561    pub xxl: Dp,
562}
563
564impl Default for Spacing {
565    fn default() -> Self {
566        Self {
567            xs: Dp(4.0),
568            sm: Dp(8.0),
569            md: Dp(12.0),
570            lg: Dp(16.0),
571            xl: Dp(24.0),
572            xxl: Dp(32.0),
573        }
574    }
575}
576
577/// Elevation levels in [`Dp`].
578#[derive(Clone, Copy, Debug)]
579#[must_use]
580pub struct Elevation {
581    pub level0: Dp,
582    pub level1: Dp,
583    pub level2: Dp,
584    pub level3: Dp,
585    pub level4: Dp,
586    pub level5: Dp,
587}
588
589impl Default for Elevation {
590    fn default() -> Self {
591        Self {
592            level0: Dp(0.0),
593            level1: Dp(1.0),
594            level2: Dp(3.0),
595            level3: Dp(6.0),
596            level4: Dp(8.0),
597            level5: Dp(12.0),
598        }
599    }
600}
601
602/// Centralized animation specs for M3 motion design.
603#[derive(Clone, Copy, Debug)]
604#[must_use]
605pub struct MotionScheme {
606    /// Shape / size / bounds transitions (e.g., indicator position, elevation).
607    /// M3 standard: 200 ms FastOutSlowIn.
608    pub shape: AnimationSpec,
609    /// Color state transitions (e.g., label, tab text, selection).
610    /// M3 DefaultEffects spring.
611    pub color: AnimationSpec,
612    /// Quick color changes (e.g., checkbox fill, switch track, radio ring).
613    /// M3 FastEffects spring.
614    pub color_fast: AnimationSpec,
615    /// Overlay / popup enter‑exit (menus, dialogs, tooltips).
616    /// M3 standard: 120 ms FastOutSlowIn.
617    pub overlay: AnimationSpec,
618    /// Spring‑based positional animation (sheets, drawers, swipe‑to‑dismiss).
619    /// M3 standard: gentle spring (ζ = 0.5, k = 200).
620    pub spring: AnimationSpec,
621    /// Expanding containers (search bar, docked search suggestions).
622    /// M3 standard: 250 ms FastOutSlowIn.
623    pub expand: AnimationSpec,
624    /// Large layout transitions (bottom sheet height, scaffold reflow).
625    /// M3 standard: 300 ms EaseOut.
626    pub layout: AnimationSpec,
627    /// M3 DefaultSpatial spring (0.9, 700).
628    pub default_spatial: AnimationSpec,
629    /// M3 FastSpatial spring (0.9, 1400).
630    pub fast_spatial: AnimationSpec,
631    /// M3 SlowSpatial spring (0.9, 300).
632    pub slow_spatial: AnimationSpec,
633    /// M3 FastEffects spring (1.0, 3800).
634    pub fast_effects: AnimationSpec,
635}
636
637impl Default for MotionScheme {
638    fn default() -> Self {
639        Self {
640            shape: AnimationSpec::tween(Duration::from_millis(200), Easing::FastOutSlowIn),
641            color: AnimationSpec::spring_crit(40.0),
642            color_fast: AnimationSpec::spring(SpringSpec::new(1.0, 3800.0)),
643            overlay: AnimationSpec::tween(Duration::from_millis(120), Easing::FastOutSlowIn),
644            spring: AnimationSpec::spring_gentle(),
645            expand: AnimationSpec::tween(Duration::from_millis(250), Easing::FastOutSlowIn),
646            layout: AnimationSpec::tween(Duration::from_millis(300), Easing::EaseOut),
647            default_spatial: AnimationSpec::spring(SpringSpec::new(0.9, 700.0)),
648            fast_spatial: AnimationSpec::spring(SpringSpec::new(0.9, 1400.0)),
649            slow_spatial: AnimationSpec::spring(SpringSpec::new(0.9, 300.0)),
650            fast_effects: AnimationSpec::spring(SpringSpec::new(1.0, 3800.0)),
651        }
652    }
653}
654
655#[derive(Clone, Copy, Debug)]
656#[must_use]
657pub struct Theme {
658    pub colors: ColorScheme,
659    pub typography: Typography,
660    pub shapes: Shapes,
661    pub spacing: Spacing,
662    pub elevation: Elevation,
663    pub motion: MotionScheme,
664
665    pub focus: Color,
666    pub scrollbar_track: Color,
667    pub scrollbar_thumb: Color,
668    pub button_bg: Color,
669    pub button_bg_hover: Color,
670    pub button_bg_pressed: Color,
671}
672
673impl Deref for Theme {
674    type Target = ColorScheme;
675    fn deref(&self) -> &Self::Target {
676        &self.colors
677    }
678}
679
680impl Default for Theme {
681    fn default() -> Self {
682        let colors = ColorScheme::default();
683        Self {
684            colors,
685            typography: Typography::default(),
686            shapes: Shapes::default(),
687            spacing: Spacing::default(),
688            elevation: Elevation::default(),
689            motion: MotionScheme::default(),
690            focus: colors.focus,
691            scrollbar_track: Color::TRANSPARENT,
692            scrollbar_thumb: colors.outline.with_alpha(179),
693            button_bg: colors.primary,
694            button_bg_hover: colors.primary_container,
695            button_bg_pressed: colors.secondary_container,
696        }
697    }
698}
699
700impl Theme {
701    pub fn with_colors(mut self, colors: ColorScheme) -> Self {
702        self.colors = colors;
703        self
704    }
705
706    /// A dark theme around the default dark color scheme.
707    pub fn dark() -> Self {
708        Self::default().with_colors(ColorScheme::dark())
709    }
710
711    /// A light theme: default colors swapped for the light scheme plus light
712    /// chrome/button derivatives.
713    pub fn light() -> Self {
714        let colors = ColorScheme::light();
715        Self {
716            focus: colors.focus,
717            scrollbar_thumb: colors.outline.with_alpha(179),
718            button_bg: colors.primary,
719            button_bg_hover: colors.primary_container,
720            button_bg_pressed: colors.secondary_container,
721            colors,
722            ..Self::default()
723        }
724    }
725
726    /// Whether the theme's background reads as dark, for syncing OS window
727    /// chrome (titlebar / caption buttons) to the app theme.
728    pub fn is_dark(&self) -> bool {
729        self.colors.background.is_dark()
730    }
731}
732
733/// Platform/device scale (dp->px multiplier). Platform runner should set this.
734#[derive(Clone, Copy, Debug)]
735pub struct Density {
736    pub scale: f32,
737}
738impl Default for Density {
739    fn default() -> Self {
740        Self { scale: 1.0 }
741    }
742}
743
744/// Additional UI scale multiplier (app-controlled).
745#[derive(Clone, Copy, Debug)]
746pub struct UiScale(pub f32);
747impl Default for UiScale {
748    fn default() -> Self {
749        Self(1.0)
750    }
751}
752
753#[derive(Clone, Copy, Debug)]
754pub struct TextScale(pub f32);
755impl Default for TextScale {
756    fn default() -> Self {
757        Self(1.0)
758    }
759}
760
761pub fn with_theme<R>(theme: Theme, f: impl FnOnce() -> R) -> R {
762    with_locals_frame(|| {
763        set_local_boxed(TypeId::of::<Theme>(), Box::new(theme));
764        f()
765    })
766}
767
768pub fn with_density<R>(density: Density, f: impl FnOnce() -> R) -> R {
769    with_locals_frame(|| {
770        set_local_boxed(TypeId::of::<Density>(), Box::new(density));
771        f()
772    })
773}
774
775pub fn with_ui_scale<R>(s: UiScale, f: impl FnOnce() -> R) -> R {
776    with_locals_frame(|| {
777        set_local_boxed(TypeId::of::<UiScale>(), Box::new(s));
778        f()
779    })
780}
781
782pub fn with_text_scale<R>(ts: TextScale, f: impl FnOnce() -> R) -> R {
783    with_locals_frame(|| {
784        set_local_boxed(TypeId::of::<TextScale>(), Box::new(ts));
785        f()
786    })
787}
788
789pub fn with_text_direction<R>(dir: TextDirection, f: impl FnOnce() -> R) -> R {
790    with_locals_frame(|| {
791        set_local_boxed(TypeId::of::<TextDirection>(), Box::new(dir));
792        f()
793    })
794}
795
796pub fn with_window_insets<R>(insets: WindowInsets, f: impl FnOnce() -> R) -> R {
797    with_locals_frame(|| {
798        set_local_boxed(TypeId::of::<WindowInsets>(), Box::new(insets));
799        f()
800    })
801}
802
803#[derive(Clone, Copy, Debug)]
804pub struct ContentColor(pub Color);
805
806pub fn with_content_color<R>(color: Color, f: impl FnOnce() -> R) -> R {
807    with_locals_frame(|| {
808        set_local_boxed(TypeId::of::<ContentColor>(), Box::new(ContentColor(color)));
809        f()
810    })
811}
812
813pub fn content_color() -> Color {
814    let value = get_local::<ContentColor>()
815        .map(|color| color.0)
816        .unwrap_or_else(|| {
817            get_local::<Theme>()
818                .unwrap_or_else(|| defaults().read().theme)
819                .on_surface
820        });
821    record_local(LocalId::ContentColor, &value, fingerprint_color);
822    value
823}
824
825/// Compose `@Composable contentColorFor(backgroundColor)`.
826/// Scheme role pair if known, otherwise the current `LocalContentColor`.
827pub fn content_color_for(background: Color) -> Color {
828    if let Some(c) = theme().colors.content_color_for(background) {
829        return c;
830    }
831    content_color()
832}
833
834/// Composition-local default text size ([`Sp`]). Bare `Text(...)`
835/// children inherit the container's typography instead of the global default.
836#[derive(Clone, Copy, Debug)]
837pub struct TextSize(pub Sp);
838
839pub fn with_text_size<R>(size: Sp, f: impl FnOnce() -> R) -> R {
840    with_locals_frame(|| {
841        set_local_boxed(TypeId::of::<TextSize>(), Box::new(TextSize(size)));
842        f()
843    })
844}
845
846pub fn text_size() -> Option<Sp> {
847    let value = get_local::<TextSize>().map(|size| size.0);
848    record_local(LocalId::TextSize, &value, |value| {
849        fingerprint_text_size(*value)
850    });
851    value
852}
853
854/// Composition-local default indication (ripple/highlight) factory.
855/// Components like `Button` read this to get the default press feedback.
856/// Mirrors Compose's `LocalIndication`.
857#[derive(Clone, Debug, Default)]
858pub struct LocalIndication(pub Option<Rc<dyn IndicationNodeFactory>>);
859
860pub fn with_local_indication<R>(
861    indication: Option<Rc<dyn IndicationNodeFactory>>,
862    f: impl FnOnce() -> R,
863) -> R {
864    with_locals_frame(|| {
865        set_local_boxed(
866            std::any::TypeId::of::<LocalIndication>(),
867            Box::new(LocalIndication(indication)),
868        );
869        f()
870    })
871}
872
873/// Optional composition-local override for [`crate::input::InputMode`].
874/// Mirrors Compose `LocalInputModeManager` for tests and nested hosts.
875#[derive(Clone, Copy, Debug)]
876struct LocalInputMode(pub crate::input::InputMode);
877
878/// Override input mode for a composition subtree.
879pub fn with_input_mode<R>(mode: crate::input::InputMode, f: impl FnOnce() -> R) -> R {
880    with_locals_frame(|| {
881        set_local_boxed(
882            TypeId::of::<LocalInputMode>(),
883            Box::new(LocalInputMode(mode)),
884        );
885        f()
886    })
887}
888
889/// Read a composition-local input mode override, if any.
890pub(crate) fn local_input_mode() -> Option<crate::input::InputMode> {
891    let value = get_local::<LocalInputMode>().map(|mode| mode.0);
892    let effective = value.unwrap_or_else(crate::input::default_input_mode);
893    record_local(LocalId::InputMode, &effective, |value| {
894        fingerprint_input_mode(*value)
895    });
896    value
897}
898
899fn raw_local_indication() -> Option<Rc<dyn IndicationNodeFactory>> {
900    LOCALS_STACK.with(|stack| {
901        for frame in stack.borrow().iter().rev() {
902            if let Some(value) = frame.get(&TypeId::of::<LocalIndication>())
903                && let Some(indication) = value.downcast_ref::<LocalIndication>()
904            {
905                return indication.0.clone();
906            }
907        }
908        None
909    })
910}
911
912pub fn local_indication() -> Option<Rc<dyn IndicationNodeFactory>> {
913    let value = raw_local_indication();
914    record_local(LocalId::Indication, &value, fingerprint_indication);
915    value
916}
917
918/// System window insets (status bar, navigation bar, IME keyboard, etc.)
919#[derive(Clone, Copy, Debug, Default, PartialEq)]
920pub struct WindowInsets {
921    pub top: f32,
922    pub bottom: f32,
923    pub left: f32,
924    pub right: f32,
925    /// Soft keyboard (IME) inset from bottom of screen. Set by platform runner
926    /// when the keyboard opens/closes. Used by `imePadding()` modifier.
927    pub ime_bottom: f32,
928}
929
930/// Set the global default window insets (platform should call this when insets change).
931pub fn set_window_insets_default(insets: WindowInsets) {
932    let changed = {
933        let mut defaults = defaults().write();
934        let old = defaults.window_insets;
935        let changed = old.top.to_bits() != insets.top.to_bits()
936            || old.bottom.to_bits() != insets.bottom.to_bits()
937            || old.left.to_bits() != insets.left.to_bits()
938            || old.right.to_bits() != insets.right.to_bits()
939            || old.ime_bottom.to_bits() != insets.ime_bottom.to_bits();
940        defaults.window_insets = insets;
941        changed
942    };
943    set_local_boxed(TypeId::of::<WindowInsets>(), Box::new(insets));
944    if changed {
945        crate::request_frame();
946    }
947}
948
949/// Update just the IME bottom inset (keyboard height in px). Platform runners
950/// call this when the soft keyboard opens/closes.
951pub fn set_ime_inset(height_px: f32) {
952    let insets = {
953        let mut defaults = defaults().write();
954        let changed = defaults.window_insets.ime_bottom.to_bits() != height_px.to_bits();
955        defaults.window_insets.ime_bottom = height_px;
956        (changed, defaults.window_insets)
957    };
958    set_local_boxed(TypeId::of::<WindowInsets>(), Box::new(insets.1));
959    if insets.0 {
960        crate::request_frame();
961    }
962}
963
964/// Query current window insets.
965pub fn window_insets() -> WindowInsets {
966    let value = get_local::<WindowInsets>().unwrap_or_else(|| defaults().read().window_insets);
967    record_local(LocalId::WindowInsets, &value, fingerprint_window_insets);
968    value
969}
970
971/// Set the logical window container size (in dp). The `LayoutEngine` calls
972/// this on every layout from the physical viewport + density.
973pub fn set_window_container_size(width_dp: f32, height_dp: f32) {
974    let changed = {
975        let mut defaults = defaults().write();
976        let changed = defaults.container_width.to_bits() != width_dp.to_bits()
977            || defaults.container_height.to_bits() != height_dp.to_bits();
978        defaults.container_width = width_dp;
979        defaults.container_height = height_dp;
980        changed
981    };
982    if changed {
983        crate::request_frame();
984    }
985}
986
987/// Set just the logical window container width (in dp). Prefer
988/// [`set_window_container_size`]. Kept for hosts that update one axis at a time.
989pub fn set_window_container_width(w_dp: f32) {
990    let changed = {
991        let mut defaults = defaults().write();
992        let changed = defaults.container_width.to_bits() != w_dp.to_bits();
993        defaults.container_width = w_dp;
994        changed
995    };
996    if changed {
997        crate::request_frame();
998    }
999}
1000
1001/// Set just the logical window container height (in dp). Prefer
1002/// [`set_window_container_size`]. Kept for hosts that update one axis at a time.
1003pub fn set_window_container_height(h_dp: f32) {
1004    let changed = {
1005        let mut defaults = defaults().write();
1006        let changed = defaults.container_height.to_bits() != h_dp.to_bits();
1007        defaults.container_height = h_dp;
1008        changed
1009    };
1010    if changed {
1011        crate::request_frame();
1012    }
1013}
1014
1015/// The logical window container width in dp (used by Material dropdowns).
1016pub fn get_window_container_width() -> f32 {
1017    let value = defaults().read().container_width;
1018    record_local(LocalId::ContainerWidth, &value, |value| {
1019        fingerprint_f32(*value)
1020    });
1021    value
1022}
1023
1024/// The logical window container height in dp (used by Material search bars).
1025pub fn get_window_container_height() -> f32 {
1026    let value = defaults().read().container_height;
1027    record_local(LocalId::ContainerHeight, &value, |value| {
1028        fingerprint_f32(*value)
1029    });
1030    value
1031}
1032
1033/// Coarse width category for a window, computed from its current size.
1034///
1035/// Thresholds (in dp) match the Material 3 adaptive spec:
1036///
1037/// - [`WidthClass::Compact`]  : width < 600 dp
1038/// - [`WidthClass::Medium`]   : 600 dp <= width < 840 dp
1039/// - [`WidthClass::Expanded`] : width >= 840 dp
1040#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
1041pub enum WidthClass {
1042    #[default]
1043    Compact,
1044    Medium,
1045    Expanded,
1046}
1047
1048/// Coarse height category for a window, computed from its current size.
1049///
1050/// Thresholds (in dp) match the Material 3 adaptive spec:
1051///
1052/// - [`HeightClass::Compact`]  : height < 480 dp
1053/// - [`HeightClass::Medium`]   : 480 dp <= height < 900 dp
1054/// - [`HeightClass::Expanded`] : height >= 900 dp
1055#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
1056pub enum HeightClass {
1057    #[default]
1058    Compact,
1059    Medium,
1060    Expanded,
1061}
1062
1063/// Snapshot of the current window's size category.
1064///
1065/// The `LayoutEngine` updates the `WindowSizeClass` default local every time
1066/// the window is resized, so UI can read it via [`window_size_class()`] during
1067/// composition.
1068#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
1069pub struct WindowSizeClass {
1070    pub width: WidthClass,
1071    pub height: HeightClass,
1072}
1073
1074impl WindowSizeClass {
1075    /// `true` when there is enough horizontal space for multi-pane layouts.
1076    pub fn is_expanded_width(&self) -> bool {
1077        matches!(self.width, WidthClass::Expanded)
1078    }
1079    /// `true` when there is enough horizontal space for a two-pane layout
1080    /// (list + detail). Per M3 this is Medium or wider.
1081    pub fn is_at_least_medium_width(&self) -> bool {
1082        matches!(self.width, WidthClass::Medium | WidthClass::Expanded)
1083    }
1084}
1085
1086/// Compute a [`WindowSizeClass`] from a window size in physical pixels and
1087/// the current dp->px density scale (`Density.scale * UiScale.0`).
1088pub fn calculate_window_size_class(
1089    width_px: u32,
1090    height_px: u32,
1091    density_scale: f32,
1092) -> WindowSizeClass {
1093    let density = density_scale.max(0.0001);
1094    let width_dp = (width_px as f32) / density;
1095    let height_dp = (height_px as f32) / density;
1096
1097    let width = if width_dp < 600.0 {
1098        WidthClass::Compact
1099    } else if width_dp < 840.0 {
1100        WidthClass::Medium
1101    } else {
1102        WidthClass::Expanded
1103    };
1104    let height = if height_dp < 480.0 {
1105        HeightClass::Compact
1106    } else if height_dp < 900.0 {
1107        HeightClass::Medium
1108    } else {
1109        HeightClass::Expanded
1110    };
1111
1112    WindowSizeClass { width, height }
1113}
1114
1115/// Set the global default window size class used when no local is active.
1116/// Called by the `LayoutEngine` on resize.
1117pub fn set_window_size_class_default(class: WindowSizeClass) {
1118    let changed = {
1119        let mut defaults = defaults().write();
1120        let changed = defaults.window_size_class != class;
1121        defaults.window_size_class = class;
1122        changed
1123    };
1124    if changed {
1125        crate::request_frame();
1126    }
1127}
1128
1129/// Override the window size class for a subtree of the composition.
1130pub fn with_window_size_class<R>(class: WindowSizeClass, f: impl FnOnce() -> R) -> R {
1131    with_locals_frame(|| {
1132        set_local_boxed(TypeId::of::<WindowSizeClass>(), Box::new(class));
1133        f()
1134    })
1135}
1136
1137/// Query current window size class. Returns a default-initialized
1138/// `WindowSizeClass` (Compact/Compact) if nothing has been set yet.
1139pub fn window_size_class() -> WindowSizeClass {
1140    let value =
1141        get_local::<WindowSizeClass>().unwrap_or_else(|| defaults().read().window_size_class);
1142    record_local(
1143        LocalId::WindowSizeClass,
1144        &value,
1145        fingerprint_window_size_class,
1146    );
1147    value
1148}
1149
1150pub fn theme() -> Theme {
1151    let value = get_local::<Theme>().unwrap_or_else(|| defaults().read().theme);
1152    record_local(LocalId::Theme, &value, fingerprint_theme);
1153    value
1154}
1155
1156pub fn theme_fingerprint() -> u64 {
1157    fingerprint_theme(&theme())
1158}
1159
1160/// Same as [`theme_fingerprint`], but reuses a [`Theme`] the caller already
1161/// read. Fingerprinting formats the whole theme, so caching code should take
1162/// this overload rather than reading the local twice.
1163pub fn theme_fingerprint_of(theme: &Theme) -> u64 {
1164    fingerprint_theme(theme)
1165}
1166
1167pub fn density() -> Density {
1168    let value = get_local::<Density>().unwrap_or_else(|| defaults().read().density);
1169    record_local(LocalId::Density, &value, |value| {
1170        fingerprint_f32(value.scale)
1171    });
1172    value
1173}
1174
1175pub fn ui_scale() -> UiScale {
1176    let value = get_local::<UiScale>().unwrap_or_else(|| defaults().read().ui_scale);
1177    record_local(LocalId::UiScale, &value, |value| fingerprint_f32(value.0));
1178    value
1179}
1180
1181pub fn text_scale() -> TextScale {
1182    let value = get_local::<TextScale>().unwrap_or_else(|| defaults().read().text_scale);
1183    record_local(LocalId::TextScale, &value, |value| fingerprint_f32(value.0));
1184    value
1185}
1186
1187pub fn text_direction() -> TextDirection {
1188    let value = get_local::<TextDirection>().unwrap_or_else(|| defaults().read().text_direction);
1189    record_local(LocalId::TextDirection, &value, fingerprint_text_direction);
1190    value
1191}
1192
1193pub(crate) fn local_fingerprint(id: usize) -> u64 {
1194    match id {
1195        id if id == LocalId::Theme.index() => {
1196            fingerprint_theme(&get_local::<Theme>().unwrap_or_else(|| defaults().read().theme))
1197        }
1198        id if id == LocalId::Density.index() => fingerprint_f32(
1199            get_local::<Density>()
1200                .unwrap_or_else(|| defaults().read().density)
1201                .scale,
1202        ),
1203        id if id == LocalId::UiScale.index() => fingerprint_f32(
1204            get_local::<UiScale>()
1205                .unwrap_or_else(|| defaults().read().ui_scale)
1206                .0,
1207        ),
1208        id if id == LocalId::TextScale.index() => fingerprint_f32(
1209            get_local::<TextScale>()
1210                .unwrap_or_else(|| defaults().read().text_scale)
1211                .0,
1212        ),
1213        id if id == LocalId::TextDirection.index() => fingerprint_text_direction(
1214            &get_local::<TextDirection>().unwrap_or_else(|| defaults().read().text_direction),
1215        ),
1216        id if id == LocalId::WindowInsets.index() => fingerprint_window_insets(
1217            &get_local::<WindowInsets>().unwrap_or_else(|| defaults().read().window_insets),
1218        ),
1219        id if id == LocalId::WindowSizeClass.index() => fingerprint_window_size_class(
1220            &get_local::<WindowSizeClass>().unwrap_or_else(|| defaults().read().window_size_class),
1221        ),
1222        id if id == LocalId::ContainerWidth.index() => {
1223            fingerprint_f32(defaults().read().container_width)
1224        }
1225        id if id == LocalId::ContainerHeight.index() => {
1226            fingerprint_f32(defaults().read().container_height)
1227        }
1228        id if id == LocalId::ContentColor.index() => fingerprint_color(
1229            &get_local::<ContentColor>()
1230                .map(|value| value.0)
1231                .unwrap_or_else(|| {
1232                    get_local::<Theme>()
1233                        .unwrap_or_else(|| defaults().read().theme)
1234                        .on_surface
1235                }),
1236        ),
1237        id if id == LocalId::TextSize.index() => {
1238            fingerprint_text_size(get_local::<TextSize>().map(|value| value.0))
1239        }
1240        id if id == LocalId::Indication.index() => fingerprint_indication(&raw_local_indication()),
1241        id if id == LocalId::InputMode.index() => {
1242            fingerprint_input_mode(crate::input::input_mode())
1243        }
1244        _ => 0,
1245    }
1246}
1247
1248pub fn locals_stamp() -> u64 {
1249    let mut hasher = std::collections::hash_map::DefaultHasher::new();
1250    for id in 0..=LocalId::InputMode.index() {
1251        id.hash(&mut hasher);
1252        local_fingerprint(id).hash(&mut hasher);
1253    }
1254    hasher.finish()
1255}
1256
1257#[cfg(test)]
1258mod tests {
1259    use super::*;
1260
1261    #[test]
1262    fn width_class_thresholds_match_m3() {
1263        // Density 1.0 (1 dp = 1 px) for clarity.
1264        assert_eq!(
1265            calculate_window_size_class(100, 100, 1.0).width,
1266            WidthClass::Compact
1267        );
1268        assert_eq!(
1269            calculate_window_size_class(599, 100, 1.0).width,
1270            WidthClass::Compact
1271        );
1272        assert_eq!(
1273            calculate_window_size_class(600, 100, 1.0).width,
1274            WidthClass::Medium
1275        );
1276        assert_eq!(
1277            calculate_window_size_class(839, 100, 1.0).width,
1278            WidthClass::Medium
1279        );
1280        assert_eq!(
1281            calculate_window_size_class(840, 100, 1.0).width,
1282            WidthClass::Expanded
1283        );
1284        assert_eq!(
1285            calculate_window_size_class(2000, 100, 1.0).width,
1286            WidthClass::Expanded
1287        );
1288    }
1289
1290    #[test]
1291    fn height_class_thresholds_match_m3() {
1292        assert_eq!(
1293            calculate_window_size_class(100, 100, 1.0).height,
1294            HeightClass::Compact
1295        );
1296        assert_eq!(
1297            calculate_window_size_class(100, 479, 1.0).height,
1298            HeightClass::Compact
1299        );
1300        assert_eq!(
1301            calculate_window_size_class(100, 480, 1.0).height,
1302            HeightClass::Medium
1303        );
1304        assert_eq!(
1305            calculate_window_size_class(100, 899, 1.0).height,
1306            HeightClass::Medium
1307        );
1308        assert_eq!(
1309            calculate_window_size_class(100, 900, 1.0).height,
1310            HeightClass::Expanded
1311        );
1312    }
1313
1314    #[test]
1315    fn density_scales_thresholds() {
1316        // 2.0x density: 600 dp = 1200 px.
1317        let c = calculate_window_size_class(1199, 100, 2.0);
1318        assert_eq!(c.width, WidthClass::Compact);
1319        let c = calculate_window_size_class(1200, 100, 2.0);
1320        assert_eq!(c.width, WidthClass::Medium);
1321    }
1322
1323    #[test]
1324    fn is_at_least_medium_width() {
1325        let c = WindowSizeClass {
1326            width: WidthClass::Compact,
1327            height: HeightClass::Compact,
1328        };
1329        assert!(!c.is_at_least_medium_width());
1330        let c = WindowSizeClass {
1331            width: WidthClass::Medium,
1332            height: HeightClass::Compact,
1333        };
1334        assert!(c.is_at_least_medium_width());
1335        let c = WindowSizeClass {
1336            width: WidthClass::Expanded,
1337            height: HeightClass::Compact,
1338        };
1339        assert!(c.is_at_least_medium_width());
1340    }
1341}