sysd-manager 2.19.6

Application to empower user to manage their <b>systemd units</b> via Graphical User Interface. Not only are you able to make changes to the enablement and running status of each of the units, but you will also be able to view and modify their unit files and check the journal logs.
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use crate::gtk::prelude::ListModelExtManual;
use crate::widget::{
    unit_list::UnitCuratedList, unit_properties_selector::data_selection::UnitPropertySelection,
};
use indexmap::{IndexMap, IndexSet};
use serde::{Deserialize, Serialize};
use std::{env, fmt::Display, path::Path};
use systemd::runtime;
use tokio::fs::{self};
use tokio::io::AsyncWriteExt;
use tracing::{error, info, warn};

const UNIT_COLUMNS: &str = "unit_columns.toml";

#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct UnitColumn {
    pub id: String,
    pub title: Option<String>,
    #[serde(rename = "width")]
    pub fixed_width: i32,
    pub expands: bool,
    pub resizable: bool,
    pub visible: bool,
    #[serde(rename = "type")]
    pub prop_type: Option<String>,
    pub sort: Option<SortType>,
}

impl Default for UnitColumn {
    fn default() -> Self {
        Self {
            id: "".to_owned(),
            title: None,
            fixed_width: -1,
            expands: false,
            resizable: false,
            visible: true,
            prop_type: None,
            sort: None,
        }
    }
}

impl UnitColumn {
    pub fn from(data: &UnitPropertySelection) -> Self {
        let sort = if data.sort() == SortType::Unset {
            None
        } else {
            Some(data.sort())
        };

        Self {
            id: data.id().map(|s| s.to_string()).unwrap_or_default(),
            title: data.title().map(|s| s.to_string()),
            fixed_width: data.fixed_width(),
            expands: data.expands(),
            resizable: data.resizable(),
            visible: data.visible(),
            prop_type: data.prop_type(),
            sort,
        }
    }

    pub(crate) fn new(id: &str, arg: &str) -> Self {
        Self {
            id: id.to_owned(),
            prop_type: Some(arg.to_owned()),
            ..Default::default()
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default, PartialEq, Eq, glib::Enum)]
#[enum_type(name = "SortType")]
pub enum SortType {
    #[default]
    Unset,
    Asc,
    Desc,
}

impl Display for SortType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match &self {
            SortType::Asc => "Asc",
            SortType::Desc => "Desc",
            SortType::Unset => "",
        };
        write!(f, "{s}")
    }
}

impl From<SortType> for Option<gtk::SortType> {
    fn from(val: SortType) -> Self {
        match val {
            SortType::Unset => None,
            SortType::Asc => Some(gtk::SortType::Ascending),
            SortType::Desc => Some(gtk::SortType::Descending),
        }
    }
}

