sysd-manager 2.23.0

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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
use super::*;
use crate::{
    upgrade, upgrade_opt,
    widget::creator::{
        self, CreateUnitErr, UnitCreateType,
        creator_page_service::standard_output::{StandardOutput, output_file_descriptor},
        mydropdown::MyDropDown,
        suggestion::SuggestionRow,
        unit_file::{STANDARD_ERROR, STANDARD_OUTPUT, UnitFileData},
    },
};
use adw::{
    prelude::{ActionRowExt, ComboRowExt, PreferencesGroupExt},
    subclass::prelude::*,
};
use gettextrs::{gettext, pgettext};
use gtk::{StringObject, glib, prelude::*};
use indexmap::{IndexMap, map::Entry};
use itertools::{EitherOrBoth, Itertools};
use regex::Regex;
use std::{
    cell::{Cell, OnceCell, RefCell},
    fs,
    os::unix::fs::PermissionsExt,
    path::Path,
};
use tracing::{info, warn};

const VALIDATE_CPU_QUOTA_REGEX: &str = r"\d+%";
const VALIDATE_MEMORY_HIGH_REGEX: &str = r"^[1-9][0-9]*[%KMGT]?$";

#[derive(Default, gtk::CompositeTemplate, glib::Properties)]
#[template(resource = "/io/github/plrigaux/sysd-manager/creator_page_service.ui")]
#[properties(wrapper_type = super::CreatorPageService)]
pub struct CreatorPageServiceImp {
    #[property(get, set, default)]
    creation_type: Cell<UnitCreateType>,

    #[template_child]
    description_entry: TemplateChild<adw::EntryRow>,

    #[template_child]
    exec_start_entry: TemplateChild<adw::EntryRow>,

    #[template_child]
    environment_entry: TemplateChild<adw::EntryRow>,

    #[template_child]
    working_directory_entry: TemplateChild<adw::EntryRow>,

    #[template_child]
    restart_policy_combo: TemplateChild<adw::ComboRow>,

    #[template_child]
    unit_wants: TemplateChild<MyDropDown>,

    #[template_child]
    unit_after: TemplateChild<MyDropDown>,

    #[template_child]
    service_group: TemplateChild<adw::PreferencesGroup>,

    #[template_child]
    memory_high_entry: TemplateChild<adw::EntryRow>,

    #[template_child]
    cpu_quota_entry: TemplateChild<adw::EntryRow>,

    #[template_child]
    user_combo: TemplateChild<adw::ComboRow>,

    #[template_child]
    group_combo: TemplateChild<adw::ComboRow>,

    #[template_child]
    standard_output_entry: TemplateChild<SuggestionRow>,

    #[template_child]
    standard_error_entry: TemplateChild<SuggestionRow>,

    #[template_child]
    resource_control_group: TemplateChild<adw::PreferencesGroup>,

    #[template_child]
    wanted_by_entry: TemplateChild<SuggestionRow>,

    #[template_child]
    install_group: TemplateChild<adw::PreferencesGroup>,

    pub(super) window: OnceCell<WeakRef<UnitCreatorWindow>>,

    pub(super) file_data: RefCell<UnitFileData>,

    pub(super) widget_track: RefCell<IndexMap<String, Vec<gtk::Widget>>>,

    validate_cpu_quota_regex: OnceCell<Regex>,
    validate_memory_high_regex: OnceCell<Regex>,
}

#[glib::object_subclass]
impl ObjectSubclass for CreatorPageServiceImp {
    const NAME: &'static str = "CreatorPageService";
    type Type = CreatorPageService;
    type ParentType = adw::NavigationPage;

    fn class_init(klass: &mut Self::Class) {
        // The layout manager determines how child widgets are laid out.
        SuggestionRow::default();
        klass.bind_template();
        klass.bind_template_callbacks();
    }

    fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
        obj.init_template();
    }
}

