use std::sync::Arc;
use crate::platform::Appearance;
use crate::theme::Theme;
use crate::ui::Ui;
use crate::{EventArgs, PropValue};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NetworkState {
None,
Local,
#[default]
Internet,
}
impl crate::prop::PropEnum for NetworkState {
const NAMES: &'static [&'static str] = &["none", "local", "internet"];
fn from_index(index: usize) -> Option<Self> {
[Self::None, Self::Local, Self::Internet].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ThemeMode {
#[default]
Project,
Light,
Dark,
System,
}
impl crate::prop::PropEnum for ThemeMode {
const NAMES: &'static [&'static str] = &["project", "light", "dark", "system"];
fn from_index(index: usize) -> Option<Self> {
[Self::Project, Self::Light, Self::Dark, Self::System].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MotionPreference {
#[default]
System,
Reduced,
Full,
}
impl crate::prop::PropEnum for MotionPreference {
const NAMES: &'static [&'static str] = &["system", "reduced", "full"];
fn from_index(index: usize) -> Option<Self> {
[Self::System, Self::Reduced, Self::Full].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
pub struct NetworkChanged(pub NetworkState);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SystemEvent {
Suspend,
Resume,
Appearance(Appearance),
ReducedMotion(bool),
DoNotDisturb(bool),
Network(NetworkState),
}
#[derive(Default)]
pub(crate) struct SystemState {
appearance: Option<Appearance>,
reduced_motion: Option<bool>,
do_not_disturb: Option<bool>,
network: Option<NetworkState>,
suspended: bool,
motion: MotionPreference,
theme_mode: ThemeMode,
variants: Option<(Arc<Theme>, Arc<Theme>)>,
project_theme: Option<Arc<Theme>>,
idle_threshold: f64,
idle_now: bool,
idle_scheduled: bool,
}
impl Ui {
fn system_state(&mut self) -> &mut SystemState {
self.extension::<SystemState>()
}
fn system_state_ref(&self) -> Option<&SystemState> {
self.extension_ref::<SystemState>()
}
pub fn system_event(&mut self, event: SystemEvent) {
let fire = |ui: &mut Ui, name: &str, args: EventArgs| {
for app in ui.application_events() {
ui.fire(app, name, &args);
}
};
match event {
SystemEvent::Suspend => {
if !std::mem::replace(&mut self.system_state().suspended, true) {
fire(self, "on_suspend", EventArgs::None);
}
}
SystemEvent::Resume => {
if std::mem::replace(&mut self.system_state().suspended, false) {
fire(self, "on_resume", EventArgs::None);
}
}
SystemEvent::Appearance(a) => {
let before = self.system_state().appearance.replace(a);
if before != Some(a) {
self.apply_theme_mode();
if before.is_some() {
fire(self, "on_appearance_change", EventArgs::Value(PropValue::Enum(appearance_name(a).into())));
}
}
}
SystemEvent::ReducedMotion(on) => {
if self.system_state().reduced_motion.replace(on) != Some(on) {
self.request_repaint();
}
}
SystemEvent::DoNotDisturb(on) => {
let before = self.system_state().do_not_disturb.replace(on);
if before.is_some_and(|b| b != on) {
fire(self, "on_do_not_disturb_change", EventArgs::Value(PropValue::Bool(on)));
}
}
SystemEvent::Network(n) => {
let before = self.system_state().network.replace(n);
if before.is_some_and(|b| b != n) {
fire(self, "on_network_change", EventArgs::Value(PropValue::Enum(crate::prop::PropEnum::name(n).into())));
let watchers: Vec<_> = self.components().filter(|&c| self.class_name(c) == Some("Network")).collect();
for c in watchers {
self.send_message(c, &NetworkChanged(n));
}
}
}
}
self.process_events();
}
pub fn system_appearance(&self) -> Appearance {
self.system_state_ref()
.and_then(|s| s.appearance)
.or_else(|| self.services().screen.as_ref().map(|s| s.appearance()))
.unwrap_or_default()
}
pub fn reduced_motion(&self) -> bool {
let s = self.system_state_ref();
match s.map(|s| s.motion).unwrap_or_default() {
MotionPreference::Reduced => true,
MotionPreference::Full => false,
MotionPreference::System => s.and_then(|s| s.reduced_motion).unwrap_or(false),
}
}
pub fn system_reduced_motion(&self) -> bool {
self.system_state_ref().and_then(|s| s.reduced_motion).unwrap_or(false)
}
pub fn set_motion_preference(&mut self, preference: MotionPreference) {
self.system_state().motion = preference;
self.request_repaint();
}
pub fn motion_preference(&self) -> MotionPreference {
self.system_state_ref().map(|s| s.motion).unwrap_or_default()
}
pub fn do_not_disturb(&self) -> bool {
self.services()
.desktop
.as_ref()
.and_then(|d| d.do_not_disturb())
.or_else(|| self.system_state_ref().and_then(|s| s.do_not_disturb))
.unwrap_or(false)
}
pub fn network_state(&self) -> NetworkState {
self.system_state_ref().and_then(|s| s.network).unwrap_or_default()
}
pub fn network_notified(&self) -> bool {
self.system_state_ref().is_some_and(|s| s.network.is_some())
}
pub fn suspended(&self) -> bool {
self.system_state_ref().is_some_and(|s| s.suspended)
}
pub fn idle_seconds(&self) -> f64 {
self.services().desktop.as_ref().and_then(|d| d.idle_seconds()).unwrap_or(0.0)
}
pub fn set_idle_threshold(&mut self, seconds: f64) {
let s = self.system_state();
s.idle_threshold = if seconds.is_finite() { seconds.max(0.0) } else { 0.0 };
s.idle_now = false;
self.schedule_idle_check();
}
pub fn idle_threshold(&self) -> f64 {
self.system_state_ref().map_or(0.0, |s| s.idle_threshold)
}
fn schedule_idle_check(&mut self) {
let (threshold, idle_now, scheduled) = {
let s = self.system_state();
(s.idle_threshold, s.idle_now, s.idle_scheduled)
};
if threshold <= 0.0 || scheduled {
return;
}
let idle = self.idle_seconds();
let wait = if idle_now { 1.0 } else { (threshold - idle).max(0.25) };
self.system_state().idle_scheduled = true;
self.set_timeout((wait * 1000.0).ceil() as u64, |ui| {
ui.system_state().idle_scheduled = false;
ui.check_idle();
});
}
pub fn check_idle(&mut self) {
let threshold = self.idle_threshold();
if threshold <= 0.0 {
return;
}
let idle = self.idle_seconds() >= threshold;
if std::mem::replace(&mut self.system_state().idle_now, idle) != idle {
for app in self.application_events() {
self.fire(app, "on_idle", &EventArgs::Value(PropValue::Bool(idle)));
}
self.process_events();
}
self.schedule_idle_check();
}
pub fn set_theme_mode(&mut self, mode: ThemeMode) {
let before = std::mem::replace(&mut self.system_state().theme_mode, mode);
if before == ThemeMode::Project && mode != ThemeMode::Project {
let theme = self.shared_theme();
self.system_state().project_theme = Some(theme);
}
if mode == ThemeMode::Project {
if let Some(theme) = self.system_state().project_theme.take() {
self.set_shared_theme(theme);
}
return;
}
self.apply_theme_mode();
}
pub fn theme_mode(&self) -> ThemeMode {
self.system_state_ref().map(|s| s.theme_mode).unwrap_or_default()
}
pub fn set_theme_variants(&mut self, light: Theme, dark: Theme) {
self.system_state().variants = Some((Arc::new(light), Arc::new(dark)));
self.apply_theme_mode();
}
fn apply_theme_mode(&mut self) {
let dark = match self.theme_mode() {
ThemeMode::Project => return,
ThemeMode::Light => false,
ThemeMode::Dark => true,
ThemeMode::System => self.system_appearance() == Appearance::Dark,
};
if self.theme().dark == dark {
return;
}
let base = self.system_state_ref().and_then(|s| s.project_theme.clone()).unwrap_or_else(|| self.shared_theme());
let chosen = match self.system_state_ref().and_then(|s| s.variants.clone()) {
Some((light, dark_theme)) => Some(if dark { dark_theme } else { light }),
None => crate::themes::of_family(base.family_name(), dark).filter(|t| t.dark == dark).map(|t| Arc::new(t.clone())),
};
if let Some(theme) = chosen {
self.set_shared_theme(theme);
}
}
}
pub fn appearance_name(a: Appearance) -> &'static str {
match a {
Appearance::Light => "light",
Appearance::Dark => "dark",
}
}
pub fn json_strings(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut chars = text.chars();
while let Some(c) = chars.next() {
if c != '"' {
continue;
}
let mut item = String::new();
while let Some(c) = chars.next() {
match c {
'"' => break,
'\\' => match chars.next() {
Some('n') => item.push('\n'),
Some('t') => item.push('\t'),
Some('r') => item.push('\r'),
Some('u') => {
let hex: String = chars.by_ref().take(4).collect();
if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
item.push(ch);
}
}
Some(other) => item.push(other),
None => {}
},
other => item.push(other),
}
}
out.push(item);
}
out
}