sysd-manager 2.24.5

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
//test

use glib::{object::IsA, subclass::types::ObjectSubclassIsExt};
use tracing::warn;

glib::wrapper! {
    pub struct SuggestionRow(ObjectSubclass<imp::SuggestionRowImp>)
    @extends adw::EntryRow, adw::PreferencesRow, gtk::ListBoxRow, gtk::Widget,
    @implements gtk::Accessible, gtk::Actionable,  gtk::Buildable,  gtk::ConstraintTarget, gtk::Editable ;
}

impl SuggestionRow {
    pub fn new() -> Self {
        let obj: SuggestionRow = glib::Object::new();
        obj
    }

    pub fn set_model(&self, model: Option<&impl IsA<gio::ListModel>>) {
        self.imp().set_model(model)
    }

    pub fn set_factory(&self, factory: Option<&impl IsA<gtk::ListItemFactory>>) {
        self.imp().set_factory(factory);
    }

    pub fn set_text2(&self, text: &str) {
        self.imp().set_text2(text)
    }

    pub fn set_expression(&self, expression: gtk::PropertyExpression) {
        let _ = self
            .imp()
            .expression
            .set(expression)
            .inspect_err(|_| warn!("Expression already set!"));
    }
}

impl Default for SuggestionRow {
    fn default() -> Self {
        SuggestionRow::new()
    }
}

mod imp {
    use adw::subclass::prelude::*;
    use glib::{
        object::IsA,
        subclass::{object::ObjectImpl, types::ObjectSubclass},
    };
    use gtk::{
        gdk::{self, Key},
        prelude::*,
    };
    use std::cell::{Cell, OnceCell, RefCell};
    use tracing::{debug, error, info};

    use crate::{upgrade, widget::find_child_by_name};

    const PAGE_STEP: u32 = 10;

    #[derive(Default, gtk::CompositeTemplate, glib::Properties)]
    #[properties(wrapper_type = super::SuggestionRow)]
    #[template(resource = "/io/github/plrigaux/sysd-manager/suggestion_entry.ui")]
    // #[properties(wrapper_type = super::SDDropdown)]
    pub struct SuggestionRowImp {
        drop_list_view: OnceCell<gtk::ListView>,

        popover: OnceCell<gtk::Popover>,

        #[template_child]
        arrow_down_image: TemplateChild<gtk::Image>,

        // #[property(get, set)]
        popup_visible: Cell<bool>,
        #[property(get=Self::popup_height, set=Self::set_popup_height, name = "popup-height", type=i32) ]
        #[property(get=Self::popup_width, set=Self::set_popup_width, name = "popup-width", type=i32) ]
        filter_list_model: OnceCell<gtk::FilterListModel>,

        single_selection: OnceCell<gtk::SingleSelection>,

        search_text: RefCell<String>,

        change_id: OnceCell<glib::SignalHandlerId>,

        custom_filter: OnceCell<gtk::CustomFilter>,

        pub(super) expression: OnceCell<gtk::PropertyExpression>,
    }

    impl SuggestionRowImp {
        pub fn set_model(&self, model: Option<&impl IsA<gio::ListModel>>) {
            if let Some(fl) = self.filter_list_model.get() {
                fl.set_model(model);
            }
        }

        fn create_filter(&self) -> gtk::CustomFilter {
            let this = self.downgrade();

            gtk::CustomFilter::new(move |object| {
                let this = upgrade!(this, false);
                let text_gs = this.obj().text();
                if text_gs.is_empty() {
                    return true;
                }

                let Some(expression) = this.expression.get() else {
                    return true;
                };

                let Some(value) = expression.evaluate(Some(object)).and_then(|value| {
                    value
                        .get::<String>()
                        .inspect_err(|err| error!("bad convertion {:?}", err))
                        .ok()
                }) else {
                    return true;
                };

                let text = text_gs.as_str();

                //if an upper case --> filter
                if text_gs.chars().any(|c| c.is_ascii_uppercase()) {
                    value.contains(text)
                } else {
                    value.to_ascii_lowercase().contains(text)
                }
            })
        }

        pub fn set_factory(&self, factory: Option<&impl IsA<gtk::ListItemFactory>>) {
            self.drop_list_view().set_factory(factory);
        }

        fn set_popup_visible(&self, visible: bool) {
            if visible {
                if let Some(single_selection) = self.single_selection.get() {
                    single_selection.set_selected(gtk::INVALID_LIST_POSITION);
                }
                self.popover().popup();
            } else {
                self.popover().popdown();
            }

            // Set the porperty indicator
            self.popup_visible.set(visible);
        }

        fn drop_list_view(&self) -> &gtk::ListView {
            self.drop_list_view
                .get_or_init(|| gtk::ListView::builder().build())
        }

