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
//! Integrations for cosmic-config — the cosmic configuration system.

use notify::{
    event::{EventKind, ModifyKind},
    Watcher,
};
use serde::{de::DeserializeOwned, Serialize};
use std::{
    fmt, fs,
    io::Write,
    path::{Path, PathBuf},
    sync::Mutex,
};

#[cfg(feature = "subscription")]
mod subscription;
#[cfg(feature = "subscription")]
pub use subscription::*;

#[cfg(all(feature = "dbus", feature = "subscription"))]
pub mod dbus;

#[cfg(feature = "macro")]
pub use cosmic_config_derive;

#[cfg(feature = "calloop")]
pub mod calloop;

#[derive(Debug)]
pub enum Error {
    AtomicWrites(atomicwrites::Error<std::io::Error>),
    InvalidName(String),
    Io(std::io::Error),
    NoConfigDirectory,
    Notify(notify::Error),
    Ron(ron::Error),
    RonSpanned(ron::error::SpannedError),
    GetKey(String, std::io::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::AtomicWrites(err) => err.fmt(f),
            Self::InvalidName(name) => write!(f, "invalid config name '{}'", name),
            Self::Io(err) => err.fmt(f),
            Self::NoConfigDirectory => write!(f, "cosmic config directory not found"),
            Self::Notify(err) => err.fmt(f),
            Self::Ron(err) => err.fmt(f),
            Self::RonSpanned(err) => err.fmt(f),
            Self::GetKey(key, err) => write!(f, "failed to get key '{}': {}", key, err),
        }
    }
}

impl std::error::Error for Error {}

impl From<atomicwrites::Error<std::io::Error>> for Error {
    fn from(f: atomicwrites::Error<std::io::Error>) -> Self {
        Self::AtomicWrites(f)
    }
}

impl From<std::io::Error> for Error {
    fn from(f: std::io::Error) -> Self {
        Self::Io(f)
    }
}

impl From<notify::Error> for Error {
    fn from(f: notify::Error) -> Self {
        Self::Notify(f)
    }
}

impl From<ron::Error> for Error {
    fn from(f: ron::Error) -> Self {
        Self::Ron(f)
    }
}

impl From<ron::error::SpannedError> for Error {
    fn from(f: ron::error::SpannedError) -> Self {
        Self::RonSpanned(f)
    }
}

pub trait ConfigGet {
    /// Get a configuration value
    fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T, Error>;
}

pub trait ConfigSet {
    /// Set a configuration value
    fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error>;
}

#[derive(Clone, Debug)]
pub struct Config {
    system_path: Option<PathBuf>,
    user_path: Option<PathBuf>,
}

/// Check that the name is relative and doesn't contain . or ..
fn sanitize_name(name: &str) -> Result<&Path, Error> {
    let path = Path::new(name);
    if path
        .components()
        .all(|x| matches!(x, std::path::Component::Normal(_)))
    {
        Ok(path)
    } else {
        Err(Error::InvalidName(name.to_owned()))
    }
}

impl Config {
    /// Get the config for the libcosmic toolkit
    pub fn libcosmic() -> Result<Self, Error> {
        Self::new("com.system76.libcosmic", 1)
    }

    /// Get a system config for the given name and config version
    pub fn system(name: &str, version: u64) -> Result<Self, Error> {
        let path = sanitize_name(name)?.join(format!("v{version}"));
        #[cfg(unix)]
        let system_path = xdg::BaseDirectories::with_prefix("cosmic")
            .map_err(std::io::Error::from)?
            .find_data_file(path);

        #[cfg(windows)]
        let system_path =
            known_folders::get_known_folder_path(known_folders::KnownFolder::ProgramFilesCommon)
                .map(|x| x.join("COSMIC").join(&path));

        Ok(Self {
            system_path,
            user_path: None,
        })
    }