#[glib::derived_properties]
impl ObjectImpl for CreatorPageServiceImp {
    fn constructed(&self) {
        self.parent_constructed();

        let event_focus = gtk::EventControllerFocus::new();
        event_focus.connect_leave(|event| {
            if let Some(entry) = event.widget().and_downcast_ref::<adw::EntryRow>() {
                CreatorPageServiceImp::validate_entry_exec_start(entry);
            }
        });
        self.exec_start_entry.add_controller(event_focus);

        let vec = vec![
            "",
            "always",
            "on-success",
            "on-failure",
            "on-abnormal",
            "on-abort",
            "on-watchdog",
        ];

        let model = gtk::StringList::new(&vec);

        self.restart_policy_combo.set_model(Some(&model));

        self.description_entry
            .connect_has_focus_notify(|entry| entry.select_region(0, -1));
        self.description_entry
            .connect_focus_on_click_notify(|entry| entry.select_region(0, -1));
        self.exec_start_entry
            .connect_has_focus_notify(|entry| entry.select_region(0, -1));
        self.exec_start_entry
            .connect_focus_on_click_notify(|entry| entry.select_region(0, -1));
        self.working_directory_entry
            .connect_has_focus_notify(|entry| entry.select_region(0, -1));
        self.working_directory_entry
            .connect_focus_on_click_notify(|entry| entry.select_region(0, -1));

        self.add_track(ENVIRONMENT, &self.environment_entry.get());

        let users = unsafe { uzers::all_users() };

        let mut users: Vec<_> = users
            .map(|u| u.name().to_string_lossy().into_owned())
            .collect();

        users.push("".into());
        users.sort();

        let model = gtk::StringList::new(&[]);
        for user in users {
            model.append(&user);
        }
        self.user_combo.set_model(Some(&model));

        let groups = unsafe { uzers::all_groups() };

        let mut groups: Vec<_> = groups
            .map(|u| u.name().to_string_lossy().into_owned())
            .collect();

        groups.push("".into());
        groups.sort();

        let model = gtk::StringList::new(&[]);
        for group in groups {
            model.append(&group);
        }
        self.group_combo.set_model(Some(&model));

        let this = self.obj().clone();
        let event_focus = gtk::EventControllerFocus::new();
        event_focus.connect_leave(move |event| {
            if let Some(entry) = event.widget().and_downcast_ref::<adw::EntryRow>() {
                CreatorPageServiceImp::validate_cpu_quota(this.imp(), entry);
            }
        });

        self.cpu_quota_entry.add_controller(event_focus);

        let this = self.obj().clone();
        let event_focus = gtk::EventControllerFocus::new();
        event_focus.connect_leave(move |event| {
            if let Some(entry) = event.widget().and_downcast_ref::<adw::EntryRow>() {
                CreatorPageServiceImp::validate_memory_high(this.imp(), entry);
            }
        });

        self.memory_high_entry.add_controller(event_focus);

        let this = self.obj().clone();
        let event_focus = gtk::EventControllerFocus::new();
        event_focus.connect_leave(move |event| {
            if let Some(entry) = event.widget().and_downcast_ref::<adw::EntryRow>() {
                this.imp().validate_working_directory(entry);
            }
        });

        self.working_directory_entry.add_controller(event_focus);

        let model = standard_output::outputs();
        self.standard_output_entry.set_model(Some(&model));
        self.standard_error_entry.set_model(Some(&model));

        let factory = gtk::SignalListItemFactory::new();
        factory.connect_setup(move |_factory, item| {
            let item = item.downcast_ref::<gtk::ListItem>().unwrap();
            let row = gtk::Label::builder().xalign(0.0).use_markup(true).build();
            item.set_child(Some(&row));
        });

        factory.connect_bind(move |_factory, item| {
            let item = item.downcast_ref::<gtk::ListItem>().unwrap();
            let data = item
                .item()
                .and_downcast::<standard_output::StandardOutput>()
                .unwrap();

            let child = item.child().and_downcast::<gtk::Label>().unwrap();

            child.set_label(&data.label());
        });

        self.standard_output_entry.set_factory(Some(&factory));
        self.standard_error_entry.set_factory(Some(&factory));

        let expression = gtk::PropertyExpression::new(
            StandardOutput::static_type(),
            None::<gtk::Expression>,
            "text",
        );

        self.standard_output_entry
            .set_expression(expression.clone());
        self.standard_error_entry.set_expression(expression);

        let event_focus = gtk::EventControllerFocus::new();
        let this = self.obj().clone();
        event_focus.connect_leave(move |event| {
            if let Some(entry) = event.widget().and_downcast_ref::<adw::EntryRow>() {
                CreatorPageServiceImp::validate_standard_output_and_error(
                    this.imp(),
                    entry,
                    STANDARD_OUTPUT,
                );
            }
        });

        self.standard_output_entry.add_controller(event_focus); //Can't clone controller
        let event_focus = gtk::EventControllerFocus::new();
        let this = self.obj().clone();
        event_focus.connect_leave(move |event| {
            if let Some(entry) = event.widget().and_downcast_ref::<adw::EntryRow>() {
                CreatorPageServiceImp::validate_standard_output_and_error(
                    this.imp(),
                    entry,
                    STANDARD_ERROR,
                );
            }
        });
        self.standard_error_entry.add_controller(event_focus);
    }
}