        fn popover(&self) -> &gtk::Popover {
            let this_weak = self.obj().downgrade();
            self.popover.get_or_init(|| {
                let pop = gtk::Popover::builder()
                    .css_classes(["menu"])
                    .autohide(false) //for not loosing the focus
                    // .autohide(true)
                    .has_arrow(true)
                    .height_request(300)
                    .width_request(200)
                    .position(gtk::PositionType::Bottom)
                    // .can_focus(false)
                    .build();

                let this = upgrade!(this_weak, pop);
                pop.set_parent(&this.imp().arrow_down_image.get());

                let scroll = gtk::ScrolledWindow::new();
                scroll.set_child(Some(this.imp().drop_list_view()));
                pop.set_child(Some(&scroll));
                pop
            })
        }

        fn key_pressed(
            &self,
            _controller: &gtk::EventControllerKey,
            key: gdk::Key,
            _keycode: u32,
            state: gdk::ModifierType,
        ) -> glib::Propagation {
            if state.contains(
                gdk::ModifierType::SHIFT_MASK
                    | gdk::ModifierType::ALT_MASK
                    | gdk::ModifierType::CONTROL_MASK,
            ) {
                self.accept_current_selection();
                return glib::Propagation::Stop;
            }

            match key {
                Key::Return | Key::KP_Enter | Key::ISO_Enter => {
                    self.accept_current_selection();
                    let visible = self.popup_visible.get();
                    self.text_changed_idle(false);

                    info!("Enter: {visible}");
                    self.set_popup_visible(!visible);
                    glib::Propagation::Proceed
                }
                Key::Escape => {
                    self.set_popup_visible(false);
                    let handler_id = self.change_id.get().unwrap();

                    let this = self.obj();
                    this.block_signal(handler_id);
                    this.set_text("");
                    this.set_position(-1);
                    self.set_popup_visible(false);
                    self.text_changed_idle(false);
                    this.unblock_signal(handler_id);
                    glib::Propagation::Stop
                }
                Key::Tab | Key::KP_Tab | Key::ISO_Left_Tab => {
                    self.set_popup_visible(false);
                    glib::Propagation::Proceed
                }
                _ => {
                    let Some(single) = self.single_selection.get() else {
                        return glib::Propagation::Stop;
                    };

                    let matches = single.n_items();
                    let mut selected = single.selected();

                    let proceed = match key {
                        Key::Up | Key::KP_Up => {
                            if selected == 0 {
                                selected = gtk::INVALID_LIST_POSITION;
                            } else if selected == gtk::INVALID_LIST_POSITION {
                                selected = matches - 1;
                            } else {
                                selected -= 1;
                            }

                            glib::Propagation::Stop
                        }
                        Key::Down | Key::KP_Down => {
                            if selected == matches - 1 {
                                selected = gtk::INVALID_LIST_POSITION;
                            } else if selected == gtk::INVALID_LIST_POSITION {
                                selected = 0;
                            } else {
                                selected += 1;
                            }

                            glib::Propagation::Stop
                        }
                        Key::Page_Up => {
                            if selected == 0 {
                                selected = gtk::INVALID_LIST_POSITION;
                            } else if selected == gtk::INVALID_LIST_POSITION {
                                selected = matches - 1;
                            } else if selected >= PAGE_STEP {
                                selected -= PAGE_STEP
                            } else {
                                selected -= 1;
                            }

                            glib::Propagation::Stop
                        }
                        Key::Page_Down => {
                            if selected == matches - 1 {
                                selected = gtk::INVALID_LIST_POSITION;
                            } else if selected == gtk::INVALID_LIST_POSITION {
                                selected = 0;
                            } else if selected + PAGE_STEP < matches {
                                selected += PAGE_STEP
                            } else {
                                selected += 1;
                            }

                            glib::Propagation::Stop
                        }
                        _ => glib::Propagation::Proceed,
                    };

                    if selected != gtk::INVALID_LIST_POSITION {
                        self.drop_list_view().scroll_to(
                            selected,
                            gtk::ListScrollFlags::SELECT,
                            None,
                        );
                    }
                    proceed
                }
            }
        }

        fn accept_current_selection(&self) {
            let Some(item) = self.single_selection.get().and_then(|s| s.selected_item()) else {
                return;
            };

            let handler_id = self.change_id.get().unwrap();

            let obj = self.obj();
            obj.block_signal(handler_id);

            let Some(expression) = self.expression.get() else {
                error!("Suggestion Expression None");
                return;
            };

            if let Some(value) = expression
                .evaluate(Some(&item))
                .and_then(|v| v.get::<String>().ok())
            {
                obj.set_text(&value);
            }

            obj.set_position(-1);

            obj.unblock_signal(handler_id);

            self.set_popup_visible(false);
        }