    /// Get config for the given application name and config version
    // Use folder at XDG config/name for config storage, return Config if successful
    //TODO: fallbacks for flatpak (HOST_XDG_CONFIG_HOME, xdg-desktop settings proxy)
    pub fn new(name: &str, version: u64) -> Result<Self, Error> {
        // Look for [name]/v[version]
        let path = sanitize_name(name)?.join(format!("v{}", version));

        // Search data file, which provides default (e.g. /usr/share)
        #[cfg(unix)]
        let system_path = xdg::BaseDirectories::with_prefix("cosmic")
            .map_err(std::io::Error::from)?
            .find_data_file(&path);

        #[cfg(windows)]
        let system_path =
            known_folders::get_known_folder_path(known_folders::KnownFolder::ProgramFilesCommon)
                .map(|x| x.join("COSMIC").join(&path));

        // Get libcosmic user configuration directory
        let cosmic_user_path = dirs::config_dir()
            .ok_or(Error::NoConfigDirectory)?
            .join("cosmic");

        let user_path = cosmic_user_path.join(path);
        // Create new configuration directory if not found.
        fs::create_dir_all(&user_path)?;

        // Return Config
        Ok(Self {
            system_path,
            user_path: Some(user_path),
        })
    }

    /// Get config for the given application name and config version and custom path.
    pub fn with_custom_path(name: &str, version: u64, custom_path: PathBuf) -> Result<Self, Error> {
        // Look for [name]/v[version]
        let path = sanitize_name(name)?.join(format!("v{version}"));

        let cosmic_user_path = custom_path.join("cosmic");

        let user_path = cosmic_user_path.join(path);
        // Create new configuration directory if not found.
        fs::create_dir_all(&user_path)?;

        // Return Config
        Ok(Self {
            system_path: None,
            user_path: Some(user_path),
        })
    }

    /// Get state for the given application name and config version. State is meant to be used to
    /// store items that may need to be exposed to other programs but will change regularly without
    /// user action
    // Use folder at XDG config/name for config storage, return Config if successful
    //TODO: fallbacks for flatpak (HOST_XDG_CONFIG_HOME, xdg-desktop settings proxy)
    pub fn new_state(name: &str, version: u64) -> Result<Self, Error> {
        // Look for [name]/v[version]
        let path = sanitize_name(name)?.join(format!("v{}", version));

        // Get libcosmic user state directory
        let cosmic_user_path = dirs::state_dir()
            .ok_or(Error::NoConfigDirectory)?
            .join("cosmic");

        let user_path = cosmic_user_path.join(path);
        // Create new state directory if not found.
        fs::create_dir_all(&user_path)?;

        Ok(Self {
            system_path: None,
            user_path: Some(user_path),
        })
    }

    // Start a transaction (to set multiple configs at the same time)
    pub fn transaction<'a>(&'a self) -> ConfigTransaction<'a> {
        ConfigTransaction {
            config: self,
            updates: Mutex::new(Vec::new()),
        }
    }

    // Watch keys for changes, will be triggered once per transaction
    // This may end up being an mpsc channel instead of a function
    // See EventHandler in the notify crate: https://docs.rs/notify/latest/notify/trait.EventHandler.html
    // Having a callback allows for any application abstraction to be used
    pub fn watch<F>(&self, f: F) -> Result<notify::RecommendedWatcher, Error>
    // Argument is an array of all keys that changed in that specific transaction
    //TODO: simplify F requirements
    where
        F: Fn(&Self, &[String]) + Send + Sync + 'static,
    {
        let watch_config = self.clone();
        let Some(user_path) = self.user_path.as_ref() else {
            return Err(Error::NoConfigDirectory);
        };
        let user_path_clone = user_path.clone();
        let mut watcher =
            notify::recommended_watcher(move |event_res: Result<notify::Event, notify::Error>| {
                match &event_res {
                    Ok(event) => {
                        match &event.kind {
                            EventKind::Access(_) | EventKind::Modify(ModifyKind::Metadata(_)) => {
                                // Data not mutated
                                return;
                            }
                            _ => {}
                        }

                        let mut keys = Vec::new();
                        for path in &event.paths {
                            match path.strip_prefix(&user_path_clone) {
                                Ok(key_path) => {
                                    if let Some(key) = key_path.to_str() {
                                        // Skip any .atomicwrite temporary files
                                        if key.starts_with(".atomicwrite") {
                                            continue;
                                        }
                                        keys.push(key.to_string());
                                    }
                                }
                                Err(_err) => {
                                    //TODO: handle errors
                                }
                            }
                        }
                        if !keys.is_empty() {
                            f(&watch_config, &keys);
                        }
                    }
                    Err(_err) => {
                        //TODO: handle errors
                    }
                }
            })?;
        watcher.watch(user_path, notify::RecursiveMode::NonRecursive)?;
        Ok(watcher)
    }

    fn default_path(&self, key: &str) -> Result<PathBuf, Error> {
        let Some(system_path) = self.system_path.as_ref() else {
            return Err(Error::NoConfigDirectory);
        };

        Ok(system_path.join(sanitize_name(key)?))
    }

    fn key_path(&self, key: &str) -> Result<PathBuf, Error> {
        let Some(user_path) = self.user_path.as_ref() else {
            return Err(Error::NoConfigDirectory);
        };
        Ok(user_path.join(sanitize_name(key)?))
    }
}

