corundum-framework-gui 0.7.0

The look shared by sapphire and asteria apps: egui shell, system fonts, Lucide icons, translations
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
//! [`ServiceRow`]: an About-page row for one of the app's background services.

use corundum_framework_platform::package;
use corundum_framework_service::{ServiceSpec, ServiceState};

use crate::service::{Job, ServiceOps};
use crate::tr;

/// The About-page row for one of the app's background services: what it is doing, and the
/// buttons that change it. Not registered, it offers **Keep running in the background**;
/// running or stopped, it says so and offers **Stop** or **Start**, and **Remove**; broken,
/// the reason and **Repair**, which takes the registration away and makes it again. When the
/// state cannot be found, it shows why and offers **Try again**.
///
/// A build running from cargo's `target` directory registers nothing, as a service must not
/// point into it: not registered, the row says it is a development build; broken, it shows
/// the reason without **Repair**. **Stop**, **Start** and **Remove** stay, so a registration
/// an installed build made can still be removed.
///
/// Before uninstalling the app on macOS or Linux, remove its background service (Settings ›
/// About › Remove). Windows' uninstaller removes it.
///
/// The state is found on a thread, as is every change, after which the state is found
/// again: a frame never waits on the service manager. Hold the row on the page and call
/// [`ui`](Self::ui) every frame.
pub struct ServiceRow {
    service: fn() -> ServiceSpec,
    /// The service's name, as its spec gives it.
    name: &'static str,
    /// How the service is reached: [`ServiceOps::SYSTEM`], or stand-ins in the tests.
    ops: ServiceOps,
    /// Whether the app is a cargo build, which registers nothing: a service must not point
    /// into a directory the next `cargo clean` empties.
    is_dev: bool,
    /// The state as last found, or why it could not be; `None` while it is being found.
    state: Option<Result<ServiceState, String>>,
    /// The change or lookup running now.
    job: Option<Job<Looked>>,
    /// What the last click did not do, and why, shown under the row.
    error: Option<(Act, String)>,
    /// The message ids of the buttons and notes last drawn, for the tests.
    #[cfg(test)]
    shown: Vec<&'static str>,
    /// The button the next frame clicks, as a person would, for the tests.
    #[cfg(test)]
    pressed: Option<&'static str>,
}

/// What a click on one of the row's buttons does.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Act {
    Install,
    Stop,
    Start,
    Remove,
    /// Take the registration away and make it again: making it over one still there is not
    /// something every manager accepts (launchd refuses to load a label already loaded).
    Repair,
}

/// A job's answer: what the change did, if there was one, and the state after it.
struct Looked {
    acted: Option<(Act, Result<(), String>)>,
    state: Result<ServiceState, String>,
}

impl ServiceRow {
    /// The row for the service `service` builds the spec of.
    pub fn new(service: fn() -> ServiceSpec) -> ServiceRow {
        let mut row = ServiceRow::with_ops(service, ServiceOps::SYSTEM);
        row.is_dev = package::current_exe().is_some_and(|exe| package::is_cargo_build(&exe));
        row
    }

    /// The row for `service`, reaching it through `ops` instead of this machine's service
    /// manager.
    pub(crate) fn with_ops(service: fn() -> ServiceSpec, ops: ServiceOps) -> ServiceRow {
        ServiceRow {
            service,
            name: service().app_name,
            ops,
            is_dev: false,
            state: None,
            job: None,
            error: None,
            #[cfg(test)]
            shown: Vec::new(),
            #[cfg(test)]
            pressed: None,
        }
    }

