sector-f-linux

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

app.rs (22970B)


      1 //! The window: Patina's frame and header bar, then what is booted, the registry to follow, and the
      2 //! update. Nothing here touches the system; it goes through the `Backend`.
      3 
      4 use std::path::PathBuf;
      5 use std::sync::Arc;
      6 use std::sync::mpsc::{self, Receiver, TryRecvError};
      7 use std::time::{Duration, Instant};
      8 
      9 use patina::frame::{self, TitleBar};
     10 use patina::skin::{self, Skin};
     11 
     12 use crate::backend::{
     13     Action as Change, Availability, Backend, DEFAULT_REGISTRY, Event, Status, short_digest,
     14     valid_image, with_tag,
     15 };
     16 
     17 const HOME_SKIN: &str = "Default";
     18 
     19 /// What the header asks for, handled after it's drawn.
     20 enum Action {
     21     Quit,
     22     Check,
     23     RollBack,
     24     SetSkin(String),
     25     SystemTitleBar(bool),
     26 }
     27 
     28 struct Screenshot {
     29     path: PathBuf,
     30     started: Instant,
     31     asked: bool,
     32 }
     33 
     34 type Checked = (String, Result<Availability, String>);
     35 
     36 pub struct App {
     37     backend: Arc<dyn Backend>,
     38     ctx: egui::Context,
     39     custom_frame: bool,
     40     skins: Vec<Skin>,
     41     skin_errors: Vec<String>,
     42     skin: Option<String>,
     43 
     44     status: Result<Status, String>,
     45     /// The registries to pick from; the default is always first.
     46     registries: Vec<String>,
     47     selected: String,
     48     new_registry: String,
     49     add_error: Option<String>,
     50 
     51     /// What the registry said about `.0`, the last time it was asked.
     52     checked: Option<Checked>,
     53     checking: Option<Receiver<Checked>>,
     54     /// A change in progress, and what it has said so far.
     55     run: Option<Receiver<Event>>,
     56     log: Vec<String>,
     57     /// How the last change ended.
     58     outcome: Option<Result<(), String>>,
     59     /// A switch of registry waiting for the person to confirm it.
     60     confirming: Option<String>,
     61     screenshot: Option<Screenshot>,
     62 }
     63 
     64 impl App {
     65     pub fn new(cc: &eframe::CreationContext<'_>, backend: Arc<dyn Backend>) -> Self {
     66         patina::appearance::watch(&cc.egui_ctx);
     67         let dirs: Vec<_> = skin::app_dir("patina-updater").into_iter().collect();
     68         let (skins, skin_errors) = skin::load_all(skin::BUILT_IN, &dirs);
     69         let get = |key: &str| cc.storage.and_then(|s| s.get_string(key));
     70 
     71         let status = backend.status();
     72         let mut registries = vec![DEFAULT_REGISTRY.to_string()];
     73         for line in get("registries").unwrap_or_default().lines() {
     74             if valid_image(line) && !registries.iter().any(|r| with_tag(r) == with_tag(line)) {
     75                 registries.push(line.to_string());
     76             }
     77         }
     78         // The one the system follows is always in the list, whoever put it there.
     79         if let Ok(s) = &status
     80             && !s.image.is_empty()
     81             && !registries.iter().any(|r| with_tag(r) == with_tag(&s.image))
     82         {
     83             registries.push(s.image.clone());
     84         }
     85         let followed = status
     86             .as_ref()
     87             .map(|s| s.image.clone())
     88             .unwrap_or_else(|_| DEFAULT_REGISTRY.into());
     89         let selected = registries
     90             .iter()
     91             .find(|r| with_tag(r) == with_tag(&followed))
     92             .cloned()
     93             .unwrap_or_else(|| DEFAULT_REGISTRY.into());
     94 
     95         let app = Self {
     96             backend,
     97             ctx: cc.egui_ctx.clone(),
     98             custom_frame: get("custom_frame").as_deref() != Some("false"),
     99             skins,
    100             skin_errors,
    101             skin: std::env::var("PATINA_SKIN").ok().or_else(|| get("skin")),
    102             status,
    103             registries,
    104             selected,
    105             new_registry: String::new(),
    106             add_error: None,
    107             checked: None,
    108             checking: None,
    109             run: None,
    110             log: Vec::new(),
    111             outcome: None,
    112             confirming: None,
    113             screenshot: None,
    114         };
    115         app.apply_skin(&cc.egui_ctx);
    116         app
    117     }
    118 
    119     pub fn screenshot_to(&mut self, path: PathBuf) {
    120         self.screenshot = Some(Screenshot {
    121             path,
    122             started: Instant::now(),
    123             asked: false,
    124         });
    125     }
    126 
    127     /// Puts a screen up for the screenshots (`PATINA_UPDATER_DEMO`).
    128     pub fn demo(&mut self, what: &str) {
    129         match what {
    130             "available" => {
    131                 self.checked = Some((self.selected.clone(), self.backend.check(&self.selected)));
    132             }
    133             "working" => {
    134                 self.checked = Some((self.selected.clone(), self.backend.check(&self.selected)));
    135                 self.start(Change::Update);
    136             }
    137             "done" => {
    138                 self.log = vec![
    139                     "Pulling the new image".into(),
    140                     "Staging the deployment".into(),
    141                 ];
    142                 self.outcome = Some(Ok(()));
    143                 if let Ok(s) = &mut self.status {
    144                     s.staged = true;
    145                 }
    146             }
    147             "failed" => {
    148                 self.log = vec!["Pulling the new image".into()];
    149                 self.outcome = Some(Err(
    150                     "rpm-ostree: Failed to pull: no space left on device".into()
    151                 ));
    152             }
    153             "switch" => {
    154                 let other = "registry.example.org/team/os:stable".to_string();
    155                 self.registries.push(other.clone());
    156                 self.selected = other;
    157                 self.confirming = Some(self.selected.clone());
    158             }
    159             "unreachable" => {
    160                 self.registries.push("down.example/team/os:latest".into());
    161                 self.selected = "down.example/team/os:latest".into();
    162                 self.checked = Some((self.selected.clone(), self.backend.check(&self.selected)));
    163             }
    164             _ => {}
    165         }
    166     }
    167 
    168     fn skin(&self) -> &Skin {
    169         let find = |name: &str| self.skins.iter().find(|s| s.name == name);
    170         find(self.skin.as_deref().unwrap_or(HOME_SKIN))
    171             .or_else(|| find(HOME_SKIN))
    172             .unwrap_or(&self.skins[0])
    173     }
    174 
    175     fn apply_skin(&self, ctx: &egui::Context) {
    176         self.skin().apply(ctx);
    177     }
    178 
    179     fn busy(&self) -> bool {
    180         self.run.is_some() || self.checking.is_some()
    181     }
    182 
    183     fn followed(&self) -> Option<&str> {
    184         self.status.as_ref().ok().map(|s| s.image.as_str())
    185     }
    186 
    187     /// Whether the registry picked is the one the system already follows.
    188     fn selected_is_followed(&self) -> bool {
    189         self.followed()
    190             .is_none_or(|f| with_tag(f) == with_tag(&self.selected))
    191     }
    192 
    193     fn start_check(&mut self) {
    194         if self.busy() {
    195             return;
    196         }
    197         let (tx, rx) = mpsc::channel();
    198         let (backend, ctx, image) = (
    199             self.backend.clone(),
    200             self.ctx.clone(),
    201             self.selected.clone(),
    202         );
    203         std::thread::spawn(move || {
    204             let result = backend.check(&image);
    205             let _ = tx.send((image, result));
    206             ctx.request_repaint();
    207         });
    208         self.checking = Some(rx);
    209         self.checked = None;
    210         self.outcome = None;
    211     }
    212 
    213     fn start(&mut self, change: Change) {
    214         if self.busy() {
    215             return;
    216         }
    217         let (tx, rx) = mpsc::channel();
    218         self.backend.run(change, tx);
    219         self.run = Some(rx);
    220         self.log.clear();
    221         self.outcome = None;
    222         self.confirming = None;
    223     }
    224 
    225     /// Takes what the background threads have said.
    226     fn poll(&mut self) {
    227         if let Some(rx) = &self.checking {
    228             match rx.try_recv() {
    229                 Ok(result) => {
    230                     self.checked = Some(result);
    231                     self.checking = None;
    232                 }
    233                 Err(TryRecvError::Disconnected) => self.checking = None,
    234                 Err(TryRecvError::Empty) => {}
    235             }
    236         }
    237         let mut finished = false;
    238         if let Some(rx) = &self.run {
    239             loop {
    240                 match rx.try_recv() {
    241                     Ok(Event::Line(line)) => self.log.push(line),
    242                     Ok(Event::Done) => {
    243                         self.outcome = Some(Ok(()));
    244                         finished = true;
    245                     }
    246                     Ok(Event::Failed(why)) => {
    247                         self.outcome = Some(Err(why));
    248                         finished = true;
    249                     }
    250                     Err(TryRecvError::Empty) => break,
    251                     Err(TryRecvError::Disconnected) => {
    252                         finished = true;
    253                         break;
    254                     }
    255                 }
    256             }
    257         }
    258         if finished {
    259             self.run = None;
    260             self.status = self.backend.status();
    261             self.checked = None;
    262         }
    263     }
    264 
    265     fn add_registry(&mut self) {
    266         let image = self.new_registry.trim().to_string();
    267         if !valid_image(&image) {
    268             self.add_error =
    269                 Some("That is not a registry image, like ghcr.io/team/os:latest".into());
    270         } else if self
    271             .registries
    272             .iter()
    273             .any(|r| with_tag(r) == with_tag(&image))
    274         {
    275             self.add_error = Some("That one is already in the list".into());
    276         } else {
    277             self.registries.push(image.clone());
    278             self.selected = image;
    279             self.new_registry.clear();
    280             self.add_error = None;
    281             self.checked = None;
    282         }
    283     }
    284 
    285     fn menus(&self, ui: &mut egui::Ui, actions: &mut Vec<Action>) {
    286         ui.menu_button("File", |ui| {
    287             if ui
    288                 .add(egui::Button::new("Quit").shortcut_text("Ctrl+Q"))
    289                 .clicked()
    290             {
    291                 actions.push(Action::Quit);
    292                 ui.close();
    293             }
    294         });
    295         ui.menu_button("Update", |ui| {
    296             if ui
    297                 .add_enabled(!self.busy(), egui::Button::new("Check for updates"))
    298                 .clicked()
    299             {
    300                 actions.push(Action::Check);
    301                 ui.close();
    302             }
    303             let can = self.status.as_ref().is_ok_and(|s| s.can_roll_back);
    304             if ui
    305                 .add_enabled(
    306                     can && !self.busy(),
    307                     egui::Button::new("Roll back to the previous build"),
    308                 )
    309                 .clicked()
    310             {
    311                 actions.push(Action::RollBack);
    312                 ui.close();
    313             }
    314         });
    315         ui.menu_button("View", |ui| {
    316             let mut system = !self.custom_frame;
    317             if ui.checkbox(&mut system, "System Title Bar").changed() {
    318                 actions.push(Action::SystemTitleBar(system));
    319             }
    320         });
    321         ui.menu_button("Skins", |ui| {
    322             let current = self.skin().name.clone();
    323             for skin in &self.skins {
    324                 if ui.radio(skin.name == current, &skin.name).clicked() {
    325                     actions.push(Action::SetSkin(skin.name.clone()));
    326                 }
    327             }
    328             for error in &self.skin_errors {
    329                 ui.colored_label(ui.visuals().error_fg_color, error);
    330             }
    331         });
    332     }
    333 
    334     fn body(&mut self, ui: &mut egui::Ui) {
    335         ui.add_space(4.0);
    336         ui.heading("Sector F Linux");
    337         match &self.status {
    338             Ok(s) => {
    339                 ui.label(format!(
    340                     "Version {}",
    341                     if s.version.is_empty() {
    342                         "unknown"
    343                     } else {
    344                         &s.version
    345                     }
    346                 ));
    347                 ui.label(
    348                     egui::RichText::new(format!("{}  {}", s.image, short_digest(&s.digest)))
    349                         .monospace()
    350                         .weak(),
    351                 );
    352             }
    353             Err(why) => {
    354                 ui.colored_label(ui.visuals().error_fg_color, why);
    355             }
    356         }
    357 
    358         if self.status.as_ref().is_ok_and(|s| s.staged) {
    359             ui.add_space(10.0);
    360             ui.horizontal(|ui| {
    361                 ui.label(egui::RichText::new("An update is ready. Restart to use it.").strong());
    362                 if ui.button("Restart now").clicked()
    363                     && let Err(why) = self.backend.restart()
    364                 {
    365                     self.outcome = Some(Err(why));
    366                 }
    367             });
    368         }
    369 
    370         ui.add_space(14.0);
    371         ui.label(egui::RichText::new("Registry").strong());
    372         ui.label(
    373             egui::RichText::new(
    374                 "Where updates come from. The system follows the one it was last switched to.",
    375             )
    376             .weak(),
    377         );
    378         ui.add_space(4.0);
    379         self.registry_list(ui);
    380 
    381         ui.add_space(14.0);
    382         self.update_section(ui);
    383 
    384         if !self.log.is_empty() {
    385             ui.add_space(10.0);
    386             egui::ScrollArea::vertical()
    387                 .max_height(150.0)
    388                 .stick_to_bottom(true)
    389                 .show(ui, |ui| {
    390                     for line in &self.log {
    391                         ui.label(egui::RichText::new(line).monospace().weak());
    392                     }
    393                 });
    394         }
    395         match &self.outcome {
    396             Some(Ok(())) => {
    397                 ui.add_space(6.0);
    398                 ui.label("Done. The new build starts at the next restart.");
    399             }
    400             Some(Err(why)) => {
    401                 ui.add_space(6.0);
    402                 ui.colored_label(ui.visuals().error_fg_color, why);
    403             }
    404             None => {}
    405         }
    406     }
    407 
    408     fn registry_list(&mut self, ui: &mut egui::Ui) {
    409         let followed = self.followed().map(with_tag);
    410         let mut remove = None;
    411         for (i, registry) in self.registries.clone().iter().enumerate() {
    412             ui.horizontal(|ui| {
    413                 let enabled = !self.busy();
    414                 if ui
    415                     .add_enabled(
    416                         enabled,
    417                         egui::RadioButton::new(self.selected == *registry, registry),
    418                     )
    419                     .clicked()
    420                 {
    421                     self.selected = registry.clone();
    422                     self.checked = None;
    423                     self.confirming = None;
    424                 }
    425                 let mut notes = Vec::new();
    426                 if i == 0 {
    427                     notes.push("default");
    428                 }
    429                 if followed.as_deref() == Some(&with_tag(registry)) {
    430                     notes.push("in use");
    431                 }
    432                 if !notes.is_empty() {
    433                     ui.label(egui::RichText::new(notes.join(", ")).weak());
    434                 }
    435                 let removable = i != 0 && followed.as_deref() != Some(&with_tag(registry));
    436                 if removable
    437                     && ui
    438                         .add_enabled(enabled, egui::Button::new("Remove").small())
    439                         .clicked()
    440                 {
    441                     remove = Some(i);
    442                 }
    443             });
    444         }
    445         if let Some(i) = remove {
    446             let gone = self.registries.remove(i);
    447             if self.selected == gone {
    448                 self.selected = DEFAULT_REGISTRY.into();
    449                 self.checked = None;
    450             }
    451         }
    452         ui.add_space(4.0);
    453         ui.horizontal(|ui| {
    454             let edit = ui.add(
    455                 egui::TextEdit::singleline(&mut self.new_registry)
    456                     .hint_text("ghcr.io/team/os:latest")
    457                     .desired_width(300.0),
    458             );
    459             let enter = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
    460             if (ui
    461                 .add_enabled(
    462                     !self.new_registry.trim().is_empty(),
    463                     egui::Button::new("Add"),
    464                 )
    465                 .clicked()
    466                 || enter)
    467                 && !self.new_registry.trim().is_empty()
    468             {
    469                 self.add_registry();
    470             }
    471         });
    472         if let Some(why) = &self.add_error {
    473             ui.colored_label(ui.visuals().error_fg_color, why);
    474         }
    475     }
    476 
    477     fn update_section(&mut self, ui: &mut egui::Ui) {
    478         let same = self.selected_is_followed();
    479         let newer = matches!(&self.checked, Some((image, Ok(Availability::Newer { .. }))) if *image == self.selected);
    480 
    481         if let Some(image) = self.confirming.clone() {
    482             ui.label(egui::RichText::new(format!("Switch this system to {image}?")).strong());
    483             ui.colored_label(
    484                 ui.visuals().warn_fg_color,
    485                 "The system will be replaced by that image at the next restart, and will follow it from now on. Anyone who controls that registry controls what this computer runs. Only choose one you trust. The previous build is kept, so you can roll back.",
    486             );
    487             ui.add_space(4.0);
    488             ui.horizontal(|ui| {
    489                 if ui.button("Switch").clicked() {
    490                     self.start(Change::Switch(image));
    491                 }
    492                 if ui.button("Cancel").clicked() {
    493                     self.confirming = None;
    494                 }
    495             });
    496             return;
    497         }
    498 
    499         ui.horizontal(|ui| {
    500             if ui
    501                 .add_enabled(!self.busy(), egui::Button::new("Check for updates"))
    502                 .clicked()
    503             {
    504                 self.start_check();
    505             }
    506             if same {
    507                 if ui
    508                     .add_enabled(newer && !self.busy(), egui::Button::new("Update"))
    509                     .clicked()
    510                 {
    511                     self.start(Change::Update);
    512                 }
    513             } else if ui
    514                 .add_enabled(!self.busy(), egui::Button::new("Switch to this registry"))
    515                 .clicked()
    516             {
    517                 self.confirming = Some(self.selected.clone());
    518             }
    519             if self.checking.is_some() {
    520                 ui.spinner();
    521             }
    522             if self.run.is_some() {
    523                 ui.spinner();
    524                 ui.label("Working");
    525             }
    526         });
    527         match &self.checked {
    528             Some((image, Ok(Availability::UpToDate))) if *image == self.selected => {
    529                 ui.label("This system is up to date.");
    530             }
    531             Some((image, Ok(Availability::Newer { digest }))) if *image == self.selected => {
    532                 ui.label(if same {
    533                     format!("An update is available ({}).", short_digest(digest))
    534                 } else {
    535                     format!(
    536                         "That registry has an image ({}). Switching replaces the system with it.",
    537                         short_digest(digest)
    538                     )
    539                 });
    540             }
    541             Some((_, Err(why))) => {
    542                 ui.colored_label(ui.visuals().error_fg_color, why);
    543             }
    544             _ => {}
    545         }
    546     }
    547 
    548     fn take_screenshot(&mut self, events: &[egui::Event]) {
    549         let Some(shot) = &mut self.screenshot else {
    550             return;
    551         };
    552         for event in events {
    553             if let egui::Event::Screenshot { image, .. } = event {
    554                 let (w, h) = (image.width() as u32, image.height() as u32);
    555                 match image::save_buffer(&shot.path, image.as_raw(), w, h, image::ColorType::Rgba8)
    556                 {
    557                     Ok(()) => eprintln!("patina-updater: wrote {}", shot.path.display()),
    558                     Err(e) => eprintln!("patina-updater: can't save {}: {e}", shot.path.display()),
    559                 }
    560                 self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
    561                 return;
    562             }
    563         }
    564         if !shot.asked && shot.started.elapsed() > Duration::from_millis(1500) {
    565             shot.asked = true;
    566             self.ctx
    567                 .send_viewport_cmd(egui::ViewportCommand::Screenshot(Default::default()));
    568         }
    569     }
    570 }
    571 
    572 impl eframe::App for App {
    573     fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
    574         // The window draws its own frame, so nothing gives it a shadow: ask the compositor to
    575         // (Patina's ADR-0030). It does nothing off Wayland, or once it has been asked.
    576         if self.custom_frame {
    577             patina::frame::shadow::request(frame);
    578         }
    579         let ctx = ui.ctx().clone();
    580         self.poll();
    581         let events = ui.input(|i| i.events.clone());
    582         self.take_screenshot(&events);
    583         if self.busy() || self.screenshot.is_some() {
    584             ctx.request_repaint_after(Duration::from_millis(100));
    585         }
    586 
    587         let style = self.skin().frame_style(ui.visuals());
    588         let radius = if self.custom_frame {
    589             frame::corner_radius(&ctx, style.radius)
    590         } else {
    591             0
    592         };
    593 
    594         let mut actions = Vec::new();
    595         egui::Panel::top("header")
    596             .frame(frame::header_frame(ui.style(), &style, radius))
    597             .show(ui, |ui| {
    598                 TitleBar::new("Software Update", &style)
    599                     .custom(self.custom_frame)
    600                     .menu_bar(true)
    601                     .span(frame::header_span(ui))
    602                     .show(ui, |ui| self.menus(ui, &mut actions), |_ui| {});
    603             });
    604         for action in actions {
    605             match action {
    606                 Action::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
    607                 Action::Check => self.start_check(),
    608                 Action::RollBack => self.start(Change::RollBack),
    609                 Action::SetSkin(name) => {
    610                     self.skin = Some(name);
    611                     self.apply_skin(&ctx);
    612                 }
    613                 Action::SystemTitleBar(on) => {
    614                     self.custom_frame = !on;
    615                     ctx.send_viewport_cmd(egui::ViewportCommand::Decorations(on));
    616                 }
    617             }
    618         }
    619 
    620         egui::CentralPanel::default()
    621             .frame(
    622                 egui::Frame::central_panel(ui.style()).corner_radius(egui::CornerRadius {
    623                     sw: radius,
    624                     se: radius,
    625                     ..Default::default()
    626                 }),
    627             )
    628             .show(ui, |ui| self.body(ui));
    629 
    630         if self.custom_frame {
    631             frame::edges(&ctx, radius, style.border);
    632         }
    633         if ctx.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Q)) {
    634             ctx.send_viewport_cmd(egui::ViewportCommand::Close);
    635         }
    636     }
    637 
    638     fn save(&mut self, storage: &mut dyn eframe::Storage) {
    639         // The default is always there, so only the others are kept.
    640         storage.set_string(
    641             "registries",
    642             self.registries
    643                 .iter()
    644                 .skip(1)
    645                 .cloned()
    646                 .collect::<Vec<_>>()
    647                 .join("\n"),
    648         );
    649         storage.set_string("custom_frame", self.custom_frame.to_string());
    650         if let Some(skin) = &self.skin {
    651             storage.set_string("skin", skin.clone());
    652         }
    653     }
    654 
    655     fn clear_color(&self, visuals: &egui::Visuals) -> [f32; 4] {
    656         frame::clear_color(visuals, self.custom_frame)
    657     }
    658 
    659     fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
    660         frame::release_grab(ctx, raw_input);
    661     }
    662 }