// Getting any setting is available on a Config object
impl ConfigGet for Config {
    //TODO: check for transaction
    fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T, Error> {
        // If key path exists
        let key_path = self.key_path(key);
        let data = match key_path {
            Ok(key_path) if key_path.is_file() => {
                // Load user override
                fs::read_to_string(key_path).map_err(|err| Error::GetKey(key.to_string(), err))?
            }
            _ => {
                // Load system default
                let default_path = self.default_path(key)?;
                fs::read_to_string(default_path)
                    .map_err(|err| Error::GetKey(key.to_string(), err))?
            }
        };
        let t = ron::from_str(&data)?;
        Ok(t)
    }
}

// Setting any setting in this way will do one transaction per set call
impl ConfigSet for Config {
    fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
        // Wrap up single key/value sets in a transaction
        let tx = self.transaction();
        tx.set(key, value)?;
        tx.commit()
    }
}

#[must_use = "Config transaction must be committed"]
pub struct ConfigTransaction<'a> {
    config: &'a Config,
    //TODO: use map?
    updates: Mutex<Vec<(PathBuf, String)>>,
}

impl<'a> ConfigTransaction<'a> {
    /// Apply all pending changes from ConfigTransaction
    //TODO: apply all changes at once
    pub fn commit(self) -> Result<(), Error> {
        let mut updates = self.updates.lock().unwrap();
        for (key_path, data) in updates.drain(..) {
            atomicwrites::AtomicFile::new(
                key_path,
                atomicwrites::OverwriteBehavior::AllowOverwrite,
            )
            .write(|file| file.write_all(data.as_bytes()))?;
        }
        Ok(())
    }
}

// Setting any setting in this way will do one transaction for all settings
// when commit finishes that transaction
impl<'a> ConfigSet for ConfigTransaction<'a> {
    fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
        //TODO: sanitize key (no slashes, cannot be . or ..)
        let key_path = self.config.key_path(key)?;
        let data = ron::ser::to_string_pretty(&value, ron::ser::PrettyConfig::new())?;
        //TODO: replace duplicates?
        {
            let mut updates = self.updates.lock().unwrap();
            updates.push((key_path, data));
        }
        Ok(())
    }
}

pub trait CosmicConfigEntry
where
    Self: Sized,
{
    const VERSION: u64;

    fn write_entry(&self, config: &Config) -> Result<(), crate::Error>;
    fn get_entry(config: &Config) -> Result<Self, (Vec<crate::Error>, Self)>;
    /// Returns the keys that were updated
    fn update_keys<T: AsRef<str>>(
        &mut self,
        config: &Config,
        changed_keys: &[T],
    ) -> (Vec<crate::Error>, Vec<&'static str>);
}

pub struct Update<T> {
    pub errors: Vec<crate::Error>,
    pub keys: Vec<&'static str>,
    pub config: T,
}