sector-f-linux

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

app.rs (60345B)


      1 //! The greeter's screens, drawn the way patina-lock draws its own: the skin's background, the
      2 //! time, a round avatar, and a pill for the password. There is no window frame, title bar or
      3 //! menu: it is a full-screen login (Patina's frame is for windows with menus).
      4 //!
      5 //! Two modes (ADR-0012). With accounts, the login. With none, the first-run setup, which makes
      6 //! the first account and then logs it straight in. Whatever the backend does runs on a worker
      7 //! thread, since PAM and D-Bus can take seconds, and answers over a channel.
      8 
      9 use std::path::PathBuf;
     10 use std::sync::Arc;
     11 use std::sync::mpsc::{Receiver, Sender, channel};
     12 use std::time::{Duration, Instant};
     13 
     14 use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, pos2, vec2};
     15 use patina::skin::{self, Skin};
     16 
     17 use crate::backend::{Backend, LoginError, Network, Power, User};
     18 use crate::field::{self, Field, Tone};
     19 use crate::model::{self, SetupForm};
     20 
     21 /// The skin the greeter wears: the desktop's own, so the login screen and the desktop match.
     22 const HOME_SKIN: &str = "Everforest Dark";
     23 /// How long the pill shakes after a wrong password.
     24 const SHAKE: f32 = 0.45;
     25 /// The logo GDM showed: the flask and the words Sector F Labs (linux/branding/make-logo.py).
     26 const LOGO: &[u8] = include_bytes!("../../linux/system/usr/share/pixmaps/seflos-logo.svg");
     27 
     28 #[derive(Clone, Copy, PartialEq, Debug)]
     29 pub enum Screen {
     30     Login,
     31     Setup,
     32 }
     33 
     34 /// The first-run setup's steps, in order (ADR-0019). The account is last: the polkit rule that lets
     35 /// the greeter manage accounts only holds until the first one can log in, so whatever else the
     36 /// setup changes on the system is changed in the steps before it.
     37 #[derive(Clone, Copy, PartialEq, Debug)]
     38 pub enum Step {
     39     Wifi,
     40     Clock,
     41     Name,
     42     Account,
     43 }
     44 
     45 /// The zones whose name has every word of `query` in it, in the order given. `stock` finds
     46 /// `Europe/Stockholm`; `new york` finds `America/New_York`; nothing typed finds them all.
     47 fn zones_matching<'a>(zones: &'a [String], query: &str) -> Vec<&'a String> {
     48     let words: Vec<String> = query
     49         .split_whitespace()
     50         .map(|w| w.replace('_', " ").to_lowercase())
     51         .collect();
     52     zones
     53         .iter()
     54         .filter(|zone| {
     55             let name = zone.replace('_', " ").to_lowercase();
     56             words.iter().all(|w| name.contains(w.as_str()))
     57         })
     58         .collect()
     59 }
     60 
     61 #[derive(Clone, PartialEq, Debug)]
     62 pub enum Status {
     63     Typing,
     64     Checking,
     65     Wrong,
     66     Problem(String),
     67 }
     68 
     69 /// The setup's fields, in the order they are filled in.
     70 #[derive(Clone, Copy, PartialEq, Debug)]
     71 enum Slot {
     72     FullName,
     73     Username,
     74     Password,
     75     Confirm,
     76 }
     77 
     78 const SLOTS: [Slot; 4] = [
     79     Slot::FullName,
     80     Slot::Username,
     81     Slot::Password,
     82     Slot::Confirm,
     83 ];
     84 
     85 /// What a worker thread reports back.
     86 enum Done {
     87     Login(Result<(), LoginError>),
     88     Created(Result<(), String>),
     89     Zone(Result<(), String>),
     90     Name(Result<(), String>),
     91     Networks(Vec<Network>),
     92     Wifi(Result<(), String>),
     93 }
     94 
     95 struct Screenshot {
     96     path: PathBuf,
     97     started: Instant,
     98     asked: bool,
     99 }
    100 
    101 pub struct App {
    102     ctx: egui::Context,
    103     backend: Arc<dyn Backend>,
    104     screen: Screen,
    105     users: Vec<User>,
    106     selected: usize,
    107     login: Field,
    108     status: Status,
    109     wrong_at: Option<Instant>,
    110     fields: [Field; 4],
    111     /// Once the person has typed their own user name, it stops following the full name.
    112     username_edited: bool,
    113     focus: Slot,
    114     tx: Sender<Done>,
    115     rx: Receiver<Done>,
    116     /// The new account's user name, between making it and logging it in.
    117     new_user: Option<String>,
    118     /// The steps this machine has, in order (no Wi-Fi step without Wi-Fi), and the one showing.
    119     steps: Vec<Step>,
    120     step: Step,
    121     /// The Wi-Fi step: the networks in range, the one picked, the password typed for it, and
    122     /// when the list was last asked for.
    123     networks: Vec<Network>,
    124     wifi_pick: Option<String>,
    125     wifi_field: Field,
    126     wifi_asked: Option<Instant>,
    127     wifi_scanning: bool,
    128     /// The clock step: every zone, the one chosen, what is typed to search, and whether the list
    129     /// has been scrolled to the chosen one yet.
    130     zones: Vec<String>,
    131     zone: String,
    132     zone_filter: String,
    133     zone_scrolled: bool,
    134     /// The name step: what is typed for the computer's name.
    135     host: String,
    136     host_focused: bool,
    137     screenshot: Option<Screenshot>,
    138     finished: bool,
    139 }
    140 
    141 impl App {
    142     pub fn new(cc: &eframe::CreationContext<'_>, backend: Arc<dyn Backend>) -> Self {
    143         egui_extras::install_image_loaders(&cc.egui_ctx);
    144         Self::with_context(cc.egui_ctx.clone(), pick_skin(), backend)
    145     }
    146 
    147     pub fn with_context(ctx: egui::Context, skin: Skin, backend: Arc<dyn Backend>) -> Self {
    148         let (tx, rx) = channel();
    149         skin.apply(&ctx);
    150         let mut app = Self {
    151             ctx,
    152             backend,
    153             screen: Screen::Login,
    154             users: Vec::new(),
    155             selected: 0,
    156             login: Field::new("Password", true),
    157             status: Status::Typing,
    158             wrong_at: None,
    159             fields: [
    160                 Field::new("Full name", false),
    161                 Field::new("User name", false),
    162                 Field::new("Password", true),
    163                 Field::new("Confirm password", true),
    164             ],
    165             username_edited: false,
    166             focus: Slot::FullName,
    167             tx,
    168             rx,
    169             new_user: None,
    170             steps: vec![Step::Clock, Step::Name, Step::Account],
    171             step: Step::Clock,
    172             networks: Vec::new(),
    173             wifi_pick: None,
    174             wifi_field: Field::new("Password", true),
    175             wifi_asked: None,
    176             wifi_scanning: false,
    177             zones: Vec::new(),
    178             zone: String::new(),
    179             zone_filter: String::new(),
    180             zone_scrolled: false,
    181             host: String::new(),
    182             host_focused: false,
    183             screenshot: None,
    184             finished: false,
    185         };
    186         app.refresh();
    187         app
    188     }
    189 
    190     /// Asks the backend who can log in, and so which screen to show.
    191     pub fn refresh(&mut self) {
    192         self.users = self.backend.users();
    193         self.selected = self.selected.min(self.users.len().saturating_sub(1));
    194         self.screen = if self.backend.first_run() {
    195             if self.zones.is_empty() {
    196                 self.zones = self.backend.timezones();
    197                 self.zone = self.backend.timezone();
    198                 self.host = self.backend.hostname();
    199                 if self.backend.wifi_available() {
    200                     self.steps.insert(0, Step::Wifi);
    201                 }
    202                 self.step = self.steps[0];
    203             }
    204             Screen::Setup
    205         } else {
    206             Screen::Login
    207         };
    208     }
    209 
    210     /// Saves the screen to `path` a moment after it first shows, and quits (`make screenshot`).
    211     pub fn screenshot_to(&mut self, path: PathBuf) {
    212         self.screenshot = Some(Screenshot {
    213             path,
    214             started: Instant::now(),
    215             asked: false,
    216         });
    217     }
    218 
    219     /// Fills the screen with something to look at, for screenshots.
    220     pub fn demo(&mut self, what: &str) {
    221         match (self.screen, what) {
    222             (Screen::Login, "typing") => self.login.text = "sectorf".into(),
    223             (Screen::Login, "problem") => {
    224                 self.status = Status::Problem("Can't reach the login service".into())
    225             }
    226             (Screen::Login, "wrong") => {
    227                 self.login.text.clear();
    228                 self.status = Status::Wrong;
    229             }
    230             (Screen::Setup, "wifi") => {
    231                 self.networks = self.backend.wifi_networks();
    232                 self.wifi_asked = Some(Instant::now());
    233                 self.wifi_pick = Some("Home-5G".into());
    234             }
    235             (Screen::Setup, "wifi-problem") => {
    236                 self.networks = self.backend.wifi_networks();
    237                 self.wifi_asked = Some(Instant::now());
    238                 self.wifi_pick = Some("Home-5G".into());
    239                 self.wifi_field.text = "not it".into();
    240                 self.status =
    241                     Status::Problem("could not join Home-5G: the password was not accepted".into());
    242             }
    243             (Screen::Setup, "name") => {
    244                 self.step = Step::Name;
    245                 self.host = "alices-laptop".into();
    246             }
    247             (Screen::Setup, "name-problem") => {
    248                 self.step = Step::Name;
    249                 self.host = "Alice's laptop".into();
    250             }
    251             (Screen::Setup, "clock") => {
    252                 self.zone_filter = "stock".into();
    253                 self.zone = "Europe/Stockholm".into();
    254             }
    255             (Screen::Setup, "filled") => {
    256                 self.step = Step::Account;
    257                 self.fields[0].text = "Alice Example".into();
    258                 self.fields[1].text = "alice".into();
    259                 self.fields[2].text = "correct horse".into();
    260                 self.fields[3].text = "correct horse".into();
    261                 self.username_edited = true;
    262                 self.focus = Slot::Confirm;
    263             }
    264             (Screen::Setup, "problem") => {
    265                 self.step = Step::Account;
    266                 self.fields[0].text = "Alice Example".into();
    267                 self.fields[1].text = "alice".into();
    268                 self.fields[2].text = "correct horse".into();
    269                 self.fields[3].text = "correct hors".into();
    270                 self.username_edited = true;
    271                 self.focus = Slot::Confirm;
    272             }
    273             _ => {}
    274         }
    275     }
    276 
    277     /// Runs `work` on a thread of its own and delivers what it returns to the next frame.
    278     fn spawn(&self, work: impl FnOnce(&dyn Backend) -> Done + Send + 'static) {
    279         let backend = Arc::clone(&self.backend);
    280         let tx = self.tx.clone();
    281         let ctx = self.ctx.clone();
    282         std::thread::spawn(move || {
    283             let done = work(backend.as_ref());
    284             let _ = tx.send(done);
    285             ctx.request_repaint();
    286         });
    287     }
    288 
    289     fn log_in(&mut self, user: String, mut password: String) {
    290         self.status = Status::Checking;
    291         self.spawn(move |backend| {
    292             let result = backend.login(&user, &password);
    293             model::wipe(&mut password);
    294             Done::Login(result)
    295         });
    296     }
    297 
    298     fn submit_login(&mut self) {
    299         if self.login.text.is_empty() || self.status == Status::Checking {
    300             return;
    301         }
    302         let Some(user) = self.users.get(self.selected).map(|u| u.name.clone()) else {
    303             return;
    304         };
    305         let password = std::mem::replace(
    306             &mut self.login.text,
    307             String::with_capacity(model::MAX_PASSWORD),
    308         );
    309         self.log_in(user, password);
    310     }
    311 
    312     fn form(&self) -> SetupForm {
    313         SetupForm {
    314             full_name: self.fields[0].text.trim().to_string(),
    315             username: self.fields[1].text.clone(),
    316             password: self.fields[2].text.clone(),
    317             confirm: self.fields[3].text.clone(),
    318         }
    319     }
    320 
    321     /// Sets the zone chosen and goes on; with nothing changed there is nothing to ask the system.
    322     fn submit_clock(&mut self) {
    323         if self.status == Status::Checking || self.zone.is_empty() {
    324             return;
    325         }
    326         if self.zone == self.backend.timezone() {
    327             return self.go_on();
    328         }
    329         self.status = Status::Checking;
    330         let zone = self.zone.clone();
    331         self.spawn(move |backend| Done::Zone(backend.set_timezone(&zone)));
    332     }
    333 
    334     /// The name as it will be set: lower case, nothing round it.
    335     fn host_name(&self) -> String {
    336         model::normalise_hostname(&self.host)
    337     }
    338 
    339     /// Sets the name typed and goes on; with it unchanged there is nothing to ask the system.
    340     fn submit_name(&mut self) {
    341         let name = self.host_name();
    342         if self.status == Status::Checking || model::check_hostname(&name).is_err() {
    343             return;
    344         }
    345         if name == self.backend.hostname() {
    346             return self.go_on();
    347         }
    348         self.status = Status::Checking;
    349         self.spawn(move |backend| Done::Name(backend.set_hostname(&name)));
    350     }
    351 
    352     /// Asks for the networks in range, unless that is already being done.
    353     fn scan(&mut self) {
    354         if self.wifi_scanning {
    355             return;
    356         }
    357         self.wifi_scanning = true;
    358         self.wifi_asked = Some(Instant::now());
    359         self.spawn(|backend| Done::Networks(backend.wifi_networks()));
    360     }
    361 
    362     fn picked_network(&self) -> Option<&Network> {
    363         let ssid = self.wifi_pick.as_deref()?;
    364         self.networks.iter().find(|n| n.ssid == ssid)
    365     }
    366 
    367     /// Whether Connect can be pressed: a network picked, and its password if it has one.
    368     fn wifi_ready(&self) -> bool {
    369         self.picked_network()
    370             .is_some_and(|n| !n.secured() || !self.wifi_field.text.is_empty())
    371     }
    372 
    373     fn submit_wifi(&mut self) {
    374         if self.status == Status::Checking || !self.wifi_ready() {
    375             return;
    376         }
    377         let Some(network) = self.picked_network().cloned() else {
    378             return;
    379         };
    380         let mut password = std::mem::replace(
    381             &mut self.wifi_field.text,
    382             String::with_capacity(model::MAX_PASSWORD),
    383         );
    384         self.status = Status::Checking;
    385         self.spawn(move |backend| {
    386             let result = backend.wifi_connect(&network.ssid, &password);
    387             model::wipe(&mut password);
    388             Done::Wifi(result)
    389         });
    390     }
    391 
    392     fn step_index(&self) -> usize {
    393         self.steps.iter().position(|s| *s == self.step).unwrap_or(0)
    394     }
    395 
    396     fn next_step(&self) -> Option<Step> {
    397         self.steps.get(self.step_index() + 1).copied()
    398     }
    399 
    400     fn previous_step(&self) -> Option<Step> {
    401         self.step_index().checked_sub(1).map(|i| self.steps[i])
    402     }
    403 
    404     /// Continue, on whichever step this is.
    405     fn submit_step(&mut self) {
    406         match self.step {
    407             Step::Wifi => self.submit_wifi(),
    408             Step::Clock => self.submit_clock(),
    409             Step::Name => self.submit_name(),
    410             Step::Account => self.submit_setup(),
    411         }
    412     }
    413 
    414     /// To the next step, with nothing left over from this one.
    415     fn go_on(&mut self) {
    416         self.status = Status::Typing;
    417         if let Some(next) = self.next_step() {
    418             self.step = next;
    419         }
    420     }
    421 
    422     fn go_back(&mut self) {
    423         if self.status == Status::Checking {
    424             return;
    425         }
    426         self.status = Status::Typing;
    427         if let Some(previous) = self.previous_step() {
    428             self.step = previous;
    429         }
    430     }
    431 
    432     fn submit_setup(&mut self) {
    433         if self.status == Status::Checking {
    434             return;
    435         }
    436         let mut form = self.form();
    437         if form.problem().is_some() {
    438             form.wipe();
    439             return;
    440         }
    441         self.status = Status::Checking;
    442         self.new_user = Some(form.username.clone());
    443         self.spawn(move |backend| {
    444             let result = backend.create_first_user(&form.full_name, &form.username, &form.password);
    445             form.wipe();
    446             Done::Created(result)
    447         });
    448     }
    449 
    450     /// What the workers have said since the last frame.
    451     fn poll(&mut self) {
    452         while let Ok(done) = self.rx.try_recv() {
    453             match done {
    454                 Done::Login(Ok(())) => {
    455                     self.finished = true;
    456                     self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
    457                 }
    458                 Done::Login(Err(LoginError::Wrong)) => {
    459                     self.status = Status::Wrong;
    460                     self.wrong_at = Some(Instant::now());
    461                 }
    462                 Done::Login(Err(LoginError::Problem(e))) => self.status = Status::Problem(e),
    463                 Done::Created(Ok(())) => {
    464                     // The account exists: log it in with the password just given.
    465                     let user = self.new_user.take().unwrap_or_default();
    466                     let password = std::mem::take(&mut self.fields[2].text);
    467                     model::wipe(&mut self.fields[3].text);
    468                     self.refresh();
    469                     self.selected = self.users.iter().position(|u| u.name == user).unwrap_or(0);
    470                     self.log_in(user, password);
    471                 }
    472                 Done::Created(Err(e)) => {
    473                     self.new_user = None;
    474                     self.status = Status::Problem(e);
    475                 }
    476                 Done::Zone(Ok(())) => self.go_on(),
    477                 Done::Zone(Err(e)) | Done::Name(Err(e)) => self.status = Status::Problem(e),
    478                 Done::Name(Ok(())) => self.go_on(),
    479                 Done::Networks(list) => {
    480                     self.wifi_scanning = false;
    481                     self.networks = list;
    482                     if self.picked_network().is_none() {
    483                         self.wifi_pick = None;
    484                     }
    485                 }
    486                 Done::Wifi(Ok(())) => {
    487                     model::wipe(&mut self.wifi_field.text);
    488                     self.go_on();
    489                 }
    490                 Done::Wifi(Err(e)) => self.status = Status::Problem(e),
    491             }
    492         }
    493     }
    494 
    495     fn power(&mut self, action: Power) {
    496         if let Err(e) = self.backend.power(action) {
    497             self.status = Status::Problem(e);
    498         }
    499     }
    500 
    501     // ---- keys ----
    502 
    503     /// The events of a frame, in the order they came: a letter typed after Tab goes to the next
    504     /// field, and what is typed after Enter, while it is being checked, is dropped.
    505     fn handle_keys(&mut self, events: &[egui::Event]) {
    506         for event in events {
    507             if self.status == Status::Checking {
    508                 return;
    509             }
    510             match self.screen {
    511                 Screen::Login => self.login_event(event),
    512                 Screen::Setup => self.setup_event(event),
    513             }
    514         }
    515     }
    516 
    517     fn login_event(&mut self, event: &egui::Event) {
    518         if self.login.type_into(std::slice::from_ref(event)) {
    519             self.status = Status::Typing;
    520         }
    521         if let egui::Event::Key {
    522             key, pressed: true, ..
    523         } = event
    524         {
    525             match key {
    526                 egui::Key::Enter => self.submit_login(),
    527                 egui::Key::ArrowLeft => self.select(-1),
    528                 egui::Key::ArrowRight => self.select(1),
    529                 _ => {}
    530             }
    531         }
    532     }
    533 
    534     fn setup_event(&mut self, event: &egui::Event) {
    535         if self.step != Step::Account {
    536             // The Wi-Fi password is typed into the greeter's own secret field.
    537             if self.step == Step::Wifi
    538                 && self.picked_network().is_some_and(Network::secured)
    539                 && self.wifi_field.type_into(std::slice::from_ref(event))
    540             {
    541                 self.status = Status::Typing;
    542             }
    543             // The other steps are drawn with egui's own widgets, which take what is typed;
    544             // Enter is Continue.
    545             if let egui::Event::Key {
    546                 key: egui::Key::Enter,
    547                 pressed: true,
    548                 ..
    549             } = event
    550             {
    551                 self.submit_step();
    552             }
    553             return;
    554         }
    555         if let egui::Event::Key {
    556             key,
    557             pressed: true,
    558             modifiers,
    559             ..
    560         } = event
    561         {
    562             match key {
    563                 egui::Key::Tab => return self.move_focus(if modifiers.shift { -1 } else { 1 }),
    564                 egui::Key::Enter => {
    565                     if self.focus == Slot::Confirm {
    566                         self.submit_setup();
    567                     } else {
    568                         self.move_focus(1);
    569                     }
    570                     return;
    571                 }
    572                 _ => {}
    573             }
    574         }
    575         let slot = self.focus as usize;
    576         if self.fields[slot].type_into(std::slice::from_ref(event)) {
    577             self.status = Status::Typing;
    578             match self.focus {
    579                 Slot::FullName if !self.username_edited => {
    580                     self.fields[1].text = model::suggest_username(&self.fields[0].text);
    581                 }
    582                 Slot::Username => self.username_edited = !self.fields[1].text.is_empty(),
    583                 _ => {}
    584             }
    585         }
    586     }
    587 
    588     fn select(&mut self, step: i32) {
    589         let n = self.users.len() as i32;
    590         if n > 1 {
    591             self.selected = (self.selected as i32 + step).rem_euclid(n) as usize;
    592             self.login.clear();
    593             self.status = Status::Typing;
    594         }
    595     }
    596 
    597     fn move_focus(&mut self, step: i32) {
    598         let at = SLOTS.iter().position(|s| *s == self.focus).unwrap_or(0) as i32;
    599         self.focus = SLOTS[(at + step).rem_euclid(SLOTS.len() as i32) as usize];
    600     }
    601 
    602     // ---- drawing ----
    603 
    604     pub fn draw(&mut self, ui: &mut Ui) {
    605         self.poll();
    606         let events = ui.input(|i| i.events.clone());
    607         self.take_screenshot(&events);
    608         self.handle_keys(&events);
    609 
    610         let visuals = ui.visuals().clone();
    611         egui::Panel::bottom("footer")
    612             .frame(egui::Frame::NONE.fill(visuals.panel_fill))
    613             .show(ui, |ui| {
    614                 ui.vertical_centered(|ui| {
    615                     ui.add_space(18.0);
    616                     ui.add(
    617                         egui::Image::from_bytes("bytes://sector-f-labs.svg", LOGO)
    618                             .fit_to_exact_size(vec2(205.0, 42.0))
    619                             .tint(visuals.weak_text_color()),
    620                     );
    621                     ui.add_space(22.0);
    622                 });
    623             });
    624         egui::CentralPanel::default()
    625             .frame(egui::Frame::NONE.fill(visuals.panel_fill))
    626             .show(ui, |ui| {
    627                 let rect = ui.max_rect();
    628                 match self.screen {
    629                     Screen::Login => self.draw_login(ui, rect),
    630                     Screen::Setup => self.draw_setup(ui),
    631                 }
    632             });
    633         self.draw_power(ui.ctx());
    634         self.schedule(ui.ctx());
    635     }
    636 
    637     fn draw_login(&mut self, ui: &mut Ui, rect: egui::Rect) {
    638         let now = chrono::Local::now();
    639         ui.vertical_centered(|ui| {
    640             ui.add_space(rect.height() * 0.12);
    641             ui.label(
    642                 RichText::new(now.format("%H:%M").to_string())
    643                     .size(96.0)
    644                     .strong(),
    645             );
    646             ui.label(RichText::new(now.format("%A %-d %B").to_string()).size(22.0));
    647             ui.add_space(rect.height() * 0.10);
    648 
    649             // Everyone who can log in, the one chosen larger; one alone is just shown.
    650             if self.users.len() > 1 {
    651                 let side = 64.0;
    652                 let gap = 18.0;
    653                 let width = self.users.len() as f32 * side + (self.users.len() - 1) as f32 * gap;
    654                 let mut chosen = None;
    655                 ui.allocate_ui_with_layout(
    656                     vec2(width + 24.0, side + 32.0),
    657                     egui::Layout::left_to_right(egui::Align::Center),
    658                     |ui| {
    659                         ui.spacing_mut().item_spacing.x = gap;
    660                         for (i, user) in self.users.iter().enumerate() {
    661                             if avatar(ui, &user.full_name, side, i == self.selected).clicked() {
    662                                 chosen = Some(i);
    663                             }
    664                         }
    665                     },
    666                 );
    667                 if let Some(i) = chosen {
    668                     self.selected = i;
    669                     self.login.clear();
    670                     self.status = Status::Typing;
    671                 }
    672             } else if let Some(user) = self.users.first() {
    673                 avatar(ui, &user.full_name, 84.0, true);
    674             }
    675             ui.add_space(10.0);
    676             if let Some(user) = self.users.get(self.selected) {
    677                 ui.label(RichText::new(&user.full_name).size(20.0));
    678             }
    679             ui.add_space(14.0);
    680             self.password_pill(ui);
    681             ui.add_space(10.0);
    682             self.status_line(ui, "");
    683         });
    684     }
    685 
    686     /// The password pill with the arrow that sends it, and the shake on a wrong one.
    687     fn password_pill(&mut self, ui: &mut Ui) {
    688         let checking = self.status == Status::Checking;
    689         let shake = self
    690             .wrong_at
    691             .map(|t| t.elapsed().as_secs_f32())
    692             .filter(|s| *s < SHAKE)
    693             .map_or(0.0, |s| (s * 45.0).sin() * 10.0 * (1.0 - s / SHAKE));
    694         let tone = if self.status == Status::Wrong {
    695             Tone::Wrong
    696         } else if checking {
    697             Tone::Busy
    698         } else {
    699             Tone::Normal
    700         };
    701         let pill = egui::Rect::from_min_size(
    702             pos2(
    703                 ui.max_rect().center().x - field::SIZE.x / 2.0 + shake,
    704                 ui.cursor().min.y,
    705             ),
    706             field::SIZE,
    707         );
    708         ui.scope_builder(egui::UiBuilder::new().max_rect(pill), |ui| {
    709             self.login.show(ui, field::SIZE, true, tone, field::SIZE.y);
    710         });
    711         // The arrow over the right end of the pill.
    712         let button = egui::Rect::from_center_size(
    713             pos2(pill.right() - field::SIZE.y / 2.0, pill.center().y),
    714             vec2(field::SIZE.y - 12.0, field::SIZE.y - 12.0),
    715         );
    716         let ready = !self.login.text.is_empty() && !checking;
    717         if arrow(ui, button, ready, checking).clicked() && ready {
    718             self.submit_login();
    719         }
    720         ui.advance_cursor_after_rect(pill);
    721     }
    722 
    723     fn draw_setup(&mut self, ui: &mut Ui) {
    724         let rect = ui.max_rect();
    725         ui.vertical_centered(|ui| {
    726             ui.add_space(rect.height() * 0.14);
    727             ui.label(
    728                 RichText::new("Welcome to Sector F Linux")
    729                     .size(36.0)
    730                     .strong(),
    731             );
    732             ui.add_space(4.0);
    733             let subtitle = match self.step {
    734                 Step::Wifi => "Connect to Wi-Fi, so this computer has the network from the start.",
    735                 Step::Clock => "Choose your time zone, so the clock is right.",
    736                 Step::Name => "Give this computer a name.",
    737                 Step::Account => "Let's set up this computer.",
    738             };
    739             ui.label(
    740                 RichText::new(subtitle)
    741                     .size(18.0)
    742                     .color(ui.visuals().weak_text_color()),
    743             );
    744             ui.add_space(28.0);
    745             match self.step {
    746                 Step::Wifi => self.draw_wifi(ui),
    747                 Step::Clock => self.draw_clock(ui),
    748                 Step::Name => self.draw_name(ui),
    749                 Step::Account => self.draw_account(ui),
    750             }
    751             ui.add_space(12.0);
    752             self.draw_steps(ui);
    753         });
    754     }
    755 
    756     /// The last step: the first account (ADR-0012).
    757     fn draw_account(&mut self, ui: &mut Ui) {
    758         let checking = self.status == Status::Checking;
    759         for (i, slot) in SLOTS.iter().enumerate() {
    760             let tone = if checking { Tone::Busy } else { Tone::Normal };
    761             if self.fields[i]
    762                 .show(ui, field::SIZE, self.focus == *slot && !checking, tone, 0.0)
    763                 .clicked()
    764                 && !checking
    765             {
    766                 self.focus = *slot;
    767             }
    768             ui.add_space(10.0);
    769         }
    770         ui.add_space(4.0);
    771         let problem = self.form().problem();
    772         let ready = problem.is_none() && !checking;
    773         let create = wide_button(ui, "Create account", ready, checking);
    774         if create.clicked() && ready {
    775             self.submit_setup();
    776         }
    777         ui.add_space(10.0);
    778         self.status_line(ui, problem.unwrap_or(""));
    779     }
    780 
    781     /// The time zone (ADR-0019): a search over the zones, the list, and Continue.
    782     fn draw_clock(&mut self, ui: &mut Ui) {
    783         let checking = self.status == Status::Checking;
    784         let search = ui.add_enabled(
    785             !checking,
    786             egui::TextEdit::singleline(&mut self.zone_filter)
    787                 .hint_text("Search for a city or region")
    788                 .desired_width(field::SIZE.x)
    789                 .margin(egui::Margin::symmetric(14, 10)),
    790         );
    791         if !self.zone_scrolled {
    792             search.request_focus();
    793         }
    794         ui.add_space(8.0);
    795         let shown: Vec<String> = zones_matching(&self.zones, &self.zone_filter)
    796             .into_iter()
    797             .cloned()
    798             .collect();
    799         // A block as wide as the field, so it sits in the middle like the rest.
    800         ui.allocate_ui_with_layout(
    801             vec2(field::SIZE.x, 240.0),
    802             egui::Layout::top_down(egui::Align::Min),
    803             |ui| {
    804                 egui::ScrollArea::vertical()
    805                     .max_height(240.0)
    806                     .auto_shrink([false, false])
    807                     .show(ui, |ui| {
    808                         if shown.is_empty() {
    809                             ui.label(
    810                                 RichText::new("No time zone matches that")
    811                                     .color(ui.visuals().weak_text_color()),
    812                             );
    813                         }
    814                         for zone in &shown {
    815                             let chosen = *zone == self.zone;
    816                             let row = zone_row(ui, &zone.replace('_', " "), chosen);
    817                             if row.clicked() && !checking {
    818                                 self.zone = zone.clone();
    819                                 self.status = Status::Typing;
    820                             }
    821                             // Once, on the unfiltered list: put the zone in use in view.
    822                             if chosen && !self.zone_scrolled && self.zone_filter.is_empty() {
    823                                 row.scroll_to_me_animation(
    824                                     Some(egui::Align::Center),
    825                                     egui::style::ScrollAnimation::none(),
    826                                 );
    827                             }
    828                         }
    829                     });
    830             },
    831         );
    832         self.zone_scrolled = true;
    833         ui.add_space(14.0);
    834         let ready = !self.zone.is_empty() && !checking;
    835         if wide_button(ui, "Continue", ready, checking).clicked() && ready {
    836             self.submit_clock();
    837         }
    838         ui.add_space(10.0);
    839         let hint = if self.zone.is_empty() {
    840             String::new()
    841         } else {
    842             format!("Time zone: {}", self.zone.replace('_', " "))
    843         };
    844         self.status_line(ui, &hint);
    845     }
    846 
    847     /// Wi-Fi (ADR-0019): the networks in range, a password for a secured one, and Connect.
    848     fn draw_wifi(&mut self, ui: &mut Ui) {
    849         let checking = self.status == Status::Checking;
    850         // The list is asked for when the step opens and every few seconds after.
    851         if self
    852             .wifi_asked
    853             .is_none_or(|t| t.elapsed() > Duration::from_secs(8))
    854         {
    855             self.scan();
    856         }
    857         let weak = ui.visuals().weak_text_color();
    858         ui.allocate_ui_with_layout(
    859             vec2(field::SIZE.x, 190.0),
    860             egui::Layout::top_down(egui::Align::Min),
    861             |ui| {
    862                 egui::ScrollArea::vertical()
    863                     .max_height(190.0)
    864                     .auto_shrink([false, false])
    865                     .show(ui, |ui| {
    866                         if self.networks.is_empty() {
    867                             let text = if self.wifi_scanning {
    868                                 "Looking for networks…"
    869                             } else {
    870                                 "No networks found"
    871                             };
    872                             ui.label(RichText::new(text).color(weak));
    873                         }
    874                         for network in self.networks.clone() {
    875                             let chosen = self.wifi_pick.as_deref() == Some(&network.ssid);
    876                             let detail = format!(
    877                                 "{}  {}%",
    878                                 if network.secured() { "Secured" } else { "Open" },
    879                                 network.strength
    880                             );
    881                             if list_row(ui, &network.ssid, &detail, chosen).clicked() && !checking {
    882                                 if !chosen {
    883                                     model::wipe(&mut self.wifi_field.text);
    884                                 }
    885                                 self.wifi_pick = Some(network.ssid.clone());
    886                                 self.status = Status::Typing;
    887                             }
    888                         }
    889                     });
    890             },
    891         );
    892         ui.add_space(10.0);
    893         if self.picked_network().is_some_and(Network::secured) {
    894             let tone = if checking { Tone::Busy } else { Tone::Normal };
    895             self.wifi_field.show(ui, field::SIZE, !checking, tone, 0.0);
    896             ui.add_space(10.0);
    897         }
    898         let ready = self.wifi_ready() && !checking;
    899         let label = if checking { "Connecting…" } else { "Connect" };
    900         if wide_button(ui, label, ready, false).clicked() && ready {
    901             self.submit_wifi();
    902         }
    903         ui.add_space(10.0);
    904         let hint = if self.wifi_pick.is_none() {
    905             "Pick a network. Using a cable? Skip this."
    906         } else {
    907             ""
    908         };
    909         self.status_line(ui, hint);
    910     }
    911 
    912     /// The computer's name (ADR-0019): how it shows up on a network.
    913     fn draw_name(&mut self, ui: &mut Ui) {
    914         let checking = self.status == Status::Checking;
    915         let edit = ui.add_enabled(
    916             !checking,
    917             egui::TextEdit::singleline(&mut self.host)
    918                 .hint_text("a name for this computer")
    919                 .desired_width(field::SIZE.x)
    920                 .margin(egui::Margin::symmetric(14, 10)),
    921         );
    922         if !self.host_focused {
    923             edit.request_focus();
    924             self.host_focused = true;
    925         }
    926         if edit.changed() {
    927             self.status = Status::Typing;
    928         }
    929         ui.add_space(14.0);
    930         let problem = model::check_hostname(&self.host_name()).err();
    931         let ready = problem.is_none() && !checking;
    932         if wide_button(ui, "Continue", ready, checking).clicked() && ready {
    933             self.submit_name();
    934         }
    935         ui.add_space(10.0);
    936         let hint = problem.unwrap_or("It is how this computer shows up on your network");
    937         self.status_line(ui, hint);
    938     }
    939 
    940     /// Under every step: where this one is among them, Back, and Skip (the account cannot be
    941     /// skipped: it is what the setup is for).
    942     fn draw_steps(&mut self, ui: &mut Ui) {
    943         let weak = ui.visuals().weak_text_color();
    944         ui.label(
    945             RichText::new(format!(
    946                 "Step {} of {}",
    947                 self.step_index() + 1,
    948                 self.steps.len()
    949             ))
    950             .color(weak),
    951         );
    952         ui.add_space(6.0);
    953         let (mut back, mut skip) = (false, false);
    954         ui.allocate_ui_with_layout(
    955             vec2(field::SIZE.x, 28.0),
    956             egui::Layout::left_to_right(egui::Align::Center),
    957             |ui| {
    958                 if self.previous_step().is_some()
    959                     && ui.add(egui::Button::new("Back").frame(false)).clicked()
    960                 {
    961                     back = true;
    962                 }
    963                 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
    964                     if self.step != Step::Account
    965                         && ui.add(egui::Button::new("Skip").frame(false)).clicked()
    966                     {
    967                         skip = true;
    968                     }
    969                 });
    970             },
    971         );
    972         if back {
    973             self.go_back();
    974         }
    975         if skip && self.status != Status::Checking {
    976             self.go_on();
    977         }
    978     }
    979 
    980     /// The line under the form: what is happening, what went wrong, or what to do next.
    981     fn status_line(&self, ui: &mut Ui, hint: &str) {
    982         let v = ui.visuals();
    983         let (text, colour) = match &self.status {
    984             Status::Typing => (hint.to_string(), v.weak_text_color()),
    985             Status::Checking => ("Just a moment…".to_string(), v.weak_text_color()),
    986             Status::Wrong => ("Wrong password".to_string(), v.error_fg_color),
    987             Status::Problem(e) => (e.clone(), v.error_fg_color),
    988         };
    989         ui.label(RichText::new(text).color(colour));
    990     }
    991 
    992     /// Restart and Shut down, at the bottom right.
    993     fn draw_power(&mut self, ctx: &egui::Context) {
    994         let mut action = None;
    995         egui::Area::new(egui::Id::new("power"))
    996             .anchor(Align2::RIGHT_BOTTOM, vec2(-24.0, -22.0))
    997             .show(ctx, |ui| {
    998                 ui.horizontal(|ui| {
    999                     patina::dialog::buttons(ui);
   1000                     if ui
   1001                         .button("Restart")
   1002                         .on_hover_text("Restart this computer")
   1003                         .clicked()
   1004                     {
   1005                         action = Some(Power::Reboot);
   1006                     }
   1007                     if ui
   1008                         .button("Shut down")
   1009                         .on_hover_text("Shut this computer down")
   1010                         .clicked()
   1011                     {
   1012                         action = Some(Power::PowerOff);
   1013                     }
   1014                 });
   1015             });
   1016         if let Some(action) = action {
   1017             self.power(action);
   1018         }
   1019     }
   1020 
   1021     /// The minute changes on its own; the caret, the spinner and the shake need frames of their own.
   1022     fn schedule(&self, ctx: &egui::Context) {
   1023         let shaking = self
   1024             .wrong_at
   1025             .is_some_and(|t| t.elapsed().as_secs_f32() < SHAKE);
   1026         let quick = self.status == Status::Checking || shaking || self.screenshot.is_some();
   1027         ctx.request_repaint_after(Duration::from_millis(if quick { 16 } else { 500 }));
   1028     }
   1029 
   1030     fn take_screenshot(&mut self, events: &[egui::Event]) {
   1031         let Some(shot) = &mut self.screenshot else {
   1032             return;
   1033         };
   1034         for event in events {
   1035             if let egui::Event::Screenshot { image, .. } = event {
   1036                 let (w, h) = (image.width() as u32, image.height() as u32);
   1037                 match image::save_buffer(&shot.path, image.as_raw(), w, h, image::ColorType::Rgba8)
   1038                 {
   1039                     Ok(()) => eprintln!("patina-greeter: wrote {}", shot.path.display()),
   1040                     Err(e) => eprintln!("patina-greeter: can't save {}: {e}", shot.path.display()),
   1041                 }
   1042                 self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
   1043                 return;
   1044             }
   1045         }
   1046         if !shot.asked && shot.started.elapsed() > Duration::from_millis(1200) {
   1047             shot.asked = true;
   1048             self.ctx
   1049                 .send_viewport_cmd(egui::ViewportCommand::Screenshot(Default::default()));
   1050         }
   1051     }
   1052 }
   1053 
   1054 /// `PATINA_SKIN` names one for a try (as patina-hud's does); otherwise the desktop's own.
   1055 fn pick_skin() -> Skin {
   1056     let (skins, errors) = skin::load_all(skin::BUILT_IN, &[]);
   1057     for e in errors {
   1058         eprintln!("patina-greeter: skin: {e}");
   1059     }
   1060     let wanted = std::env::var("PATINA_SKIN").unwrap_or_else(|_| HOME_SKIN.into());
   1061     let find = |name: &str| skins.iter().find(|s| s.name == name).cloned();
   1062     find(&wanted)
   1063         .or_else(|| find(HOME_SKIN))
   1064         .unwrap_or_else(Skin::default_skin)
   1065 }
   1066 
   1067 /// A user in a round: the first letter of their name on the skin's accent, a ring when chosen.
   1068 /// (Pictures come with the real backend: AccountsService knows where each one is.)
   1069 fn avatar(ui: &mut Ui, name: &str, side: f32, chosen: bool) -> egui::Response {
   1070     let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::click());
   1071     let v = ui.visuals();
   1072     let painter = ui.painter();
   1073     let fill = if chosen {
   1074         v.selection.bg_fill
   1075     } else {
   1076         v.selection.bg_fill.gamma_multiply(0.45)
   1077     };
   1078     painter.circle_filled(rect.center(), side / 2.0, fill);
   1079     if chosen {
   1080         painter.circle_stroke(
   1081             rect.center(),
   1082             side / 2.0 + 4.0,
   1083             Stroke::new(2.0, v.selection.bg_fill),
   1084         );
   1085     }
   1086     let initial = name
   1087         .chars()
   1088         .next()
   1089         .map_or(String::new(), |c| c.to_uppercase().to_string());
   1090     painter.text(
   1091         rect.center(),
   1092         Align2::CENTER_CENTER,
   1093         initial,
   1094         FontId::proportional(side * 0.45),
   1095         v.selection.stroke.color,
   1096     );
   1097     response
   1098 }
   1099 
   1100 /// One time zone in the list: the chosen one on the accent, the one under the pointer lightly.
   1101 fn zone_row(ui: &mut Ui, text: &str, chosen: bool) -> egui::Response {
   1102     list_row(ui, text, "", chosen)
   1103 }
   1104 
   1105 /// A row of a list: the text in the middle, or at the left with `detail` at the right; the chosen
   1106 /// one on the accent, the one under the pointer lightly.
   1107 fn list_row(ui: &mut Ui, text: &str, detail: &str, chosen: bool) -> egui::Response {
   1108     let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click());
   1109     let v = ui.visuals().clone();
   1110     if response.hovered() {
   1111         ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
   1112     }
   1113     let fill = if chosen {
   1114         Some(v.selection.bg_fill)
   1115     } else if response.hovered() {
   1116         Some(v.widgets.hovered.weak_bg_fill)
   1117     } else {
   1118         None
   1119     };
   1120     let painter = ui.painter();
   1121     if let Some(fill) = fill {
   1122         painter.rect_filled(rect, egui::CornerRadius::same(8), fill);
   1123     }
   1124     let ink = if chosen {
   1125         v.selection.stroke.color
   1126     } else {
   1127         v.text_color()
   1128     };
   1129     if detail.is_empty() {
   1130         painter.text(
   1131             rect.center(),
   1132             Align2::CENTER_CENTER,
   1133             text,
   1134             FontId::proportional(15.0),
   1135             ink,
   1136         );
   1137     } else {
   1138         painter.text(
   1139             rect.left_center() + vec2(14.0, 0.0),
   1140             Align2::LEFT_CENTER,
   1141             text,
   1142             FontId::proportional(15.0),
   1143             ink,
   1144         );
   1145         painter.text(
   1146             rect.right_center() - vec2(14.0, 0.0),
   1147             Align2::RIGHT_CENTER,
   1148             detail,
   1149             FontId::proportional(13.0),
   1150             ink.gamma_multiply(0.7),
   1151         );
   1152     }
   1153     response
   1154 }
   1155 
   1156 /// The setup's button, as big as the fields above it: a pill in the accent, as the login's arrow
   1157 /// sits in its pill. It breaks Patina's button size on purpose (the user's choice, ADR-0013):
   1158 /// those are 24 px high, for rows in dialogs, and beside 46 px fields they look lost. Restart
   1159 /// and Shut down are Patina's own.
   1160 fn wide_button(ui: &mut Ui, text: &str, ready: bool, busy: bool) -> egui::Response {
   1161     let visuals = ui.visuals().clone();
   1162     let (rect, response) = ui.allocate_exact_size(field::SIZE, Sense::click());
   1163     if ready && response.hovered() {
   1164         ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
   1165     }
   1166     let (fill, ink) = if ready {
   1167         let fill = if response.hovered() {
   1168             visuals.selection.bg_fill.gamma_multiply(0.85)
   1169         } else {
   1170             visuals.selection.bg_fill
   1171         };
   1172         (fill, visuals.selection.stroke.color)
   1173     } else {
   1174         (
   1175             visuals.widgets.inactive.weak_bg_fill,
   1176             visuals.weak_text_color(),
   1177         )
   1178     };
   1179     let painter = ui.painter();
   1180     let radius = egui::CornerRadius::same((field::SIZE.y / 2.0) as u8);
   1181     painter.rect_filled(rect, radius, fill);
   1182     let label = if busy { "Setting up…" } else { text };
   1183     painter.text(
   1184         rect.center(),
   1185         Align2::CENTER_CENTER,
   1186         label,
   1187         FontId::proportional(17.0),
   1188         ink,
   1189     );
   1190     response
   1191 }
   1192 
   1193 /// The arrow button that sends the password, a spinner while it is checked.
   1194 fn arrow(ui: &mut Ui, button: egui::Rect, ready: bool, checking: bool) -> egui::Response {
   1195     let visuals = ui.visuals().clone();
   1196     let time = ui.input(|i| i.time);
   1197     let response = ui.interact(button, ui.id().with("send"), Sense::click());
   1198     if ready && response.hovered() {
   1199         ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
   1200     }
   1201     let (fill, ink): (Color32, Color32) = if ready {
   1202         let fill = if response.hovered() {
   1203             visuals.selection.bg_fill.gamma_multiply(0.85)
   1204         } else {
   1205             visuals.selection.bg_fill
   1206         };
   1207         (fill, visuals.selection.stroke.color)
   1208     } else {
   1209         (
   1210             visuals.widgets.inactive.weak_bg_fill,
   1211             visuals.weak_text_color(),
   1212         )
   1213     };
   1214     let painter = ui.painter();
   1215     painter.circle_filled(button.center(), button.width() / 2.0, fill);
   1216     let c = button.center();
   1217     if checking {
   1218         let angle = time as f32 * 6.0;
   1219         for k in 0..3 {
   1220             let a = angle - k as f32 * 0.5;
   1221             painter.circle_filled(
   1222                 c + vec2(a.cos(), a.sin()) * 8.0,
   1223                 2.6 - k as f32 * 0.7,
   1224                 ink.gamma_multiply(1.0 - k as f32 * 0.3),
   1225             );
   1226         }
   1227     } else {
   1228         let line = Stroke::new(2.0, ink);
   1229         painter.line_segment([c - vec2(6.0, 0.0), c + vec2(6.0, 0.0)], line);
   1230         painter.line_segment([c + vec2(6.0, 0.0), c + vec2(1.0, -5.0)], line);
   1231         painter.line_segment([c + vec2(6.0, 0.0), c + vec2(1.0, 5.0)], line);
   1232     }
   1233     response
   1234 }
   1235 
   1236 #[cfg(test)]
   1237 mod tests {
   1238     use super::*;
   1239     use crate::backend::{MOCK_BROKEN, MOCK_PASSWORD, Mock};
   1240 
   1241     fn app(mock: Mock) -> App {
   1242         App::with_context(
   1243             egui::Context::default(),
   1244             Skin::default_skin(),
   1245             Arc::new(mock),
   1246         )
   1247     }
   1248 
   1249     fn quick(users: &[(&str, &str)]) -> App {
   1250         app(Mock::new(users, Duration::ZERO))
   1251     }
   1252 
   1253     /// A fresh machine, on the setup's last step: the account form.
   1254     fn at_account() -> App {
   1255         let mut a = quick(&[]);
   1256         a.step = Step::Account;
   1257         a
   1258     }
   1259 
   1260     fn typed(text: &str) -> egui::Event {
   1261         egui::Event::Text(text.into())
   1262     }
   1263 
   1264     fn key(key: egui::Key, shift: bool) -> egui::Event {
   1265         egui::Event::Key {
   1266             key,
   1267             physical_key: None,
   1268             pressed: true,
   1269             repeat: false,
   1270             modifiers: egui::Modifiers {
   1271                 shift,
   1272                 ..Default::default()
   1273             },
   1274         }
   1275     }
   1276 
   1277     /// Waits for the worker thread, polling as a frame would.
   1278     fn settle(app: &mut App) {
   1279         for _ in 0..400 {
   1280             app.poll();
   1281             if app.status != Status::Checking || app.finished {
   1282                 return;
   1283             }
   1284             std::thread::sleep(Duration::from_millis(5));
   1285         }
   1286         panic!("the worker never answered");
   1287     }
   1288 
   1289     #[test]
   1290     fn it_starts_on_the_screen_the_machine_needs() {
   1291         assert_eq!(quick(&[("alice", "Alice Example")]).screen, Screen::Login);
   1292         assert_eq!(quick(&[]).screen, Screen::Setup);
   1293     }
   1294 
   1295     #[test]
   1296     fn the_right_password_logs_in_and_finishes() {
   1297         let mut a = quick(&[("alice", "Alice Example")]);
   1298         a.handle_keys(&[typed(MOCK_PASSWORD), key(egui::Key::Enter, false)]);
   1299         assert_eq!(a.status, Status::Checking);
   1300         assert!(
   1301             a.login.text.is_empty(),
   1302             "the password left the box when it was sent"
   1303         );
   1304         settle(&mut a);
   1305         assert!(a.finished);
   1306     }
   1307 
   1308     #[test]
   1309     fn a_wrong_password_says_so_and_can_be_tried_again() {
   1310         let mut a = quick(&[("alice", "Alice Example")]);
   1311         a.handle_keys(&[typed("nope"), key(egui::Key::Enter, false)]);
   1312         settle(&mut a);
   1313         assert_eq!(a.status, Status::Wrong);
   1314         assert!(!a.finished);
   1315         a.handle_keys(&[typed("s")]);
   1316         assert_eq!(a.status, Status::Typing, "typing again clears the message");
   1317     }
   1318 
   1319     #[test]
   1320     fn a_broken_login_service_is_shown_as_it_is() {
   1321         let mut a = quick(&[("alice", "Alice Example")]);
   1322         a.handle_keys(&[typed(MOCK_BROKEN), key(egui::Key::Enter, false)]);
   1323         settle(&mut a);
   1324         assert_eq!(
   1325             a.status,
   1326             Status::Problem("Can't reach the login service".into())
   1327         );
   1328     }
   1329 
   1330     #[test]
   1331     fn arrows_move_between_users_and_clear_the_box() {
   1332         let mut a = quick(&[("alice", "Alice"), ("bob", "Bob")]);
   1333         a.handle_keys(&[typed("abc")]);
   1334         a.handle_keys(&[key(egui::Key::ArrowRight, false)]);
   1335         assert_eq!(a.selected, 1);
   1336         assert!(a.login.text.is_empty());
   1337         a.handle_keys(&[key(egui::Key::ArrowRight, false)]);
   1338         assert_eq!(a.selected, 0, "it wraps");
   1339     }
   1340 
   1341     #[test]
   1342     fn the_setup_suggests_a_user_name_until_one_is_typed() {
   1343         let mut a = at_account();
   1344         a.handle_keys(&[typed("Alice Example")]);
   1345         assert_eq!(a.fields[1].text, "alice");
   1346         a.handle_keys(&[key(egui::Key::Tab, false), typed("x")]);
   1347         assert_eq!(
   1348             a.fields[1].text, "alicex",
   1349             "typing in it keeps what was suggested"
   1350         );
   1351         a.handle_keys(&[key(egui::Key::Tab, true), typed("!")]);
   1352         assert_eq!(
   1353             a.fields[1].text, "alicex",
   1354             "and it no longer follows the full name"
   1355         );
   1356     }
   1357 
   1358     #[test]
   1359     fn tab_and_enter_walk_the_fields_and_wrap() {
   1360         let mut a = at_account();
   1361         assert_eq!(a.focus, Slot::FullName);
   1362         a.handle_keys(&[key(egui::Key::Tab, false)]);
   1363         assert_eq!(a.focus, Slot::Username);
   1364         a.handle_keys(&[key(egui::Key::Enter, false)]);
   1365         assert_eq!(a.focus, Slot::Password);
   1366         a.handle_keys(&[
   1367             key(egui::Key::Tab, true),
   1368             key(egui::Key::Tab, true),
   1369             key(egui::Key::Tab, true),
   1370         ]);
   1371         assert_eq!(a.focus, Slot::Confirm, "Shift+Tab goes back and wraps");
   1372     }
   1373 
   1374     #[test]
   1375     fn the_setup_will_not_submit_a_form_with_a_problem() {
   1376         let mut a = at_account();
   1377         a.handle_keys(&[
   1378             typed("Alice Example"),
   1379             key(egui::Key::Tab, false),
   1380             key(egui::Key::Tab, false),
   1381         ]);
   1382         a.handle_keys(&[
   1383             typed("secret"),
   1384             key(egui::Key::Tab, false),
   1385             typed("secre"),
   1386             key(egui::Key::Enter, false),
   1387         ]);
   1388         assert_eq!(
   1389             a.status,
   1390             Status::Typing,
   1391             "the passwords differ, so nothing was sent"
   1392         );
   1393         assert_eq!(a.screen, Screen::Setup);
   1394         assert_eq!(a.form().problem(), Some("The passwords don't match"));
   1395     }
   1396 
   1397     #[test]
   1398     fn the_first_run_makes_the_account_and_logs_it_in() {
   1399         let mut a = at_account();
   1400         a.handle_keys(&[typed("Alice Example")]);
   1401         a.handle_keys(&[
   1402             key(egui::Key::Tab, false),
   1403             key(egui::Key::Tab, false),
   1404             typed(MOCK_PASSWORD),
   1405         ]);
   1406         a.handle_keys(&[
   1407             key(egui::Key::Tab, false),
   1408             typed(MOCK_PASSWORD),
   1409             key(egui::Key::Enter, false),
   1410         ]);
   1411         assert_eq!(a.status, Status::Checking);
   1412         settle(&mut a); // the account is made, and the login for it started
   1413         assert_eq!(
   1414             a.screen,
   1415             Screen::Login,
   1416             "from now on this machine has someone to log in"
   1417         );
   1418         assert_eq!(a.users[a.selected].name, "alice");
   1419         settle(&mut a);
   1420         assert!(
   1421             a.finished,
   1422             "and it was logged in with the password just chosen"
   1423         );
   1424         assert!(
   1425             a.fields[2].text.is_empty() && a.fields[3].text.is_empty(),
   1426             "the passwords are gone"
   1427         );
   1428     }
   1429 
   1430     #[test]
   1431     fn a_fresh_machine_starts_on_the_clock_with_the_zone_it_is_on() {
   1432         let a = quick(&[]);
   1433         assert_eq!((a.screen, a.step), (Screen::Setup, Step::Clock));
   1434         assert_eq!(
   1435             a.zone, "UTC",
   1436             "what the machine is on is chosen to begin with"
   1437         );
   1438         assert!(a.zones.iter().any(|z| z == "Europe/Stockholm"));
   1439     }
   1440 
   1441     #[test]
   1442     fn searching_the_zones_finds_a_city_by_any_words_of_it() {
   1443         let a = quick(&[]);
   1444         let find =
   1445             |q: &str| -> Vec<String> { zones_matching(&a.zones, q).into_iter().cloned().collect() };
   1446         assert_eq!(find("stock"), ["Europe/Stockholm"]);
   1447         assert_eq!(
   1448             find("NEW york"),
   1449             ["America/New_York"],
   1450             "case and spaces for underscores"
   1451         );
   1452         assert_eq!(find("europe").len(), 3);
   1453         assert_eq!(
   1454             find("").len(),
   1455             a.zones.len(),
   1456             "nothing typed shows them all"
   1457         );
   1458         assert!(find("atlantis").is_empty());
   1459     }
   1460 
   1461     #[test]
   1462     fn continuing_sets_the_zone_and_goes_to_the_name() {
   1463         let mut a = quick(&[]);
   1464         a.zone = "Europe/Stockholm".into();
   1465         a.handle_keys(&[key(egui::Key::Enter, false)]);
   1466         assert_eq!(a.status, Status::Checking);
   1467         settle(&mut a);
   1468         assert_eq!(a.step, Step::Name);
   1469         assert_eq!(a.status, Status::Typing);
   1470         assert_eq!(
   1471             a.backend.timezone(),
   1472             "Europe/Stockholm",
   1473             "the machine's zone changed"
   1474         );
   1475     }
   1476 
   1477     #[test]
   1478     fn continuing_with_the_zone_unchanged_asks_nothing_of_the_system() {
   1479         let mut a = quick(&[]);
   1480         a.submit_clock();
   1481         assert_eq!(a.status, Status::Typing, "no worker was started");
   1482         assert_eq!(a.step, Step::Name);
   1483     }
   1484 
   1485     #[test]
   1486     fn a_zone_the_system_refuses_is_shown_and_the_step_stays() {
   1487         let mut a = quick(&[]);
   1488         a.zone = "Mars/Olympus_Mons".into();
   1489         a.submit_clock();
   1490         settle(&mut a);
   1491         assert_eq!(a.step, Step::Clock);
   1492         assert!(matches!(&a.status, Status::Problem(e) if e.contains("Mars/Olympus_Mons")));
   1493         assert_eq!(a.backend.timezone(), "UTC");
   1494     }
   1495 
   1496     #[test]
   1497     fn skip_and_back_walk_the_steps_without_changing_anything() {
   1498         let mut a = quick(&[]);
   1499         a.go_on();
   1500         a.go_on();
   1501         assert_eq!(a.step, Step::Account);
   1502         a.go_on();
   1503         assert_eq!(a.step, Step::Account, "nothing comes after the account");
   1504         assert_eq!(a.backend.timezone(), "UTC");
   1505         assert_eq!(a.backend.hostname(), "sectorf");
   1506         a.go_back();
   1507         assert_eq!(a.step, Step::Name);
   1508         a.go_back();
   1509         assert_eq!(a.step, Step::Clock);
   1510         a.go_back();
   1511         assert_eq!(
   1512             a.step,
   1513             Step::Clock,
   1514             "there is nothing before the first step"
   1515         );
   1516     }
   1517 
   1518     /// A fresh machine with Wi-Fi: it opens on the Wi-Fi step.
   1519     fn with_wifi() -> App {
   1520         app(Mock::new(&[], Duration::ZERO).with_wifi())
   1521     }
   1522 
   1523     /// Polls as frames would until the list of networks is there.
   1524     fn wait_for_networks(a: &mut App) {
   1525         a.scan();
   1526         for _ in 0..400 {
   1527             a.poll();
   1528             if !a.wifi_scanning {
   1529                 return;
   1530             }
   1531             std::thread::sleep(Duration::from_millis(5));
   1532         }
   1533         panic!("the scan never answered");
   1534     }
   1535 
   1536     #[test]
   1537     fn a_machine_with_wifi_starts_on_it_and_one_without_does_not() {
   1538         let a = with_wifi();
   1539         assert_eq!(a.step, Step::Wifi);
   1540         assert_eq!(a.steps.len(), 4);
   1541         assert_eq!(quick(&[]).step, Step::Clock, "no Wi-Fi, no Wi-Fi step");
   1542         assert_eq!(quick(&[]).steps.len(), 3);
   1543     }
   1544 
   1545     #[test]
   1546     fn the_networks_come_one_per_name_strongest_first() {
   1547         let mut a = with_wifi();
   1548         wait_for_networks(&mut a);
   1549         let names: Vec<&str> = a.networks.iter().map(|n| n.ssid.as_str()).collect();
   1550         assert_eq!(
   1551             names,
   1552             ["Home-5G", "CoffeeShop", "Neighbour", "Office-Guest"]
   1553         );
   1554         assert_eq!(
   1555             a.networks[0].strength, 92,
   1556             "the stronger of the two Home-5G"
   1557         );
   1558     }
   1559 
   1560     #[test]
   1561     fn an_open_network_joins_without_a_password_and_goes_on() {
   1562         let mut a = with_wifi();
   1563         wait_for_networks(&mut a);
   1564         a.wifi_pick = Some("CoffeeShop".into());
   1565         assert!(a.wifi_ready());
   1566         a.handle_keys(&[key(egui::Key::Enter, false)]);
   1567         assert_eq!(a.status, Status::Checking);
   1568         settle(&mut a);
   1569         assert_eq!(a.step, Step::Clock);
   1570     }
   1571 
   1572     #[test]
   1573     fn a_secured_network_needs_its_password_before_it_can_be_joined() {
   1574         let mut a = with_wifi();
   1575         wait_for_networks(&mut a);
   1576         a.wifi_pick = Some("Home-5G".into());
   1577         assert!(!a.wifi_ready(), "no password yet");
   1578         a.handle_keys(&[typed(MOCK_PASSWORD)]);
   1579         assert!(a.wifi_ready());
   1580         assert!(
   1581             a.fields.iter().all(|f| f.text.is_empty()),
   1582             "what is typed here does not reach the account form"
   1583         );
   1584     }
   1585 
   1586     #[test]
   1587     fn the_right_password_joins_and_the_password_is_gone() {
   1588         let mut a = with_wifi();
   1589         wait_for_networks(&mut a);
   1590         a.wifi_pick = Some("Home-5G".into());
   1591         a.handle_keys(&[typed(MOCK_PASSWORD), key(egui::Key::Enter, false)]);
   1592         assert!(
   1593             a.wifi_field.text.is_empty(),
   1594             "it left the box when it was sent"
   1595         );
   1596         settle(&mut a);
   1597         assert_eq!(a.step, Step::Clock);
   1598         assert!(a.wifi_field.text.is_empty());
   1599     }
   1600 
   1601     #[test]
   1602     fn a_wrong_password_is_shown_and_the_step_stays_with_the_box_empty() {
   1603         let mut a = with_wifi();
   1604         wait_for_networks(&mut a);
   1605         a.wifi_pick = Some("Home-5G".into());
   1606         a.handle_keys(&[typed("nope"), key(egui::Key::Enter, false)]);
   1607         settle(&mut a);
   1608         assert_eq!(a.step, Step::Wifi);
   1609         assert!(matches!(&a.status, Status::Problem(e) if e.contains("password was not accepted")));
   1610         assert!(a.wifi_field.text.is_empty());
   1611         assert!(!a.wifi_ready(), "the password has to be typed again");
   1612     }
   1613 
   1614     #[test]
   1615     fn skip_and_back_pass_through_the_wifi_step() {
   1616         let mut a = with_wifi();
   1617         a.go_on();
   1618         assert_eq!(a.step, Step::Clock);
   1619         a.go_back();
   1620         assert_eq!(a.step, Step::Wifi);
   1621         a.go_back();
   1622         assert_eq!(a.step, Step::Wifi, "nothing before the first step");
   1623     }
   1624 
   1625     /// A fresh machine, on the name step.
   1626     fn at_name() -> App {
   1627         let mut a = quick(&[]);
   1628         a.step = Step::Name;
   1629         a
   1630     }
   1631 
   1632     #[test]
   1633     fn the_name_starts_as_the_one_the_machine_has() {
   1634         assert_eq!(at_name().host, "sectorf");
   1635     }
   1636 
   1637     #[test]
   1638     fn continuing_sets_the_name_in_lower_case_and_goes_to_the_account() {
   1639         let mut a = at_name();
   1640         a.host = "  Alices-Laptop ".into();
   1641         a.handle_keys(&[key(egui::Key::Enter, false)]);
   1642         assert_eq!(a.status, Status::Checking);
   1643         settle(&mut a);
   1644         assert_eq!(a.step, Step::Account);
   1645         assert_eq!(a.backend.hostname(), "alices-laptop");
   1646     }
   1647 
   1648     #[test]
   1649     fn a_name_that_is_not_a_host_name_is_not_sent() {
   1650         let mut a = at_name();
   1651         for bad in ["", "my laptop", "-x", "a_b"] {
   1652             a.host = bad.into();
   1653             a.submit_name();
   1654             assert_eq!(a.status, Status::Typing, "{bad:?} started a worker");
   1655             assert_eq!(a.step, Step::Name);
   1656         }
   1657         assert_eq!(a.backend.hostname(), "sectorf");
   1658     }
   1659 
   1660     #[test]
   1661     fn the_same_name_asks_nothing_of_the_system() {
   1662         let mut a = at_name();
   1663         a.submit_name();
   1664         assert_eq!(a.status, Status::Typing);
   1665         assert_eq!(a.step, Step::Account);
   1666     }
   1667 
   1668     #[test]
   1669     fn a_name_the_system_refuses_is_shown_and_the_step_stays() {
   1670         let mut a = at_name();
   1671         a.host = MOCK_BROKEN.into();
   1672         a.submit_name();
   1673         settle(&mut a);
   1674         assert_eq!(a.step, Step::Name);
   1675         assert!(matches!(&a.status, Status::Problem(e) if e.contains("hostnamed")));
   1676         assert_eq!(a.backend.hostname(), "sectorf");
   1677     }
   1678 
   1679     #[test]
   1680     fn typing_in_the_search_does_not_reach_the_account_fields() {
   1681         let mut a = quick(&[]);
   1682         a.handle_keys(&[typed("sto")]);
   1683         assert!(a.fields.iter().all(|f| f.text.is_empty()));
   1684     }
   1685 
   1686     #[test]
   1687     fn both_screens_draw_without_trouble() {
   1688         for users in [&[("alice", "Alice Example"), ("bob", "Bob")][..], &[][..]] {
   1689             let mut a = quick(users);
   1690             let ctx = a.ctx.clone();
   1691             egui_extras::install_image_loaders(&ctx);
   1692             for what in [
   1693                 "",
   1694                 "typing",
   1695                 "wrong",
   1696                 "problem",
   1697                 "filled",
   1698                 "clock",
   1699                 "name",
   1700                 "name-problem",
   1701                 "wifi",
   1702                 "wifi-problem",
   1703             ] {
   1704                 a.demo(what);
   1705                 let _ = ctx.run_ui(egui::RawInput::default(), |ui| a.draw(ui));
   1706             }
   1707         }
   1708     }
   1709 }