impl From<gtk::SortType> for SortType {
    fn from(value: gtk::SortType) -> Self {
        match value {
            gtk::SortType::Ascending => SortType::Asc,
            gtk::SortType::Descending => SortType::Desc,
            _ => SortType::Unset,
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct MyConfigOrder {
    pub id: u32,
    pub order: IndexSet<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct MyConfig {
    pub orders: Option<Vec<MyConfigOrder>>,
    #[serde(rename = "column")]
    pub columns: Vec<UnitColumn>,
}

impl MyConfig {
    pub fn is_empty(&self) -> bool {
        self.columns.is_empty()
    }
}

pub fn save_column_config(
    columns: Option<&gio::ListModel>,
    data: &IndexMap<String, UnitPropertySelection>,
    view: UnitCuratedList,
    primary_sort_id: Option<glib::GString>,
    sort_type: gtk::SortType,
    id: u32,
) {
    let ids = order_columns(columns, data, primary_sort_id, sort_type);

    let data_list: IndexMap<String, UnitColumn> = data
        .iter()
        .map(|(key, up)| (key.clone(), UnitColumn::from(up)))
        .collect();

    runtime().spawn(save_config(view, data_list, ids, id));
}

async fn save_config(
    view: UnitCuratedList,
    current_columns: IndexMap<String, UnitColumn>,
    ids: IndexSet<String>,
    config_id: u32,
) {
    let config = if let Some(loaded) = load_column_config(view).await
        && let Some(mut orders) = loaded.orders
    {
        if let Some(a) = orders.iter_mut().find(|c| c.id == config_id) {
            a.order = ids;
        } else {
            let order = MyConfigOrder {
                id: config_id,
                order: ids,
            };
            orders.push(order);
        }

        //add the current loaded col definission
        let mut loaded_col: Vec<_> = loaded
            .columns
            .into_iter()
            .filter(|col| !current_columns.contains_key(&col.id))
            .collect();

        let mut columns: Vec<_> = current_columns.into_values().collect();
        columns.append(&mut loaded_col);

        MyConfig {
            columns,
            orders: Some(orders),
        }
    } else {
        let order = MyConfigOrder {
            id: config_id,
            order: ids,
        };

        MyConfig {
            columns: current_columns.into_values().collect(),
            orders: Some(vec![order]),
        }
    };

    let sysd_manager_config_dir = get_sysd_manager_config_dir();
    if let Err(e) = fs::create_dir_all(&sysd_manager_config_dir).await {
        error!(
            "Failed to create config directory {:?}: {}",
            sysd_manager_config_dir, e
        );
        return;
    }
    let file_name = file_name(view);
    let config_path = sysd_manager_config_dir.join(file_name);

    if let Err(e) = save_to_toml_file(&config, &config_path).await {
        error!(
            "Failed to save column config to TOML file: {:?} {:?}",
            config_path, e
        );
    } else {
        info!("Column config saved to {:?}", config_path);
    }
}

fn file_name(view: UnitCuratedList) -> String {
    match view {
        UnitCuratedList::Custom => UNIT_COLUMNS.to_owned(),
        _ => format!("{}_{}", view.id(), UNIT_COLUMNS),
    }
}

pub fn order_columns(
    columns: Option<&gio::ListModel>,
    data: &IndexMap<String, UnitPropertySelection>,
    primary_sort_id: Option<glib::GString>,
    sort_type: gtk::SortType,
) -> IndexSet<String> {
    let Some(columns) = columns else {
        return IndexSet::new();
    };

    let columns_ids: IndexSet<_> = columns
        .iter::<gtk::ColumnViewColumn>()
        .filter_map(|result| result.inspect_err(|err| warn!("Error: {err:?}")).ok())
        .filter_map(|column| column.id().map(|s| s.to_string()))
        .collect();

    //Set the sort
    if let Some(ref primary_sort_id) = primary_sort_id {
        for (id, property_display) in data {
            if id.as_str() == primary_sort_id.as_str() {
                let sort_type = SortType::from(sort_type);
                property_display.set_sort(sort_type);
            } else {
                property_display.set_sort(SortType::Unset);
            }
        }
    }

    columns_ids
}

pub(crate) fn get_sysd_manager_config_dir() -> std::path::PathBuf {
    let xdg_config_home = get_xdg_config_home();

    Path::new(&xdg_config_home).join("sysd-manager")
}

fn get_xdg_config_home() -> String {
    env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| {
        let home = env::var("HOME").unwrap_or_else(|_| ".".to_string());
        format!("{}/.config", home)
    })
}

pub(crate) async fn save_to_toml_file<T>(data: &T, path: &Path) -> std::io::Result<()>
where
    T: Serialize,
{
    let toml_str = toml::to_string_pretty(data).expect("Failed to serialize data to TOML");
    let mut file = fs::File::create(path).await?;
    file.write_all(toml_str.as_bytes()).await?;
    Ok(())
}

pub async fn load_column_config(view: UnitCuratedList) -> Option<MyConfig> {
    let sysd_manager_config_dir = get_sysd_manager_config_dir();

    if !sysd_manager_config_dir.exists() {
        info!(
            "Config directory {:?} does not exist. Using default configuration.",
            sysd_manager_config_dir
        );
        return None;
    }

    let file_name = file_name(view);

    let config_path = sysd_manager_config_dir.join(file_name);

    if !config_path.exists() {
        info!(
            "Config file {:?} does not exist. Using default configuration.",
            config_path
        );
        return None;
    }

    match fs::read_to_string(&config_path).await {
        Ok(toml_str) => match toml::from_str::<MyConfig>(&toml_str) {
            Ok(config) => {
                if config.is_empty() {
                    warn!("Loaded config is empty, FALLBACK on default");
                    None
                } else {
                    Some(config)
                }
            }
            Err(e) => {
                error!("Failed to parse TOML from {:?}: {}", config_path, e);
                None
            }
        },
        Err(e) => {
            error!("Failed to read config file {:?}: {}", config_path, e);
            None
        }
    }
}

pub(crate) async fn delete_column_config(view: UnitCuratedList) {
    let sysd_manager_config_dir = get_sysd_manager_config_dir();

    if !sysd_manager_config_dir.exists() {
        info!(
            "Config directory {:?} does not exist. Using default configuration.",
            sysd_manager_config_dir
        );
        return;
    }

    let file_name = file_name(view);

    let config_path = sysd_manager_config_dir.join(file_name);

    if let Err(err) = fs::remove_file(&config_path).await {
        warn!(
            "Delete file {:?} Error {:?}",
            config_path.to_string_lossy(),
            err
        );
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_save_array_of_structs_to_toml() {
        let data_list = vec![
            UnitColumn {
                id: "alpha".to_string(),
                title: Some("Alpha Title".to_string()),
                fixed_width: 1,
                expands: true,
                resizable: false,
                visible: true,
                ..Default::default()
            },
            UnitColumn {
                id: "beta".to_string(),
                title: Some("Beta Title".to_string()),
                fixed_width: 2,
                expands: false,
                resizable: true,
                visible: false,
                ..Default::default()
            },
            UnitColumn {
                id: "gamma".to_string(),
                title: Some("Gamma Title".to_string()),
                fixed_width: 3,
                expands: true,
                resizable: true,
                visible: true,
                prop_type: Some("i".to_string()),
                sort: Some(SortType::Asc),
            },
            UnitColumn {
                id: "".to_string(),
                title: None,
                fixed_width: 3,
                expands: true,
                resizable: true,
                visible: true,
                ..Default::default()
            },
        ];

        let config = MyConfig {
            columns: data_list,
            orders: None,
        };

        let toml_str = toml::to_string_pretty(&config).expect("Failed to serialize array to TOML");

        println!("{}", toml_str);

        // Check that each struct appears as a TOML table
        assert!(toml_str.contains("id = \"alpha\""));
        assert!(toml_str.contains("id = \"beta\""));
        assert!(toml_str.contains("title = \"Gamma Title\""));
        assert!(toml_str.matches("[").count() >= 4); // At least 4 tables
    }

    #[test]
    fn test_toml_save_empty() {
        let data_list = vec![];

        let config = MyConfig {
            columns: data_list,
            orders: None,
        };

        let toml_str = toml::to_string_pretty(&config).expect("Failed to serialize array to TOML");

        println!("{}", toml_str);
    }

    #[test]
    fn test_load_multiple_structs_from_toml_file() {
        let toml_content = r#"
            [[column]]
            id = "alpha"
            title = "Alpha Title"
            fixed_width = 1
            expands = true
            resizable = false
            visible = true

            [[column]]
            id = "beta"
            title = "Beta Title"
            width = 2
            expands = false
            resizable = true
            visible = false

            [[column]]
            id = "gamma"
            title = "Gamma Title"
            width = 3
            expands = true
            resizable = true
            visible = true

            [[column]]
            expands = true
            resizable = true
            visible = true
            type = "i"
        "#;

        let config: MyConfig = toml::from_str(toml_content).expect("Failed to parse TOML");

        assert!(config.columns.len() >= 4);
        assert_eq!(config.columns[0].id.as_str(), "alpha");
        assert_eq!(config.columns[1].fixed_width, 2);
        assert!(config.columns[2].visible);
        assert_eq!(config.columns[3].title, None);
        assert_eq!(config.columns[3].fixed_width, -1);
        assert_eq!(config.columns[3].prop_type, Some("i".to_string()));
    }

    #[test]
    fn test_iter() {
        let data = ['a', 'b', 'c', 'd'];

        for (sub_index, ps) in data[2..].iter().enumerate() {
            println!("{sub_index} {ps}")
        }
    }
}