impl CreatorPageServiceImp {
    fn validate_entry_exec_start(entry: &adw::EntryRow) {
        let text = entry.text();

        let name_err = if text.is_empty() {
            CreateUnitErr::NoErr
        } else {
            let path = Path::new(&text);

            if !path.exists() {
                CreateUnitErr::FileNotExits
            } else if !path.is_file() {
                CreateUnitErr::NotFile
            } else if !is_executable(path) {
                CreateUnitErr::NotExecutable
            } else if !path.is_absolute() {
                CreateUnitErr::NotAbsolute
            } else {
                CreateUnitErr::NoErr
            }
        };

        CreateUnitErr::apply_validation_result(entry, &name_err, "ExecStart");
    }

    fn validate_working_directory(&self, entry: &adw::EntryRow) {
        let text = entry.text();

        let name_err = match creator::get_file_path(text.as_str()) {
            Ok(text) => {
                if text.is_empty() {
                    CreateUnitErr::NoErr
                } else {
                    let path = Path::new(text);

                    if !path.exists() {
                        CreateUnitErr::FileNotExits
                    } else if !path.is_dir() {
                        CreateUnitErr::NotDir
                    } else if !is_executable(path) {
                        CreateUnitErr::NotExecutable
                    } else if !path.is_absolute() {
                        CreateUnitErr::NotAbsolute
                    } else {
                        CreateUnitErr::NoErr
                    }
                }
            }

            Err(err) => err,
        };
        CreateUnitErr::apply_validation_result(entry, &name_err, "WorkingDirectory");
    }

    fn cpu_quota_regex(&self) -> &Regex {
        self.validate_cpu_quota_regex
            .get_or_init(|| Regex::new(VALIDATE_CPU_QUOTA_REGEX).unwrap())
    }

    fn validate_cpu_quota(&self, entry: &adw::EntryRow) {
        let text = entry.text();
        let cpuquota = "CPUQuota";
        info!("Validating {:?} {:?}", cpuquota, text);

        let name_err = if text.is_empty() {
            CreateUnitErr::NoErr
        } else if !self.cpu_quota_regex().is_match(text.as_str()) {
            CreateUnitErr::Malformed
        } else {
            CreateUnitErr::NoErr
        };

        CreateUnitErr::apply_validation_result(entry, &name_err, cpuquota);
    }

    fn validate_standard_output_and_error(&self, entry: &adw::EntryRow, attribute: &str) {
        let text = entry.text();
        let text = text.as_str();
        info!("Validating {:?} {:?}", attribute, text);

        let name_err = if text.is_empty() {
            CreateUnitErr::NoErr
        } else {
            let mut name_err = CreateUnitErr::Malformed;
            for a in output_file_descriptor() {
                if a == text
                    && !matches!(
                        text,
                        "file:path" | "append:path" | "truncate:path" | "fd:name"
                    )
                {
                    name_err = CreateUnitErr::NoErr;
                    break;
                }
            }

            if CreateUnitErr::Malformed == name_err {
                const FILE: &str = "file:";
                const APPEND: &str = "append:";
                const TRUNCATE: &str = "truncate:";
                if let Some(path) = text.strip_prefix(FILE) {
                    name_err = Self::validate_path(path);
                } else if let Some(path) = text.strip_prefix(APPEND) {
                    name_err = Self::validate_path(path);
                } else if let Some(path) = text.strip_prefix(TRUNCATE) {
                    name_err = Self::validate_path(path);
                } else if text.starts_with("fd:") {
                    name_err = CreateUnitErr::NoErr;
                }
            }
            name_err
        };

        CreateUnitErr::apply_validation_result(entry, &name_err, attribute);
    }