        fn text_changed_idle(&self, manage_popup: bool) {
            let text = self.obj().text();

            let mut last_filter_text = self.search_text.borrow_mut();

            let text_is_empty = text.is_empty();

            let change_type = if text_is_empty {
                gtk::FilterChange::LessStrict
            } else if text.len() > last_filter_text.len()
                && text.contains(last_filter_text.as_str())
            {
                gtk::FilterChange::MoreStrict
            } else if text.len() < last_filter_text.len()
                && last_filter_text.contains(text.as_str())
            {
                gtk::FilterChange::LessStrict
            } else {
                gtk::FilterChange::Different
            };

            debug!("Search text. Current \"{text}\" Prev \"{last_filter_text}\"");
            last_filter_text.replace_range(.., text.as_str());

            if let Some(custom_filter) = self.custom_filter.get() {
                custom_filter.changed(change_type);
            }

            if manage_popup {
                let matches = self
                    .single_selection
                    .get()
                    .map(|s| s.n_items())
                    .unwrap_or_default();
                //TODO Hacky
                self.set_popup_visible(matches > 1 || (matches == 1 && self.popup_visible.get()));
            }
        }

        fn text_changed(&self) {
            /* We need to defer to an idle since GtkText sets selection bounds
             * after notify::text
             */
            let this = self.obj().downgrade();
            glib::spawn_future_local(async move {
                let this = upgrade!(this);
                this.imp().text_changed_idle(true);
            });
        }

        pub(crate) fn set_text2(&self, text: &str) {
            let handler_id = self.change_id.get().unwrap();

            let this = self.obj();
            this.block_signal(handler_id);
            this.set_text(text);
            this.unblock_signal(handler_id);
        }

        pub fn filter_list_model(&self) -> &OnceCell<gtk::FilterListModel> {
            &self.filter_list_model
        }

        pub fn set_filter_list_model(&mut self, filter_list_model: OnceCell<gtk::FilterListModel>) {
            self.filter_list_model = filter_list_model;
        }

        fn popup_height(&self) -> i32 {
            self.popover().height()
        }

        fn set_popup_height(&self, val: i32) {
            self.popover().set_height_request(val)
        }

        fn popup_width(&self) -> i32 {
            self.popover().width()
        }

        fn set_popup_width(&self, val: i32) {
            self.popover().set_width_request(val)
        }
    }

    #[glib::object_subclass]
    impl ObjectSubclass for SuggestionRowImp {
        const NAME: &'static str = "SuggestionRow";
        type Type = super::SuggestionRow;
        type ParentType = adw::EntryRow;

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

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

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

            let filter = self.create_filter();

            self.custom_filter
                .set(filter.clone())
                .expect("custom filter set once");

            let filter_list_model = gtk::FilterListModel::new(None::<gio::ListStore>, Some(filter));
            let selection_model = gtk::SingleSelection::builder()
                .can_unselect(true)
                .autoselect(false)
                .model(&filter_list_model)
                .build();

            let _ = self.single_selection.set(selection_model.clone());

            let _ = self.filter_list_model.set(filter_list_model);
            let this = self.downgrade();

            let gesture = gtk::GestureClick::new();
            gesture.connect_released(move |_, _, _, _| {
                let this = upgrade!(this);
                let visible = this.popup_visible.get();
                this.set_popup_visible(!visible);
            });

            self.obj().add_controller(gesture);

            let controller = gtk::EventControllerKey::new();

            let this = self.obj().downgrade();
            controller.connect_key_pressed(move |controller_key, key, code, status| {
                let this = upgrade!(this, glib::Propagation::Proceed);
                this.imp().key_pressed(controller_key, key, code, status)
            });

            let this = self.obj().clone();
            if let Some(text) = find_child_by_name::<gtk::Text>(&this, "text") {
                text.add_controller(controller);
            } else {
                error!("Text Widget not found");
            }

            selection_model.connect_selected_notify(move |_| {
                this.imp().accept_current_selection();
            });

            let handler = self
                .obj()
                .connect_text_notify(|this| this.imp().text_changed());

            let _ = self.change_id.set(handler);
            self.drop_list_view().set_model(Some(&selection_model));

            let controller = gtk::EventControllerFocus::new();

            let this = self.obj().clone();
            controller.connect_leave(move |_controller| {
                this.imp().set_popup_visible(false);
                this.imp().accept_current_selection();
            });
            self.obj().add_controller(controller);

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

            self.obj().set_expression(expression);

            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::<gtk::StringObject>().unwrap();
                let child = item.child().and_downcast::<gtk::Label>().unwrap();
                child.set_label(&data.string());
            });

            self.obj().set_factory(Some(&factory));
        }
    }

    impl WidgetImpl for SuggestionRowImp {}
    impl ListBoxRowImpl for SuggestionRowImp {}
    impl PreferencesRowImpl for SuggestionRowImp {}
    impl EntryRowImpl for SuggestionRowImp {}
}