sector-f-linux

Sector F Linux
git clone https://git.sectorflabs.com/sector-f-linux.git
Log | Files | Refs | README | LICENSE

app.rs (18483B)


      1 //! The installer's screens, in the greeter's look (Everforest, no window frame, pills): choose the
      2 //! drive, confirm it by name, the flask and a progress bar while it installs, and done or failed
      3 //! (ADR-0014). Whatever the backend does runs on its own threads and answers over a channel.
      4 
      5 use std::path::PathBuf;
      6 use std::sync::Arc;
      7 use std::sync::mpsc::{Receiver, Sender, channel};
      8 use std::time::{Duration, Instant};
      9 
     10 use egui::{Align2, CornerRadius, FontId, RichText, Sense, Stroke, StrokeKind, Ui, vec2};
     11 use patina::skin::{self, Skin};
     12 
     13 use crate::backend::{Backend, Drive, Event, gigabytes};
     14 use crate::flask;
     15 
     16 /// The skin the greeter wears, and so the installer: one visual language from the stick to the
     17 /// first account.
     18 const HOME_SKIN: &str = "Everforest Dark";
     19 const LOGO: &[u8] = include_bytes!("../../linux/system/usr/share/pixmaps/seflos-logo.svg");
     20 const COLUMN: f32 = 640.0;
     21 const PILL: egui::Vec2 = vec2(340.0, 46.0);
     22 
     23 #[derive(Clone, PartialEq, Debug)]
     24 pub enum Screen {
     25     Choose,
     26     Confirm,
     27     Installing,
     28     Done,
     29     Failed(String),
     30 }
     31 
     32 struct Screenshot {
     33     path: PathBuf,
     34     started: Instant,
     35     asked: bool,
     36 }
     37 
     38 pub struct App {
     39     ctx: egui::Context,
     40     backend: Arc<dyn Backend>,
     41     pub screen: Screen,
     42     drives: Vec<Drive>,
     43     drives_at: Instant,
     44     /// The chosen drive, by path, so a refresh of the list keeps it.
     45     chosen: Option<String>,
     46     tx: Sender<Event>,
     47     rx: Receiver<Event>,
     48     step: String,
     49     progress: Option<f32>,
     50     began: Instant,
     51     restart_error: Option<String>,
     52     screenshot: Option<Screenshot>,
     53 }
     54 
     55 impl App {
     56     pub fn new(cc: &eframe::CreationContext<'_>, backend: Arc<dyn Backend>) -> Self {
     57         egui_extras::install_image_loaders(&cc.egui_ctx);
     58         Self::with_context(cc.egui_ctx.clone(), pick_skin(), backend)
     59     }
     60 
     61     pub fn with_context(ctx: egui::Context, skin: Skin, backend: Arc<dyn Backend>) -> Self {
     62         let (tx, rx) = channel();
     63         skin.apply(&ctx);
     64         let drives = backend.drives();
     65         Self {
     66             ctx,
     67             backend,
     68             screen: Screen::Choose,
     69             drives,
     70             drives_at: Instant::now(),
     71             chosen: None,
     72             tx,
     73             rx,
     74             step: String::new(),
     75             progress: None,
     76             began: Instant::now(),
     77             restart_error: None,
     78             screenshot: None,
     79         }
     80     }
     81 
     82     pub fn screenshot_to(&mut self, path: PathBuf) {
     83         self.screenshot = Some(Screenshot {
     84             path,
     85             started: Instant::now(),
     86             asked: false,
     87         });
     88     }
     89 
     90     /// Puts a screen up for the screenshots (`PATINA_INSTALLER_DEMO`).
     91     pub fn demo(&mut self, what: &str) {
     92         let first = self
     93             .drives
     94             .iter()
     95             .find(|d| d.unusable.is_none())
     96             .map(|d| d.path.clone());
     97         match what {
     98             "choose" => self.chosen = first,
     99             "confirm" => {
    100                 self.chosen = first;
    101                 self.screen = Screen::Confirm;
    102             }
    103             "installing" => {
    104                 self.chosen = first;
    105                 self.step = "Writing the system to the drive".into();
    106                 self.progress = Some(0.42);
    107                 self.screen = Screen::Installing;
    108             }
    109             "done" => self.screen = Screen::Done,
    110             "failed" => {
    111                 self.screen =
    112                     Screen::Failed("bootc: writing the bootloader: No space left on device".into());
    113             }
    114             _ => {}
    115         }
    116     }
    117 
    118     fn chosen_drive(&self) -> Option<&Drive> {
    119         let path = self.chosen.as_deref()?;
    120         self.drives
    121             .iter()
    122             .find(|d| d.path == path && d.unusable.is_none())
    123     }
    124 
    125     fn start_install(&mut self) {
    126         let Some(drive) = self.chosen_drive().cloned() else {
    127             self.screen = Screen::Choose;
    128             return;
    129         };
    130         self.step = "Starting".into();
    131         self.progress = None;
    132         self.began = Instant::now();
    133         self.screen = Screen::Installing;
    134         self.backend.install(&drive, self.tx.clone());
    135     }
    136 
    137     fn poll(&mut self) {
    138         while let Ok(event) = self.rx.try_recv() {
    139             if self.screen != Screen::Installing {
    140                 continue;
    141             }
    142             match event {
    143                 Event::Step(s) => self.step = s,
    144                 Event::Progress(p) => self.progress = Some(p.clamp(0.0, 1.0)),
    145                 Event::Done => self.screen = Screen::Done,
    146                 Event::Failed(why) => self.screen = Screen::Failed(why),
    147             }
    148         }
    149         // Drives come and go (a USB stick plugged in): look again every few seconds.
    150         if self.screen == Screen::Choose && self.drives_at.elapsed() > Duration::from_secs(3) {
    151             self.drives = self.backend.drives();
    152             self.drives_at = Instant::now();
    153             if self.chosen_drive().is_none() {
    154                 self.chosen = None;
    155             }
    156         }
    157     }
    158 
    159     pub fn draw(&mut self, ui: &mut Ui) {
    160         self.poll();
    161         let events = ui.input(|i| i.events.clone());
    162         self.take_screenshot(&events);
    163         let visuals = ui.visuals().clone();
    164         egui::Panel::bottom("footer")
    165             .frame(egui::Frame::NONE.fill(visuals.panel_fill))
    166             .show(ui, |ui| {
    167                 ui.vertical_centered(|ui| {
    168                     ui.add_space(18.0);
    169                     ui.add(
    170                         egui::Image::from_bytes("bytes://sector-f-labs.svg", LOGO)
    171                             .fit_to_exact_size(vec2(205.0, 42.0))
    172                             .tint(visuals.weak_text_color()),
    173                     );
    174                     ui.add_space(22.0);
    175                 });
    176             });
    177         egui::CentralPanel::default()
    178             .frame(egui::Frame::NONE.fill(visuals.panel_fill))
    179             .show(ui, |ui| {
    180                 let height = ui.max_rect().height();
    181                 let screen = self.screen.clone();
    182                 ui.vertical_centered(|ui| {
    183                     ui.set_max_width(COLUMN);
    184                     ui.add_space(height * 0.08);
    185                     match screen {
    186                         Screen::Choose => self.draw_choose(ui, &events),
    187                         Screen::Confirm => self.draw_confirm(ui, &events),
    188                         Screen::Installing => self.draw_installing(ui),
    189                         Screen::Done => self.draw_done(ui),
    190                         Screen::Failed(why) => self.draw_failed(ui, &why),
    191                     }
    192                 });
    193             });
    194         let busy = self.screen == Screen::Installing || self.screenshot.is_some();
    195         ui.ctx()
    196             .request_repaint_after(Duration::from_millis(if busy {
    197                 1000 / flask::FPS as u64
    198             } else {
    199                 500
    200             }));
    201     }
    202 
    203     fn heading(ui: &mut Ui, title: &str, sub: &str) {
    204         ui.label(RichText::new(title).size(34.0).strong());
    205         ui.add_space(8.0);
    206         ui.label(
    207             RichText::new(sub)
    208                 .size(17.0)
    209                 .color(ui.visuals().weak_text_color()),
    210         );
    211         ui.add_space(26.0);
    212     }
    213 
    214     fn draw_choose(&mut self, ui: &mut Ui, events: &[egui::Event]) {
    215         Self::heading(
    216             ui,
    217             "Install Sector F Linux",
    218             "Choose the drive to install on. Everything on it will be erased.",
    219         );
    220         if self.drives.is_empty() {
    221             ui.label("No drives found.");
    222         }
    223         let mut clicked = None;
    224         for drive in &self.drives {
    225             let on = self.chosen.as_deref() == Some(drive.path.as_str());
    226             if drive_card(ui, drive, on).clicked() && drive.unusable.is_none() {
    227                 clicked = Some(drive.path.clone());
    228             }
    229             ui.add_space(10.0);
    230         }
    231         if clicked.is_some() {
    232             self.chosen = clicked;
    233         }
    234         ui.add_space(16.0);
    235         let enter = events.iter().any(|e| {
    236             matches!(
    237                 e,
    238                 egui::Event::Key {
    239                     key: egui::Key::Enter,
    240                     pressed: true,
    241                     ..
    242                 }
    243             )
    244         });
    245         let ready = self.chosen_drive().is_some();
    246         if (pill_button(ui, "Continue", ready, false, false).clicked() || enter) && ready {
    247             self.screen = Screen::Confirm;
    248         }
    249     }
    250 
    251     fn draw_confirm(&mut self, ui: &mut Ui, events: &[egui::Event]) {
    252         let Some(drive) = self.chosen_drive().cloned() else {
    253             self.screen = Screen::Choose;
    254             return;
    255         };
    256         Self::heading(
    257             ui,
    258             &format!("Erase {}?", drive.model),
    259             &format!("{} · {}", gigabytes(drive.bytes), drive.path),
    260         );
    261         ui.label(format!(
    262             "This deletes everything on it: {}.",
    263             drive.contents.join(", ")
    264         ));
    265         ui.add_space(6.0);
    266         ui.label("It cannot be undone.");
    267         ui.add_space(28.0);
    268         if pill_button(ui, "Erase and install", true, false, true).clicked() {
    269             self.start_install();
    270         }
    271         ui.add_space(12.0);
    272         let back = events.iter().any(|e| {
    273             matches!(
    274                 e,
    275                 egui::Event::Key {
    276                     key: egui::Key::Escape,
    277                     pressed: true,
    278                     ..
    279                 }
    280             )
    281         });
    282         if ui.button("Back").clicked() || back {
    283             self.screen = Screen::Choose;
    284         }
    285     }
    286 
    287     fn draw_installing(&mut self, ui: &mut Ui) {
    288         let seconds = self.began.elapsed().as_secs_f64();
    289         ui.add_space(10.0);
    290         flask::show(ui, seconds, 200.0, true);
    291         ui.add_space(28.0);
    292         ui.label(
    293             RichText::new("Installing Sector F Linux")
    294                 .size(26.0)
    295                 .strong(),
    296         );
    297         ui.add_space(8.0);
    298         ui.label(
    299             RichText::new(&self.step)
    300                 .size(16.0)
    301                 .color(ui.visuals().weak_text_color()),
    302         );
    303         ui.add_space(20.0);
    304         // A bar only when the progress is real (a bar that lies is worse than none).
    305         if let Some(p) = self.progress {
    306             ui.add(
    307                 egui::ProgressBar::new(p)
    308                     .desired_width(380.0)
    309                     .text(format!("{:.0}%", p * 100.0)),
    310             );
    311         }
    312         ui.add_space(20.0);
    313         ui.label(
    314             RichText::new("This takes a few minutes. Don't turn the computer off.")
    315                 .color(ui.visuals().weak_text_color()),
    316         );
    317     }
    318 
    319     fn draw_done(&mut self, ui: &mut Ui) {
    320         flask::show(ui, 0.75, 160.0, false);
    321         ui.add_space(24.0);
    322         Self::heading(
    323             ui,
    324             "Sector F Linux is installed",
    325             "Remove the install disc, then restart to set it up.",
    326         );
    327         if pill_button(ui, "Restart", true, false, false).clicked() {
    328             self.restart_error = self.backend.restart().err();
    329         }
    330         if let Some(e) = &self.restart_error {
    331             ui.add_space(10.0);
    332             ui.colored_label(
    333                 ui.visuals().error_fg_color,
    334                 format!("Could not restart: {e}"),
    335             );
    336         }
    337     }
    338 
    339     fn draw_failed(&mut self, ui: &mut Ui, why: &str) {
    340         Self::heading(
    341             ui,
    342             "The install did not finish",
    343             "Nothing is lost that was not already on the drive. You can try again.",
    344         );
    345         if !why.is_empty() {
    346             egui::Frame::new()
    347                 .fill(ui.visuals().extreme_bg_color)
    348                 .corner_radius(10)
    349                 .inner_margin(14)
    350                 .show(ui, |ui| {
    351                     ui.label(RichText::new(why).monospace().size(13.0));
    352                 });
    353             ui.add_space(24.0);
    354         }
    355         if pill_button(ui, "Try again", true, false, false).clicked() {
    356             self.drives = self.backend.drives();
    357             self.chosen = None;
    358             self.screen = Screen::Choose;
    359         }
    360         ui.add_space(12.0);
    361         if ui.button("Restart").clicked() {
    362             self.restart_error = self.backend.restart().err();
    363         }
    364     }
    365 
    366     fn take_screenshot(&mut self, events: &[egui::Event]) {
    367         let Some(shot) = &mut self.screenshot else {
    368             return;
    369         };
    370         for event in events {
    371             if let egui::Event::Screenshot { image, .. } = event {
    372                 let (w, h) = (image.width() as u32, image.height() as u32);
    373                 match image::save_buffer(&shot.path, image.as_raw(), w, h, image::ColorType::Rgba8)
    374                 {
    375                     Ok(()) => eprintln!("patina-installer: wrote {}", shot.path.display()),
    376                     Err(e) => {
    377                         eprintln!("patina-installer: can't save {}: {e}", shot.path.display());
    378                     }
    379                 }
    380                 self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
    381                 return;
    382             }
    383         }
    384         if !shot.asked && shot.started.elapsed() > Duration::from_millis(1500) {
    385             shot.asked = true;
    386             self.ctx
    387                 .send_viewport_cmd(egui::ViewportCommand::Screenshot(Default::default()));
    388         }
    389     }
    390 }
    391 
    392 fn pick_skin() -> Skin {
    393     let (skins, errors) = skin::load_all(skin::BUILT_IN, &[]);
    394     for e in errors {
    395         eprintln!("patina-installer: skin: {e}");
    396     }
    397     let wanted = std::env::var("PATINA_SKIN").unwrap_or_else(|_| HOME_SKIN.into());
    398     let find = |name: &str| skins.iter().find(|s| s.name == name).cloned();
    399     find(&wanted)
    400         .or_else(|| find(HOME_SKIN))
    401         .unwrap_or_else(Skin::default_skin)
    402 }
    403 
    404 /// A drive as a card: what it is and how big, its serial and what is on it; the chosen one in the
    405 /// accent, one that cannot be chosen dimmed with the reason in place of its contents.
    406 fn drive_card(ui: &mut Ui, drive: &Drive, chosen: bool) -> egui::Response {
    407     let usable = drive.unusable.is_none();
    408     let width = ui.available_width().min(COLUMN);
    409     let (rect, response) = ui.allocate_exact_size(
    410         vec2(width, 78.0),
    411         if usable {
    412             Sense::click()
    413         } else {
    414             Sense::hover()
    415         },
    416     );
    417     if usable && response.hovered() {
    418         ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
    419     }
    420     let v = ui.visuals();
    421     let radius = CornerRadius::same(14);
    422     let fill = if chosen {
    423         v.selection.bg_fill.gamma_multiply(0.35)
    424     } else if response.hovered() && usable {
    425         v.widgets.hovered.weak_bg_fill
    426     } else {
    427         v.widgets.inactive.weak_bg_fill
    428     };
    429     let painter = ui.painter();
    430     painter.rect_filled(rect, radius, fill);
    431     if chosen {
    432         painter.rect_stroke(
    433             rect,
    434             radius,
    435             Stroke::new(2.0, v.selection.bg_fill),
    436             StrokeKind::Inside,
    437         );
    438     }
    439     let (ink, dim) = if usable {
    440         (v.text_color(), v.weak_text_color())
    441     } else {
    442         (v.weak_text_color(), v.weak_text_color().gamma_multiply(0.7))
    443     };
    444     let left = rect.left() + 20.0;
    445     painter.text(
    446         egui::pos2(left, rect.top() + 26.0),
    447         Align2::LEFT_CENTER,
    448         &drive.model,
    449         FontId::proportional(19.0),
    450         ink,
    451     );
    452     painter.text(
    453         egui::pos2(rect.right() - 20.0, rect.top() + 26.0),
    454         Align2::RIGHT_CENTER,
    455         gigabytes(drive.bytes),
    456         FontId::proportional(19.0),
    457         ink,
    458     );
    459     let second = match &drive.unusable {
    460         Some(why) => why.clone(),
    461         None => {
    462             let mut s = drive.contents.join(" · ");
    463             if !drive.serial.is_empty() {
    464                 s = format!("{s}   —   serial {}", drive.serial);
    465             }
    466             s
    467         }
    468     };
    469     painter.text(
    470         egui::pos2(left, rect.top() + 54.0),
    471         Align2::LEFT_CENTER,
    472         second,
    473         FontId::proportional(14.5),
    474         dim,
    475     );
    476     response
    477 }
    478 
    479 /// The big pill (as the greeter's), in the accent, or in the error colour for an erase.
    480 fn pill_button(ui: &mut Ui, text: &str, ready: bool, busy: bool, danger: bool) -> egui::Response {
    481     let v = ui.visuals().clone();
    482     let (rect, response) = ui.allocate_exact_size(PILL, Sense::click());
    483     if ready && response.hovered() {
    484         ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
    485     }
    486     let accent = if danger {
    487         v.error_fg_color
    488     } else {
    489         v.selection.bg_fill
    490     };
    491     let ink = if danger {
    492         v.panel_fill
    493     } else {
    494         v.selection.stroke.color
    495     };
    496     let (fill, ink) = if ready {
    497         let fill = if response.hovered() {
    498             accent.gamma_multiply(0.85)
    499         } else {
    500             accent
    501         };
    502         (fill, ink)
    503     } else {
    504         (v.widgets.inactive.weak_bg_fill, v.weak_text_color())
    505     };
    506     ui.painter()
    507         .rect_filled(rect, CornerRadius::same((PILL.y / 2.0) as u8), fill);
    508     ui.painter().text(
    509         rect.center(),
    510         Align2::CENTER_CENTER,
    511         if busy { "Working…" } else { text },
    512         FontId::proportional(17.0),
    513         ink,
    514     );
    515     response
    516 }
    517 
    518 #[cfg(test)]
    519 mod tests {
    520     use super::*;
    521     use crate::backend::Mock;
    522 
    523     fn app() -> App {
    524         let ctx = egui::Context::default();
    525         App::with_context(ctx, Skin::default_skin(), Arc::new(Mock::new(false)))
    526     }
    527 
    528     fn frame(app: &mut App) {
    529         let ctx = app.ctx.clone();
    530         let _ = ctx.run_ui(Default::default(), |ui| app.draw(ui));
    531     }
    532 
    533     #[test]
    534     fn a_drive_that_cannot_be_chosen_is_never_chosen() {
    535         let mut app = app();
    536         app.chosen = Some("/dev/sda".into()); // the install disc's own drive, in the mock
    537         assert!(app.chosen_drive().is_none());
    538         app.start_install();
    539         assert_eq!(app.screen, Screen::Choose);
    540     }
    541 
    542     #[test]
    543     fn every_screen_draws() {
    544         for what in ["choose", "confirm", "installing", "done", "failed"] {
    545             let mut app = app();
    546             app.demo(what);
    547             frame(&mut app);
    548         }
    549     }
    550 
    551     #[test]
    552     fn events_move_the_screens_and_a_late_one_is_ignored() {
    553         let mut app = app();
    554         app.demo("confirm");
    555         app.start_install();
    556         assert_eq!(app.screen, Screen::Installing);
    557         app.tx.send(Event::Progress(0.5)).unwrap();
    558         app.tx.send(Event::Done).unwrap();
    559         app.poll();
    560         assert_eq!(app.screen, Screen::Done);
    561         app.tx.send(Event::Failed("late".into())).unwrap();
    562         app.poll();
    563         assert_eq!(app.screen, Screen::Done);
    564     }
    565 }