Skip to main content

argui_platform/
application.rs

1use std::collections::HashSet;
2
3use crate::{ApplicationIdentity, PreferenceOverrides, TrayConfig, WindowKey, WindowSpec};
4
5#[derive(Clone, Debug, PartialEq)]
6pub struct ApplicationConfig {
7    pub identity: ApplicationIdentity,
8    pub windows: Vec<WindowSpec>,
9    pub tray: Option<TrayConfig>,
10    pub preferences: PreferenceOverrides,
11}
12
13impl ApplicationConfig {
14    #[must_use]
15    pub fn new(identity: ApplicationIdentity, main_window: crate::WindowConfig) -> Self {
16        Self {
17            identity,
18            windows: vec![WindowSpec::new(WindowKey::main(), main_window)],
19            tray: None,
20            preferences: PreferenceOverrides::default(),
21        }
22    }
23
24    #[must_use]
25    pub fn with_window(mut self, window: WindowSpec) -> Self {
26        self.windows.push(window);
27        self
28    }
29
30    #[must_use]
31    pub fn with_tray(mut self, tray: TrayConfig) -> Self {
32        self.tray = Some(tray);
33        self
34    }
35
36    #[must_use]
37    pub const fn with_preferences(mut self, preferences: PreferenceOverrides) -> Self {
38        self.preferences = preferences;
39        self
40    }
41
42    pub fn validate(&self) -> Result<(), ApplicationConfigError> {
43        let mut keys = HashSet::new();
44        for window in &self.windows {
45            if window.key.as_str().is_empty() {
46                return Err(ApplicationConfigError::EmptyWindowKey);
47            }
48            if !keys.insert(window.key.clone()) {
49                return Err(ApplicationConfigError::DuplicateWindowKey(
50                    window.key.clone(),
51                ));
52            }
53        }
54        if let Some(tray) = &self.tray {
55            tray.validate()
56                .map_err(|error| ApplicationConfigError::InvalidTray(error.to_string()))?;
57        }
58        Ok(())
59    }
60}
61
62#[derive(Clone, Debug, Eq, PartialEq)]
63pub enum ApplicationConfigError {
64    EmptyWindowKey,
65    DuplicateWindowKey(WindowKey),
66    InvalidTray(String),
67}
68
69impl std::fmt::Display for ApplicationConfigError {
70    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            Self::EmptyWindowKey => formatter.write_str("window keys cannot be empty"),
73            Self::DuplicateWindowKey(key) => {
74                write!(formatter, "duplicate window key: {}", key.as_str())
75            }
76            Self::InvalidTray(error) => formatter.write_str(error),
77        }
78    }
79}
80
81impl std::error::Error for ApplicationConfigError {}