this repo has no description
1use std::{
2 collections::HashMap,
3 fs::File,
4 io::{Read, Write},
5 path::PathBuf,
6 sync::{Mutex, MutexGuard},
7};
8
9use chrono::Utc;
10use flate2::{read::GzDecoder, write::GzEncoder, Compression};
11use serde::{Deserialize, Serialize};
12
13use crate::structs::nodes::Node;
14
15#[derive(Clone, Serialize, Deserialize, Debug)]
16pub struct ConfigValues {
17 #[serde(default)]
18 pub loaded_tabs: HashMap<String, (Vec<Node>, String, Option<String>, bool)>,
19
20 #[serde(default)]
21 pub hide_editor_on_start: bool,
22}
23
24pub struct Config {
25 pub store: Mutex<ConfigValues>,
26 path: PathBuf,
27}
28
29impl Config {
30 pub fn new(path: PathBuf) -> Self {
31 let json_string = if path.exists() {
32 let mut decoder = GzDecoder::new(File::open(&path).unwrap());
33 let mut string = String::new();
34
35 decoder.read_to_string(&mut string).unwrap();
36 string
37 } else {
38 "{}".into()
39 };
40
41 let json: ConfigValues = serde_json::from_str(&json_string).unwrap();
42
43 Config {
44 store: Mutex::new(json),
45 path: path,
46 }
47 }
48
49 pub fn save(&self) {
50 let mut dat = self.store.lock().unwrap();
51
52 let dat = serde_json::to_string(&*dat).unwrap();
53
54 let file = File::create(&self.path).unwrap();
55 let mut encoder = GzEncoder::new(file, Compression::default());
56
57 encoder.write_all(dat.as_bytes()).unwrap();
58 encoder.finish().unwrap();
59 }
60
61 pub fn save_prelocked(&self, mut dat: MutexGuard<'_, ConfigValues>) {
62 let dat = serde_json::to_string(&*dat).unwrap();
63
64 let file = File::create(&self.path).unwrap();
65 let mut encoder = GzEncoder::new(file, Compression::default());
66
67 encoder.write_all(dat.as_bytes()).unwrap();
68 encoder.finish().unwrap();
69 }
70}