Skip to main content

vizia_core/
environment.rs

1//! A model for system specific state which can be accessed by any model or view.
2use crate::prelude::*;
3
4#[cfg(target_os = "linux")]
5use mundy::Interest;
6#[cfg(target_os = "linux")]
7use mundy::Preferences;
8use unic_langid::CharacterDirection;
9use unic_langid::LanguageIdentifier;
10
11/// And enum which represents the current built-in theme mode.
12#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
13pub enum ThemeMode {
14    /// Follow the system theme.
15    #[default]
16    System,
17    /// The built-in vizia dark theme.
18    DarkMode,
19    /// The built-in vizia light theme.
20    LightMode,
21}
22
23use crate::{context::EventContext, events::Event};
24
25/// A model for system specific state which can be accessed by any model or view.
26pub struct Environment {
27    /// The locale used for localization.
28    pub locale: Signal<LanguageIdentifier>,
29    /// The text and layout direction used by the application.
30    pub direction: Signal<Direction>,
31    /// The maximum interval between two clicks to be recognised as a double-click.
32    pub double_click_interval: Duration,
33    /// The delay before a tooltip fades in.
34    pub tooltip_delay: Duration,
35    /// The user's theme preference (may be `System` to follow the OS).
36    pub theme_mode: ThemeMode,
37    /// The OS-reported system theme (always `DarkMode` or `LightMode`, never `System`).
38    pub system_theme_mode: ThemeMode,
39    /// The timer used to blink the caret of a textbox.
40    pub(crate) caret_timer: Timer,
41    /// The distance the mouse has to be dragged to start a drag operation.
42    pub drag_distance: Signal<u32>,
43    /// Whether the layout debug overlay is enabled. When set, views which underwent layout in the
44    /// most recent layout pass are outlined in orange until the next layout pass.
45    pub debug_layout: bool,
46}
47
48fn direction_from_locale(locale: &LanguageIdentifier) -> Direction {
49    match locale.character_direction() {
50        CharacterDirection::RTL => Direction::RightToLeft,
51        _ => Direction::LeftToRight,
52    }
53}
54
55pub(crate) fn apply_direction_class(cx: &mut EventContext, direction: Direction) {
56    let rtl = direction == Direction::RightToLeft;
57    cx.with_current(Entity::root(), |cx| {
58        cx.toggle_class("rtl", rtl);
59    });
60}
61
62pub(crate) fn apply_theme_class(cx: &mut EventContext, is_dark: bool) {
63    cx.with_current(Entity::root(), |cx| {
64        cx.toggle_class("dark", is_dark);
65    });
66}
67
68fn detect_theme() -> ThemeMode {
69    #[cfg(target_os = "linux")]
70    {
71        let mundy_prefs =
72            Preferences::once_blocking(Interest::ColorScheme, Duration::from_millis(100));
73
74        if let Some(preferences) = mundy_prefs
75            && preferences.color_scheme == mundy::ColorScheme::Dark
76        {
77            ThemeMode::DarkMode
78        } else {
79            ThemeMode::LightMode
80        }
81    }
82
83    #[cfg(not(target_os = "linux"))]
84    {
85        ThemeMode::LightMode
86    }
87}
88
89impl Environment {
90    pub(crate) fn new(cx: &mut Context) -> Self {
91        let locale: LanguageIdentifier =
92            sys_locale::get_locale().and_then(|l| l.parse().ok()).unwrap_or_default();
93        let caret_timer = cx.add_timer(Duration::from_millis(530), None, |cx, action| {
94            if matches!(action, TimerAction::Tick(_)) {
95                cx.emit(TextEvent::ToggleCaret);
96            }
97        });
98        let direction = direction_from_locale(&locale);
99        cx.style.debug_layout = false;
100        Self {
101            locale: Signal::new(locale.clone()),
102            direction: Signal::new(direction),
103            double_click_interval: Duration::from_millis(500),
104            tooltip_delay: Duration::from_millis(1500),
105            theme_mode: ThemeMode::default(),
106            system_theme_mode: detect_theme(),
107            caret_timer,
108            drag_distance: Signal::new(4),
109            debug_layout: false,
110        }
111    }
112
113    /// Returns the effective (resolved) theme, substituting the OS theme when the
114    /// user preference is [`ThemeMode::System`].
115    pub fn effective_theme(&self) -> ThemeMode {
116        match self.theme_mode {
117            ThemeMode::System => self.system_theme_mode,
118            other => other,
119        }
120    }
121}
122
123/// Events for setting the state in the [Environment].
124pub enum EnvironmentEvent {
125    /// Set the locale used for the whole application.
126    SetLocale(LanguageIdentifier),
127    /// Set the text and layout direction used by the whole application.
128    SetDirection(Direction),
129    /// Set the default theme mode.
130    // TODO: add SetSysTheme event when the winit `set_theme` fixed.
131    SetThemeMode(ThemeMode),
132    /// Reset the locale to use the system provided locale.
133    UseSystemLocale,
134    /// Alternate between dark and light theme modes.
135    ToggleThemeMode,
136    /// Set the maximum interval between two clicks to be recognised as a double-click.
137    SetDoubleClickInterval(Duration),
138    /// Set the delay before a tooltip fades in.
139    SetTooltipDelay(Duration),
140    /// Set the distance the mouse has to be dragged to start a drag operation.
141    SetDragDistance(u32),
142    /// Enable or disable the layout debug overlay.
143    SetDebugLayout(bool),
144    /// Toggle the layout debug overlay on or off.
145    ToggleDebugLayout,
146}
147
148impl Model for Environment {
149    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
150        event.take(|event, _| match event {
151            EnvironmentEvent::SetLocale(locale) => {
152                self.locale.set(locale.clone());
153                let direction = direction_from_locale(&locale);
154                self.direction.set(direction);
155                apply_direction_class(cx, direction);
156                cx.reload_styles().unwrap();
157            }
158
159            EnvironmentEvent::SetDirection(direction) => {
160                self.direction.set_if_changed(direction);
161                apply_direction_class(cx, direction);
162                cx.reload_styles().unwrap();
163            }
164
165            EnvironmentEvent::SetThemeMode(theme) => {
166                self.theme_mode = theme;
167                let is_dark = self.effective_theme() == ThemeMode::DarkMode;
168                apply_theme_class(cx, is_dark);
169                cx.reload_styles().unwrap();
170            }
171
172            EnvironmentEvent::UseSystemLocale => {
173                let locale: LanguageIdentifier =
174                    sys_locale::get_locale().map(|l| l.parse().unwrap()).unwrap_or_default();
175                let direction = direction_from_locale(&locale);
176                self.locale.set(locale);
177                self.direction.set(direction);
178                apply_direction_class(cx, direction);
179                cx.reload_styles().unwrap();
180            }
181
182            EnvironmentEvent::ToggleThemeMode => {
183                let theme_mode = match self.theme_mode {
184                    ThemeMode::System => ThemeMode::System,
185                    ThemeMode::DarkMode => ThemeMode::LightMode,
186                    ThemeMode::LightMode => ThemeMode::DarkMode,
187                };
188
189                self.theme_mode = theme_mode;
190
191                let is_dark = self.effective_theme() == ThemeMode::DarkMode;
192                apply_theme_class(cx, is_dark);
193
194                cx.reload_styles().unwrap();
195            }
196
197            EnvironmentEvent::SetDoubleClickInterval(interval) => {
198                self.double_click_interval = interval;
199            }
200
201            EnvironmentEvent::SetTooltipDelay(delay) => {
202                self.tooltip_delay = delay;
203            }
204
205            EnvironmentEvent::SetDragDistance(distance) => {
206                self.drag_distance.set_if_changed(distance);
207            }
208
209            EnvironmentEvent::SetDebugLayout(enabled) => {
210                self.debug_layout = enabled;
211                cx.style.debug_layout = enabled;
212                if !enabled {
213                    cx.style.laid_out.clear();
214                }
215                cx.needs_redraw();
216            }
217
218            EnvironmentEvent::ToggleDebugLayout => {
219                self.debug_layout = !self.debug_layout;
220                cx.style.debug_layout = self.debug_layout;
221                if !self.debug_layout {
222                    cx.style.laid_out.clear();
223                }
224                cx.needs_redraw();
225            }
226        });
227
228        event.map(|event, _| match event {
229            WindowEvent::ThemeChanged(theme) => {
230                self.system_theme_mode = *theme;
231                if self.theme_mode == ThemeMode::System {
232                    let is_dark = self.system_theme_mode == ThemeMode::DarkMode;
233                    apply_theme_class(cx, is_dark);
234                    cx.reload_styles().unwrap();
235                }
236            }
237            _ => (),
238        })
239    }
240}