    fn validate_path(path: &str) -> CreateUnitErr {
        let path = path.trim_ascii();

        if path.is_empty() {
            CreateUnitErr::NoPath
        } else {
            let path = Path::new(&path);

            if !path.exists() {
                CreateUnitErr::FileNotExits
            } else if !path.is_absolute() {
                CreateUnitErr::NotAbsolute
            } else {
                CreateUnitErr::NoErr
            }
        }
    }

    fn get_memory_high_regex(&self) -> &Regex {
        self.validate_memory_high_regex
            .get_or_init(|| Regex::new(VALIDATE_MEMORY_HIGH_REGEX).unwrap())
    }

    fn validate_memory_high(&self, entry: &adw::EntryRow) {
        let text = entry.text();
        let cpuquota = "MemoryHigh";
        info!("Validating {:?} {:?}", cpuquota, text);

        let name_err = if text.is_empty() {
            CreateUnitErr::NoErr
        } else if !self.get_memory_high_regex().is_match(text.as_str()) {
            CreateUnitErr::Malformed
        } else {
            CreateUnitErr::NoErr
        };

        CreateUnitErr::apply_validation_result(entry, &name_err, cpuquota);
    }

    fn add_track(&self, param: &str, widget: &impl IsA<gtk::Widget>) {
        match self.widget_track.borrow_mut().entry(param.to_owned()) {
            Entry::Occupied(mut occupied_entry) => {
                occupied_entry.get_mut().push(widget.as_ref().clone())
            }
            Entry::Vacant(vacant_entry) => {
                vacant_entry.insert_entry(vec![widget.as_ref().clone()]);
            }
        };
    }

    fn remove_track(&self, param: &str, widget: &impl IsA<gtk::Widget>) {
        if let Some(v) = self.widget_track.borrow_mut().get_mut(param) {
            for (i, w) in v.iter().enumerate() {
                if w == widget {
                    v.remove(i);
                    break;
                }
            }
        };
    }

    pub(crate) fn update_from_unit_info(&self) {
        let window = upgrade_opt!(self.window.get());

        let model = window.imp().get_trigger_units_model();

        self.unit_wants.set_model(Some(&model));
        self.unit_after.set_model(Some(&model));
    }

    pub(super) fn advanced_mode(&self, advanced: bool) {
        self.unit_wants.set_visible(advanced);
        self.unit_after.set_visible(advanced);
        self.environment_entry.set_visible(advanced);
        self.working_directory_entry.set_visible(advanced);
        self.memory_high_entry.set_visible(advanced);
        self.cpu_quota_entry.set_visible(advanced);
        self.resource_control_group.set_visible(advanced);
        self.install_group.set_visible(advanced);
    }
}

fn is_executable(path: &Path) -> bool {
    let Ok(metadata) = fs::metadata(path) else {
        return false;
    };

    metadata.permissions().mode() & 0o111 != 0
}

#[gtk::template_callbacks]
impl CreatorPageServiceImp {
    #[template_callback]
    fn working_directory_search_dialog_clicked(&self, _button: gtk::Button) {
        let file_dialog = gtk::FileDialog::builder()
            .title("Select a working directory")
            .accept_label("Select")
            .build();

        let create_service_page = self.obj().clone();

        let text = self.working_directory_entry.text();
        let text = creator::get_file_path(&text).unwrap_or_default();
        if text.is_empty() {
            creator::set_initial_folder(&file_dialog);
        } else {
            let path = Path::new(text);
            if path.exists() {
                let file = gio::File::for_path(path);
                file_dialog.set_initial_file(Some(&file));
            } else {
                println!("not ex {text}");
                creator::set_initial_folder(&file_dialog);
            }
        }

        let win = self.window.get().and_then(|w| w.upgrade());
        let win = win.and_upcast_ref::<gtk::Window>();

        file_dialog.select_folder(win, None::<&gio::Cancellable>, move |result| match result {
            Ok(file) => {
                if let Some(path) = file.path() {
                    let file_path_str = path.display().to_string();
                    create_service_page
                        .imp()
                        .working_directory_entry
                        .set_text(&file_path_str);
                }
            }
            Err(e) => warn!("Unit File Selection Error {e:?}"),
        });
    }

