Guide API
Skip to main content

tvision_rs/widgets/
reveal_eye.rs

1//! `RevealEye`, the reveal toggle for masked input lines (documented on the type).
2
3use std::time::Duration;
4
5use crate::command::Command;
6use crate::event::Key;
7use crate::theme::SurfaceRoles;
8use crate::timer::TimerId;
9use crate::view::{Context, DrawCtx, View, ViewState};
10use crate::{Event, Options, Point, Rect, Role};
11
12/// Behaviour of a [`RevealEye`]. The eye glyphs are theme-controlled
13/// (`Glyphs::reveal_eye_hidden` / `reveal_eye_revealed`), so this config carries
14/// only the interaction knobs.
15#[derive(Debug, Clone, Copy)]
16pub struct RevealEyeConfig {
17    /// Timed-peek duration for a non-sticky Space press. Default 1 s.
18    pub peek: Duration,
19    /// When true, Space toggles a latched reveal instead of a timed peek.
20    pub sticky: bool,
21}
22
23impl Default for RevealEyeConfig {
24    fn default() -> Self {
25        RevealEyeConfig {
26            peek: Duration::from_secs(1),
27            sticky: false,
28        }
29    }
30}
31
32/// A one-cell focusable "reveal" eye for masked [`InputLine`](super::InputLine)
33/// fields.
34///
35/// Drives a paired field's reveal: press-and-hold the mouse for a momentary
36/// peek, or (while focused) press Space for a 1 s timed peek, or, when
37/// configured `sticky`, toggle a latched reveal. It carries no secret text; it
38/// only tracks its own intent and broadcasts [`Command::REVEAL_CHANGED`] so the
39/// owning [`MaskedInput`](super::MaskedInput) can apply it.
40///
41/// # Turbo Vision heritage
42/// **tvision-rs extension**: no Turbo Vision counterpart.
43pub struct RevealEye {
44    pub state: ViewState,
45    cfg: RevealEyeConfig,
46    /// Mouse button held on the eye (momentary peek).
47    held: bool,
48    /// Latched reveal (sticky mode).
49    sticky_on: bool,
50    /// Live one-shot peek timer (non-sticky Space), if any.
51    pub(crate) peek_timer: Option<TimerId>,
52    /// Absolute origin cached each `draw` for the mouse-track capture.
53    abs_origin: Point,
54}
55
56impl RevealEye {
57    /// Build a one-cell eye. `bounds` should be 1×1.
58    pub fn new(bounds: Rect, cfg: RevealEyeConfig) -> Self {
59        let mut state = ViewState::new(bounds);
60        state.options = Options {
61            selectable: true,
62            first_click: true,
63            ..Default::default()
64        };
65        RevealEye {
66            state,
67            cfg,
68            held: false,
69            sticky_on: false,
70            peek_timer: None,
71            abs_origin: Point::new(0, 0),
72        }
73    }
74
75    /// Whether the paired field should currently show cleartext.
76    pub fn is_revealing(&self) -> bool {
77        self.held || self.sticky_on || self.peek_timer.is_some()
78    }
79
80    fn announce(&self, ctx: &mut Context) {
81        ctx.broadcast(Command::REVEAL_CHANGED, self.state.id());
82    }
83}
84
85/// [`RevealEye`]'s surface triple for [`DrawCtx::content_surface`] — mirrors
86/// [`InputLine`](super::InputLine)'s private `SURFACE_ROLES` const, which is
87/// not `pub` and so cannot be reused directly.
88const SURFACE_ROLES: SurfaceRoles = SurfaceRoles {
89    normal: Role::InputNormal,
90    surface: Role::InputSurface,
91    inactive: Role::InputInactive,
92};
93
94impl View for RevealEye {
95    fn state(&self) -> &ViewState {
96        &self.state
97    }
98    fn state_mut(&mut self) -> &mut ViewState {
99        &mut self.state
100    }
101    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
102        Some(self)
103    }
104
105    fn draw(&mut self, ctx: &mut DrawCtx) {
106        self.abs_origin = ctx.origin();
107        let color = ctx.content_surface(
108            SURFACE_ROLES,
109            self.state.state.focused,
110            self.state.options.selectable,
111        );
112        let glyph = if self.is_revealing() {
113            ctx.glyphs().reveal_eye_revealed
114        } else {
115            ctx.glyphs().reveal_eye_hidden
116        };
117        ctx.fill(Rect::new(0, 0, self.state.size.x, 1), ' ', color);
118        ctx.put_char(0, 0, glyph, color);
119    }
120
121    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
122        match ev {
123            Event::MouseDown(_) => {
124                if let Some(id) = self.state.id() {
125                    self.held = true;
126                    ctx.start_mouse_track(
127                        id,
128                        self.abs_origin,
129                        crate::capture::TrackMask::default(),
130                    );
131                    self.announce(ctx);
132                    ev.clear();
133                }
134            }
135            Event::MouseUp(_) if self.held => {
136                self.held = false;
137                self.announce(ctx);
138                ev.clear();
139            }
140            Event::KeyDown(k) if k.key == Key::Char(' ') => {
141                if self.cfg.sticky {
142                    self.sticky_on = !self.sticky_on;
143                } else {
144                    if let Some(t) = self.peek_timer.take() {
145                        ctx.kill_timer(t);
146                    }
147                    self.peek_timer = Some(ctx.set_timer(self.cfg.peek, None));
148                }
149                self.announce(ctx);
150                ev.clear();
151            }
152            Event::Timer(id) if Some(*id) == self.peek_timer => {
153                self.peek_timer = None;
154                self.announce(ctx);
155                ev.clear();
156            }
157            // Tab, arrows, and everything else pass through for field navigation.
158            _ => {}
159        }
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use crate::event::{
167        Key, KeyEvent, KeyModifiers, MouseButtons, MouseEvent, MouseEventFlags, MouseWheel,
168    };
169    use crate::timer::TimerQueue;
170    use crate::view::{Context, Deferred, ViewId};
171    use crate::{Event, Point, Rect};
172    use std::collections::VecDeque;
173
174    fn eye(sticky: bool) -> RevealEye {
175        let mut e = RevealEye::new(
176            Rect::new(0, 0, 1, 1),
177            RevealEyeConfig {
178                sticky,
179                ..Default::default()
180            },
181        );
182        e.state_mut().id = Some(ViewId::next());
183        e.state_mut().state.selected = true; // stand in for focus in a unit test
184        e
185    }
186
187    #[test]
188    fn draw_paints_the_theme_reveal_eye_glyphs() {
189        use crate::screen::Buffer;
190        use crate::theme::Theme;
191        use crate::view::DrawCtx;
192
193        let theme = Theme::classic_blue();
194        let hidden = theme.glyphs().reveal_eye_hidden;
195        let revealed = theme.glyphs().reveal_eye_revealed;
196
197        // Hidden by default: the eye paints the theme's hidden glyph, not a
198        // hardcoded one.
199        let mut e = eye(false);
200        let mut buf = Buffer::new(1, 1);
201        {
202            let mut dc = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 1, 1), Point::new(0, 0));
203            e.draw(&mut dc);
204        }
205        let row: String = (0..1).map(|x| buf.get(x, 0).symbol()).collect();
206        assert_eq!(row, hidden.to_string(), "hidden eye paints the theme glyph");
207
208        // While revealing (sticky latched on), it paints the theme's revealed glyph.
209        let mut e2 = eye(true);
210        let mut timers = TimerQueue::new();
211        with_ctx(&mut timers, |ctx| {
212            let mut sp = Event::KeyDown(KeyEvent::from(Key::Char(' ')));
213            e2.handle_event(&mut sp, ctx);
214        });
215        assert!(e2.is_revealing());
216        let mut buf2 = Buffer::new(1, 1);
217        {
218            let mut dc = DrawCtx::new(&mut buf2, &theme, Rect::new(0, 0, 1, 1), Point::new(0, 0));
219            e2.draw(&mut dc);
220        }
221        let row2: String = (0..1).map(|x| buf2.get(x, 0).symbol()).collect();
222        assert_eq!(
223            row2,
224            revealed.to_string(),
225            "revealed eye paints the theme glyph"
226        );
227    }
228
229    /// Build a fresh `Context` over the given (persistent) `TimerQueue`, run
230    /// `f`, and return the posted/broadcast events, the deferred queue, and
231    /// `f`'s result. `timers` is owned by the caller so a test can inspect it
232    /// (`len()`) after the dispatch — there is no `Deferred::SetTimer`;
233    /// `Context::set_timer`/`kill_timer` mutate the injected `TimerQueue`
234    /// directly (see `Context::set_timer`). Mirrors `button.rs`'s
235    /// `with_ctx_d` so tests can assert on both the `REVEAL_CHANGED`
236    /// broadcast and any `Deferred::PushCapture`.
237    fn with_ctx<R>(
238        timers: &mut TimerQueue,
239        f: impl FnOnce(&mut Context) -> R,
240    ) -> (Vec<Event>, Vec<Deferred>, R) {
241        let mut out: VecDeque<Event> = VecDeque::new();
242        let mut deferred: Vec<Deferred> = Vec::new();
243        let r = {
244            let mut ctx = Context::new(&mut out, timers, 0, &mut deferred);
245            f(&mut ctx)
246        };
247        (out.into_iter().collect(), deferred, r)
248    }
249
250    /// Assert `out` contains exactly one `Command::REVEAL_CHANGED` broadcast,
251    /// sourced from `id`.
252    fn assert_reveal_changed(out: &[Event], id: Option<ViewId>) {
253        let matches: Vec<_> = out
254            .iter()
255            .filter(|e| {
256                matches!(
257                    e,
258                    Event::Broadcast { command, source }
259                        if *command == Command::REVEAL_CHANGED && *source == id
260                )
261            })
262            .collect();
263        assert_eq!(
264            matches.len(),
265            1,
266            "expected exactly one REVEAL_CHANGED broadcast (source={:?}) in {:?}",
267            id,
268            out
269        );
270    }
271
272    fn mouse_down() -> Event {
273        Event::MouseDown(MouseEvent {
274            position: Point::new(0, 0),
275            buttons: MouseButtons {
276                left: true,
277                ..Default::default()
278            },
279            wheel: MouseWheel::None,
280            flags: MouseEventFlags::default(),
281            modifiers: KeyModifiers::default(),
282        })
283    }
284    fn mouse_up() -> Event {
285        Event::MouseUp(MouseEvent {
286            position: Point::new(0, 0),
287            buttons: MouseButtons {
288                left: true,
289                ..Default::default()
290            },
291            wheel: MouseWheel::None,
292            flags: MouseEventFlags::default(),
293            modifiers: KeyModifiers::default(),
294        })
295    }
296
297    #[test]
298    fn mouse_hold_reveals_until_release() {
299        let mut e = eye(false);
300        let id = e.state.id();
301        let mut timers = TimerQueue::new();
302        let (out, deferred, ()) = with_ctx(&mut timers, |ctx| {
303            let mut d = mouse_down();
304            e.handle_event(&mut d, ctx);
305        });
306        assert!(e.is_revealing(), "press reveals");
307        assert_reveal_changed(&out, id);
308        // A mouse-tracking capture must have been queued, targeting the
309        // eye's own view id (mirrors button.rs's mouse_down_inside_arms_tracking).
310        assert_eq!(deferred.len(), 1, "one capture deferred");
311        assert!(
312            matches!(deferred[0], Deferred::PushCapture(_)),
313            "deferred[0] is PushCapture"
314        );
315        if let Deferred::PushCapture(ref h) = deferred[0] {
316            assert_eq!(h.view(), id, "capture tracks the eye's own id");
317        }
318
319        let (out, _deferred, ()) = with_ctx(&mut timers, |ctx| {
320            let mut u = mouse_up();
321            e.handle_event(&mut u, ctx);
322        });
323        assert!(!e.is_revealing(), "release hides");
324        assert_reveal_changed(&out, id);
325    }
326
327    #[test]
328    fn space_non_sticky_arms_a_timed_peek() {
329        let mut e = eye(false);
330        let id = e.state.id();
331        let mut timers = TimerQueue::new();
332        let (out, _deferred, ()) = with_ctx(&mut timers, |ctx| {
333            let mut sp = Event::KeyDown(KeyEvent::from(Key::Char(' ')));
334            e.handle_event(&mut sp, ctx);
335        });
336        assert!(e.is_revealing(), "Space reveals");
337        assert_eq!(timers.len(), 1, "a one-shot timer is armed");
338        assert_reveal_changed(&out, id);
339
340        // The matching Timer hides it again.
341        let tid = e.peek_timer.expect("timer id stored");
342        let (out, _deferred, ()) = with_ctx(&mut timers, |ctx| {
343            let mut t = Event::Timer(tid);
344            e.handle_event(&mut t, ctx);
345        });
346        assert!(!e.is_revealing(), "timer expiry hides");
347        assert_reveal_changed(&out, id);
348    }
349
350    #[test]
351    fn space_sticky_toggles() {
352        let mut e = eye(true);
353        let id = e.state.id();
354        let mut timers = TimerQueue::new();
355        let (out, _deferred, ()) = with_ctx(&mut timers, |ctx| {
356            let mut sp = Event::KeyDown(KeyEvent::from(Key::Char(' ')));
357            e.handle_event(&mut sp, ctx);
358        });
359        assert!(e.is_revealing(), "sticky Space latches on");
360        assert_reveal_changed(&out, id);
361        let (out, _deferred, ()) = with_ctx(&mut timers, |ctx| {
362            let mut sp = Event::KeyDown(KeyEvent::from(Key::Char(' ')));
363            e.handle_event(&mut sp, ctx);
364        });
365        assert!(!e.is_revealing(), "sticky Space latches off");
366        assert_reveal_changed(&out, id);
367    }
368}