    /// Render the row: its label, the service's state, and the buttons the state calls for.
    pub fn ui(&mut self, ui: &mut egui::Ui) {
        #[cfg(test)]
        self.shown.clear();
        if self.state.is_none() && self.job.is_none() {
            self.run(ui.ctx(), None);
        }
        if let Some(answer) = self.job.as_ref().and_then(Job::poll) {
            self.job = None;
            match answer {
                Ok(looked) => {
                    self.error = looked
                        .acted
                        .and_then(|(act, done)| done.err().map(|err| (act, err)));
                    self.state = Some(looked.state);
                }
                Err(err) => self.state = Some(Err(err)),
            }
        }
        let mut clicked = None;
        let mut again = false;
        ui.horizontal(|ui| {
            ui.label(tr!(ui, "corundum-service-row", name = self.name));
            match self.state.clone() {
                None => {
                    ui.spinner();
                }
                // A cargo build registers nothing: it says why instead of offering to.
                Some(Ok(ServiceState::NotInstalled)) if self.is_dev => {
                    self.note(ui, "corundum-service-dev-build");
                }
                Some(Ok(ServiceState::NotInstalled)) => {
                    clicked = clicked.or(self.button(ui, "corundum-service-run", Act::Install));
                }
                Some(Ok(state @ (ServiceState::Running | ServiceState::Stopped))) => {
                    let (id, act, act_id) = if state == ServiceState::Running {
                        (
                            "corundum-service-running",
                            Act::Stop,
                            "corundum-service-stop",
                        )
                    } else {
                        (
                            "corundum-service-stopped",
                            Act::Start,
                            "corundum-service-start",
                        )
                    };
                    self.note(ui, id);
                    clicked = clicked.or(self.button(ui, act_id, act));
                    clicked = clicked.or(self.button(ui, "corundum-service-remove", Act::Remove));
                }
                Some(Ok(ServiceState::Broken { reason })) => {
                    self.noted("corundum-service-broken");
                    ui.colored_label(
                        ui.visuals().warn_fg_color,
                        tr!(ui, "corundum-service-broken", reason = reason.as_str()),
                    );
                    // Repair would register the cargo build; Stop, Start and Remove stay, so
                    // an installed build's old registration can still be taken away.
                    if !self.is_dev {
                        clicked =
                            clicked.or(self.button(ui, "corundum-service-repair", Act::Repair));
                    }
                }
                Some(Err(err)) => {
                    ui.colored_label(ui.visuals().error_fg_color, err);
                    again = self.button(ui, "corundum-service-try-again", ()).is_some();
                }
                // A state a later version of the service crate tells apart: nothing to offer.
                Some(Ok(_)) => {}
            }
        });
        if let Some(act) = clicked {
            self.run(ui.ctx(), Some(act));
        } else if again {
            self.run(ui.ctx(), None);
        }
        if let Some((act, error)) = &self.error {
            let text = if matches!(act, Act::Install | Act::Repair) {
                tr!(ui, "corundum-service-failed", error = error.as_str())
            } else {
                error.clone()
            };
            ui.colored_label(ui.visuals().error_fg_color, text);
        }
    }

    /// Do `act`, if any, on a thread, and find the state after it.
    fn run(&mut self, ctx: &egui::Context, act: Option<Act>) {
        let (service, ops) = (self.service, self.ops);
        self.state = None;
        self.job = Some(Job::spawn(ctx, "service state", move || {
            let spec = service();
            let acted = act.map(|act| (act, perform(&ops, act, &spec)));
            Looked {
                acted,
                state: (ops.state)(&spec),
            }
        }));
    }

    /// Draw the button `id`; `act` when it was clicked.
    fn button<T>(&mut self, ui: &mut egui::Ui, id: &'static str, act: T) -> Option<T> {
        let clicked = ui.button(tr!(ui, id)).clicked();
        #[cfg(test)]
        {
            self.shown.push(id);
            if self.pressed == Some(id) {
                self.pressed = None;
                return Some(act);
            }
        }
        clicked.then_some(act)
    }

    /// Draw the note `id`.
    fn note(&mut self, ui: &mut egui::Ui, id: &'static str) {
        self.noted(id);
        ui.label(tr!(ui, id));
    }

