sector-f-linux

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

field.rs (7751B)


      1 //! The pill a text goes in, drawn the way patina-lock draws its password box: a ring while it has
      2 //! the keys, a caret that blinks, dots for a secret. It is not an egui `TextEdit`, whose undo
      3 //! history would keep copies of a password: keys are read from egui's events and the text lives
      4 //! here, wiped when cleared.
      5 //!
      6 //! Editing is at the end only (type, Backspace, Ctrl+Backspace, Ctrl+U or Escape to clear), which
      7 //! is all a name or a password needs here.
      8 
      9 use egui::{Align2, CornerRadius, FontId, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
     10 
     11 use crate::model::{MAX_PASSWORD, wipe};
     12 
     13 pub const SIZE: egui::Vec2 = vec2(340.0, 46.0);
     14 const MAX_TEXT: usize = 128;
     15 
     16 pub struct Field {
     17     pub text: String,
     18     pub secret: bool,
     19     pub hint: &'static str,
     20 }
     21 
     22 /// How the ring is drawn.
     23 #[derive(Clone, Copy, PartialEq)]
     24 pub enum Tone {
     25     Normal,
     26     Wrong,
     27     /// Dimmed, while something is being checked.
     28     Busy,
     29 }
     30 
     31 impl Field {
     32     pub fn new(hint: &'static str, secret: bool) -> Self {
     33         let room = if secret { MAX_PASSWORD } else { MAX_TEXT };
     34         Self {
     35             text: String::with_capacity(room),
     36             secret,
     37             hint,
     38         }
     39     }
     40 
     41     fn limit(&self) -> usize {
     42         if self.secret { MAX_PASSWORD } else { MAX_TEXT }
     43     }
     44 
     45     pub fn clear(&mut self) {
     46         if self.secret {
     47             wipe(&mut self.text);
     48         } else {
     49             self.text.clear();
     50         }
     51     }
     52 
     53     /// Applies the keys typed this frame; true when the text changed.
     54     pub fn type_into(&mut self, events: &[egui::Event]) -> bool {
     55         let before = self.text.len();
     56         let mut changed = false;
     57         for event in events {
     58             match event {
     59                 egui::Event::Text(text) => {
     60                     let text: String = text.chars().filter(|c| !c.is_control()).collect();
     61                     if self.text.len() + text.len() <= self.limit() && !text.is_empty() {
     62                         self.text.push_str(&text);
     63                         changed = true;
     64                     }
     65                 }
     66                 egui::Event::Key {
     67                     key,
     68                     pressed: true,
     69                     modifiers,
     70                     ..
     71                 } => match key {
     72                     egui::Key::Backspace if modifiers.ctrl => {
     73                         self.clear();
     74                         changed = true;
     75                     }
     76                     egui::Key::Backspace => {
     77                         changed |= self.text.pop().is_some();
     78                     }
     79                     egui::Key::Escape => {
     80                         changed |= !self.text.is_empty();
     81                         self.clear();
     82                     }
     83                     egui::Key::U if modifiers.ctrl => {
     84                         changed |= !self.text.is_empty();
     85                         self.clear();
     86                     }
     87                     _ => {}
     88                 },
     89                 _ => {}
     90             }
     91         }
     92         changed || self.text.len() != before
     93     }
     94 
     95     /// Draws the pill and answers clicks on it. `trailing` is the width kept clear on the right,
     96     /// for a button the caller draws over it (the login's arrow).
     97     pub fn show(
     98         &self,
     99         ui: &mut Ui,
    100         size: egui::Vec2,
    101         focused: bool,
    102         tone: Tone,
    103         trailing: f32,
    104     ) -> Response {
    105         let visuals = ui.visuals().clone();
    106         let time = ui.input(|i| i.time);
    107         let (rect, response) = ui.allocate_exact_size(size, Sense::click());
    108         let radius = CornerRadius::same((size.y / 2.0) as u8);
    109         let painter = ui.painter().clone();
    110         painter.rect_filled(rect, radius, visuals.extreme_bg_color);
    111         let ring = match (tone, focused) {
    112             (Tone::Wrong, _) => Stroke::new(2.0, visuals.error_fg_color),
    113             (_, true) => Stroke::new(2.0, visuals.selection.bg_fill),
    114             (_, false) => Stroke::new(1.0, visuals.widgets.noninteractive.bg_stroke.color),
    115         };
    116         painter.rect_stroke(rect, radius, ring, StrokeKind::Inside);
    117 
    118         let busy = tone == Tone::Busy;
    119         let left = rect.left() + 22.0;
    120         let room = rect.right() - trailing - 14.0 - left;
    121         let centre = rect.center().y;
    122         let ink = visuals
    123             .text_color()
    124             .gamma_multiply(if busy { 0.45 } else { 1.0 });
    125         let count = self.text.chars().count();
    126         let mut caret_x = left - 2.0;
    127 
    128         if self.secret {
    129             // Dots from the left, the newest last.
    130             let step = 15.0;
    131             let fit = ((room / step) as usize).max(1);
    132             let shown = count.min(fit);
    133             for i in 0..shown {
    134                 painter.circle_filled(pos2(left + 4.0 + i as f32 * step, centre), 4.5, ink);
    135             }
    136             caret_x = left - 2.0 + shown.min(fit) as f32 * step;
    137         } else if count > 0 {
    138             // The text, the end of it in view when it is longer than the room.
    139             let galley = painter.layout_no_wrap(self.text.clone(), FontId::proportional(16.0), ink);
    140             let offset = (room - galley.size().x).min(0.0);
    141             let clipped = painter.with_clip_rect(egui::Rect::from_min_max(
    142                 pos2(left - 4.0, rect.top()),
    143                 pos2(left + room + 4.0, rect.bottom()),
    144             ));
    145             clipped.galley(
    146                 pos2(left + offset, centre - galley.size().y / 2.0),
    147                 galley.clone(),
    148                 ink,
    149             );
    150             caret_x = left + offset + galley.size().x + 1.0;
    151         }
    152         if count == 0 {
    153             painter.text(
    154                 pos2(left + 2.0, centre),
    155                 Align2::LEFT_CENTER,
    156                 self.hint,
    157                 FontId::proportional(16.0),
    158                 visuals.weak_text_color(),
    159             );
    160         }
    161         if focused && !busy && (time * 2.0) as i64 % 2 == 0 {
    162             painter.line_segment(
    163                 [
    164                     pos2(caret_x, centre - size.y * 0.22),
    165                     pos2(caret_x, centre + size.y * 0.22),
    166                 ],
    167                 Stroke::new(1.5, visuals.text_color()),
    168             );
    169         }
    170         response
    171     }
    172 }
    173 
    174 #[cfg(test)]
    175 mod tests {
    176     use super::*;
    177 
    178     fn typed(text: &str) -> egui::Event {
    179         egui::Event::Text(text.into())
    180     }
    181 
    182     fn key(key: egui::Key, ctrl: bool) -> egui::Event {
    183         egui::Event::Key {
    184             key,
    185             physical_key: None,
    186             pressed: true,
    187             repeat: false,
    188             modifiers: egui::Modifiers {
    189                 ctrl,
    190                 ..Default::default()
    191             },
    192         }
    193     }
    194 
    195     #[test]
    196     fn typing_appends_and_backspace_removes_from_the_end() {
    197         let mut f = Field::new("Name", false);
    198         assert!(f.type_into(&[typed("Al"), typed("ice")]));
    199         assert_eq!(f.text, "Alice");
    200         assert!(f.type_into(&[key(egui::Key::Backspace, false)]));
    201         assert_eq!(f.text, "Alic");
    202         assert!(!Field::new("x", false).type_into(&[key(egui::Key::Backspace, false)]));
    203     }
    204 
    205     #[test]
    206     fn escape_and_ctrl_u_clear_and_a_secret_keeps_its_room() {
    207         let mut f = Field::new("Password", true);
    208         f.type_into(&[typed("hunter2")]);
    209         assert!(f.type_into(&[key(egui::Key::Escape, false)]));
    210         assert!(f.text.is_empty());
    211         assert!(f.text.capacity() >= MAX_PASSWORD);
    212         f.type_into(&[typed("again"), key(egui::Key::U, true)]);
    213         assert!(f.text.is_empty());
    214     }
    215 
    216     #[test]
    217     fn control_characters_are_dropped_and_the_length_is_capped() {
    218         let mut f = Field::new("Name", false);
    219         f.type_into(&[typed("a\tb\nc")]);
    220         assert_eq!(f.text, "abc");
    221         f.type_into(&[typed(&"x".repeat(500))]);
    222         assert!(f.text.len() <= MAX_TEXT);
    223     }
    224 }