    #[template_callback]
    fn exec_start_dialog_clicked(&self, _button: gtk::Button) {
        let file_dialog = gtk::FileDialog::builder()
            .title(pgettext("unit creation", "Select executable"))
            .accept_label(gettext("Select"))
            .build();

        let create_service_page = self.obj().clone();

        let text = self.exec_start_entry.text();
        let text = creator::get_file_path(&text).unwrap_or_default();
        if text.is_empty() {
            creator::set_initial_folder(&file_dialog);
        } else {
            let path = Path::new(text);
            if path.exists() {
                let file = gio::File::for_path(path);
                if path.is_dir() {
                    // println!("dir {:?} ", path);
                    file_dialog.set_initial_folder(Some(&file));
                } else if path.is_file() {
                    // println!("file {:?} ", path);
                    file_dialog.set_initial_file(Some(&file));
                }
            } else {
                warn!("not exist {}", path.display());
                creator::set_initial_folder(&file_dialog);
            }
        }

        let win = self.window.get().and_then(|w| w.upgrade());
        let win = win.and_upcast_ref::<gtk::Window>();

        file_dialog.open(win, None::<&gio::Cancellable>, move |result| match result {
            Ok(file) => {
                if let Some(path) = file.path() {
                    let mut file_path_str = path.display().to_string();
                    escape(&mut file_path_str);
                    create_service_page
                        .imp()
                        .exec_start_entry
                        .set_text(&file_path_str);
                }
            }
            Err(e) => warn!("Unit File Selection Error {e:?}"),
        });
    }

    #[template_callback]
    fn environment_add_clicked(&self, _button: gtk::Button) {
        self.add_entry(ENVIRONMENT);
    }

    fn last_of(&self, id: &str) -> Option<gtk::Widget> {
        if let Some(w_list) = self.widget_track.borrow_mut().get(id)
            && let Some(w) = w_list.last()
        {
            Some(w.clone())
        } else {
            match id {
                ENVIRONMENT => Some(self.environment_entry.get().into()),
                _ => None,
            }
        }
    }

    fn add_entry(&self, id: &str) -> adw::EntryRow {
        let entry = adw::EntryRow::builder().title(id).build();

        let mut vec = Vec::new();
        let mut env_idx = 0;

        let last_of = self.last_of(id);
        for i in 0..10_000 {
            let Some(widget) = self.service_group.row(i) else {
                break;
            };

            if Some(&widget) == last_of.as_ref() {
                env_idx = i;
            }

            vec.push(widget);
        }

        //Remove next widget for inserting the new one
        for (i, w) in vec.iter().enumerate().rev() {
            if env_idx == i as u32 {
                break;
            } else {
                self.service_group.remove(w);
            }
        }

        //Insert new
        self.service_group.add(&entry);
        self.add_track(id, &entry);

        //Add other widget
        for w in vec.iter().skip(env_idx as usize + 1) {
            self.service_group.add(w);
        }

        entry
    }

    fn remove_entry(&self, id: &str, w: &gtk::Widget) {
        self.service_group.remove(w);
        self.remove_track(id, w);
    }
}

impl CreatorPageServiceImp {
    pub(super) fn update_view(&self, page: &UnitFileCreatorPage) {
        self.fill_data();
        let data = self.file_data.borrow();
        page.update_view(&data);
    }

    pub(super) fn file_content(&self) -> String {
        self.fill_data();
        self.file_data.borrow().to_file()
    }

    fn fill_data(&self) {
        let mut file_data = self.file_data.borrow_mut();

        file_data.set_description(self.description_entry.text());

        let environments = self.widget_track.borrow().get(ENVIRONMENT).map(|v| {
            v.iter()
                .filter_map(|widget| {
                    widget
                        .downcast_ref::<adw::EntryRow>()
                        .map(|entry| entry.text())
                })
                .collect::<Vec<glib::GString>>()
        });
        file_data.set_environment(environments.as_deref());
        file_data.set_exec_start(self.exec_start_entry.text());
        file_data.set_user(self.user_combo.subtitle());
        file_data.set_group(self.group_combo.subtitle());
        file_data.set_working_directory(self.working_directory_entry.text());
        file_data.set_after(self.unit_after.subtitle());
        file_data.set_wants(self.unit_wants.subtitle());
        file_data.set_cpu_quota(self.cpu_quota_entry.text());
        file_data.set_memory_high(self.memory_high_entry.text());
        file_data.set_standard_output(self.standard_output_entry.text());
        file_data.set_standard_error(self.standard_error_entry.text());
        file_data.set_wanted_by(self.wanted_by_entry.text());

        file_data.sort();
    }