    /// Note that the note `id` was drawn, for the tests.
    fn noted(&mut self, _id: &'static str) {
        #[cfg(test)]
        self.shown.push(_id);
    }

    /// Click the button `id` on the next frame, as a person would.
    #[cfg(test)]
    fn press(&mut self, id: &'static str) {
        self.pressed = Some(id);
    }
}

/// Carry out `act` on the service `spec` describes.
fn perform(ops: &ServiceOps, act: Act, spec: &ServiceSpec) -> Result<(), String> {
    match act {
        Act::Install => (ops.install)(spec),
        Act::Stop => (ops.stop)(spec),
        Act::Start => (ops.start)(spec),
        Act::Remove => (ops.uninstall)(spec),
        Act::Repair => {
            (ops.uninstall)(spec)?;
            (ops.install)(spec)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::time::{Duration, Instant};

    use corundum_framework_service::{ServiceSpec, ServiceState};

    use super::*;
    use crate::service::ServiceOps;
    use crate::test_support::render_in;

    fn demo() -> ServiceSpec {
        ServiceSpec {
            app_name: "demo",
            description: "Demo".into(),
            args: Vec::new(),
            legacy_labels: Vec::new(),
            post_install: None,
        }
    }

    fn done(_: &ServiceSpec) -> Result<(), String> {
        Ok(())
    }

    /// Ops whose state is `state` and whose actions succeed and do nothing.
    fn ops(state: fn(&ServiceSpec) -> Result<ServiceState, String>) -> ServiceOps {
        ServiceOps {
            state,
            install: done,
            uninstall: done,
            stop: done,
            start: done,
        }
    }

    /// Render frames until `until` holds, for up to five seconds.
    fn settle(row: &mut ServiceRow, ctx: &egui::Context, until: impl Fn(&ServiceRow) -> bool) {
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            render_in(ctx, [600.0, 400.0], |ui| row.ui(ui));
            if until(row) || Instant::now() > deadline {
                return;
            }
            std::thread::sleep(Duration::from_millis(2));
        }
    }

    /// The buttons and notes shown once `state` has answered.
    fn shown(state: fn(&ServiceSpec) -> Result<ServiceState, String>) -> Vec<&'static str> {
        shown_as(state, false)
    }

    /// The buttons and notes shown once `state` has answered, in a development build when
    /// `is_dev`.
    fn shown_as(
        state: fn(&ServiceSpec) -> Result<ServiceState, String>,
        is_dev: bool,
    ) -> Vec<&'static str> {
        let mut row = ServiceRow::with_ops(demo, ops(state));
        row.is_dev = is_dev;
        settle(&mut row, &egui::Context::default(), |row| {
            !row.shown.is_empty()
        });
        row.shown.clone()
    }

    #[test]
    fn a_service_not_installed_offers_to_run_it() {
        assert_eq!(
            shown(|_| Ok(ServiceState::NotInstalled)),
            ["corundum-service-run"]
        );
    }

    #[test]
    fn a_running_service_offers_stop_and_remove() {
        assert_eq!(
            shown(|_| Ok(ServiceState::Running)),
            [
                "corundum-service-running",
                "corundum-service-stop",
                "corundum-service-remove"
            ]
        );
    }

    #[test]
    fn a_stopped_service_offers_start_and_remove() {
        assert_eq!(
            shown(|_| Ok(ServiceState::Stopped)),
            [
                "corundum-service-stopped",
                "corundum-service-start",
                "corundum-service-remove"
            ]
        );
    }

    #[test]
    fn a_broken_service_offers_repair() {
        assert_eq!(
            shown(|_| Ok(ServiceState::Broken {
                reason: "gone".into()
            })),
            ["corundum-service-broken", "corundum-service-repair"]
        );
    }

    #[test]
    fn a_development_build_offers_no_install() {
        assert_eq!(
            shown_as(|_| Ok(ServiceState::NotInstalled), true),
            ["corundum-service-dev-build"]
        );
    }

    #[test]
    fn a_development_build_offers_no_repair() {
        assert_eq!(
            shown_as(
                |_| Ok(ServiceState::Broken {
                    reason: "gone".into()
                }),
                true
            ),
            ["corundum-service-broken"]
        );
    }

    #[test]
    fn a_development_build_can_still_stop_start_and_remove() {
        // An old registration, made by an installed build, can still be taken away.
        assert_eq!(
            shown_as(|_| Ok(ServiceState::Running), true),
            [
                "corundum-service-running",
                "corundum-service-stop",
                "corundum-service-remove"
            ]
        );
        assert_eq!(
            shown_as(|_| Ok(ServiceState::Stopped), true),
            [
                "corundum-service-stopped",
                "corundum-service-start",
                "corundum-service-remove"
            ]
        );
    }

    #[test]
    fn a_failed_lookup_offers_to_try_again_and_asks_again() {
        static ASKED: AtomicUsize = AtomicUsize::new(0);
        fn failing(_: &ServiceSpec) -> Result<ServiceState, String> {
            ASKED.fetch_add(1, Ordering::SeqCst);
            Err("no manager".into())
        }
        let ctx = egui::Context::default();
        let mut row = ServiceRow::with_ops(demo, ops(failing));
        settle(&mut row, &ctx, |row| !row.shown.is_empty());
        assert_eq!(row.shown, ["corundum-service-try-again"]);
        assert_eq!(ASKED.load(Ordering::SeqCst), 1);
        row.press("corundum-service-try-again");
        settle(&mut row, &ctx, |_| ASKED.load(Ordering::SeqCst) >= 2);
        assert_eq!(ASKED.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn state_is_not_asked_on_the_ui_thread() {
        static RELEASED: AtomicBool = AtomicBool::new(false);
        fn blocking(_: &ServiceSpec) -> Result<ServiceState, String> {
            // Held until the test lets it go, for five seconds at most, so a row that asked
            // on the UI thread fails the timing below instead of hanging the test.
            let deadline = Instant::now() + Duration::from_secs(5);
            while !RELEASED.load(Ordering::SeqCst) && Instant::now() < deadline {
                std::thread::sleep(Duration::from_millis(2));
            }
            Ok(ServiceState::Running)
        }
        let ctx = egui::Context::default();
        let mut row = ServiceRow::with_ops(demo, ops(blocking));
        let started = Instant::now();
        render_in(&ctx, [600.0, 400.0], |ui| row.ui(ui));
        assert!(started.elapsed() < Duration::from_secs(1));
        assert!(row.shown.is_empty());
        RELEASED.store(true, Ordering::SeqCst);
        settle(&mut row, &ctx, |row| !row.shown.is_empty());
        assert_eq!(
            row.shown,
            [
                "corundum-service-running",
                "corundum-service-stop",
                "corundum-service-remove"
            ]
        );
    }

    #[test]
    fn repair_uninstalls_then_installs_and_looks_again() {
        static CALLS: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
        fn record(call: &'static str) {
            CALLS.lock().unwrap().push(call);
        }
        let ops = ServiceOps {
            state: |_| {
                record("state");
                Ok(ServiceState::Broken {
                    reason: "gone".into(),
                })
            },
            install: |_| {
                record("install");
                Ok(())
            },
            uninstall: |_| {
                record("uninstall");
                Ok(())
            },
            stop: done,
            start: done,
        };
        let ctx = egui::Context::default();
        let mut row = ServiceRow::with_ops(demo, ops);
        settle(&mut row, &ctx, |row| !row.shown.is_empty());
        row.press("corundum-service-repair");
        settle(&mut row, &ctx, |_| CALLS.lock().unwrap().len() >= 4);
        assert_eq!(
            *CALLS.lock().unwrap(),
            ["state", "uninstall", "install", "state"]
        );
    }
}