    pub fn update_from_file_content(&self, content: &str) {
        let Some(data) = UnitFileData::from_content(content) else {
            return;
        };

        self.description_entry.set_text(data.description());
        self.unit_after.set_subtitle(data.after());
        self.unit_wants.set_subtitle(data.wants());

        if let Some(env) = data.environment() {
            let mut to_remove = Vec::new();
            let mut to_add = Vec::new();
            {
                let w_track = self.widget_track.borrow();
                let w_it = w_track
                    .get(ENVIRONMENT)
                    .map(|v| v.iter())
                    .unwrap_or_default();
                for (i, v) in env.iter().zip_longest(w_it).enumerate() {
                    match v {
                        EitherOrBoth::Both(s, w) => {
                            let Some(entry) = w.downcast_ref::<adw::EntryRow>() else {
                                warn!("bad downcast");
                                continue;
                            };
                            entry.set_text(s.as_str());
                        }
                        EitherOrBoth::Left(s) => {
                            to_add.push(s);
                        }
                        EitherOrBoth::Right(w) => {
                            if i != 0 {
                                to_remove.push(w.clone())
                            } else {
                                self.environment_entry.set_text("");
                            }
                        }
                    };
                }
            }
            for s in to_add {
                self.add_entry(ENVIRONMENT).set_text(s.as_str());
            }
            for w in to_remove {
                self.remove_entry(ENVIRONMENT, &w);
            }
        } else {
            self.environment_entry.set_text("");
        }

        self.exec_start_entry.set_text(data.exec_start());
        self.working_directory_entry
            .set_text(data.working_directory());

        self.cpu_quota_entry.set_text(data.cpu_quota());
        self.memory_high_entry.set_text(data.memory_high());

        self.user_combo.set_subtitle(data.user());
        self.group_combo.set_subtitle(data.group());

        let restart = data.restart();
        let mut position_sel = 0;
        if !restart.is_empty()
            && let Some(list_model) = self.restart_policy_combo.model()
        {
            //TODO make a map if too slow
            for position in 0..list_model.n_items() {
                if let Some(string_item) = list_model
                    .item(position)
                    .and_downcast_ref::<StringObject>()
                    .map(|s| s.string())
                    && string_item.as_str() == restart
                {
                    position_sel = position;
                    break;
                }
            }
        }
        self.restart_policy_combo.set_selected(position_sel);

        self.standard_output_entry.set_text2(data.standard_output());
        self.standard_error_entry.set_text2(data.standard_error());
        self.wanted_by_entry.set_text(data.wanted_by());

        self.file_data.replace(data);
    }
}

impl WidgetImpl for CreatorPageServiceImp {}

impl NavigationPageImpl for CreatorPageServiceImp {}

fn escape(file_path: &mut String) {
    if file_path.contains(char::is_whitespace) {
        file_path.insert(0, '"');
        file_path.push('"');
    }
}

#[cfg(test)]
mod tests {
    use test_base::init_logs;

    use super::*;

    #[test]
    fn test_cpu_quota() {
        init_logs();
        let re = Regex::new(VALIDATE_CPU_QUOTA_REGEX).unwrap();

        assert!(re.is_match("50%"));
        assert!(!re.is_match("50"));
        assert!(re.is_match("33.33%"));
    }

    #[test]
    fn test_memory_hight() {
        init_logs();
        let re = Regex::new(VALIDATE_MEMORY_HIGH_REGEX).unwrap();

        assert!(re.is_match("50K"));
        assert!(!re.is_match("50Kb"));
        assert!(re.is_match("50%"));
        assert!(re.is_match("50"));
        assert!(!re.is_match("33.22"));
    }
}