Guide API
Skip to main content

tvision_rs/widgets/
masked_input.rs

1//! `MaskedInput`, a masked text field with a reveal eye (documented on the type).
2
3use crate::data::FieldValue;
4use crate::event::Event;
5use crate::view::{Context, DrawCtx, Group, Rect, View, ViewId};
6use crate::widgets::{InputLine, RevealEye, RevealEyeConfig};
7
8/// A masked text field with a reveal eye: an [`InputLine`] (masked) plus a
9/// [`RevealEye`](super::RevealEye) in its last column, bundled as one group so
10/// the eye is its own Tab stop and reveal is wired internally.
11///
12/// # Turbo Vision heritage
13/// **tvision-rs extension**: no Turbo Vision counterpart.
14pub struct MaskedInput {
15    group: Group,
16    input_id: ViewId,
17    eye_id: ViewId,
18}
19
20impl MaskedInput {
21    /// Build a masked field of `bounds` with byte cap `limit`, echo char `mask`,
22    /// and reveal-eye config `cfg`. The input takes all but the last column; the
23    /// eye takes the last column.
24    pub fn new(bounds: Rect, limit: i32, mask: char, cfg: RevealEyeConfig) -> Self {
25        let w = bounds.b.x - bounds.a.x;
26        let h = bounds.b.y - bounds.a.y;
27        let mut group = Group::new(bounds);
28
29        // MUST be inserted before the eye: `value()` reads the input
30        // positionally via `gather_data().next()`, which relies on the input
31        // being the first child in the group.
32        let mut input = InputLine::with_limit(Rect::new(0, 0, (w - 1).max(1), h), limit);
33        input.set_mask(Some(mask));
34        let input_id = group.insert(Box::new(input));
35
36        let eye = RevealEye::new(Rect::new((w - 1).max(1), 0, w, h), cfg);
37        let eye_id = group.insert(Box::new(eye));
38
39        MaskedInput {
40            group,
41            input_id,
42            eye_id,
43        }
44    }
45
46    fn input_mut(&mut self) -> Option<&mut InputLine> {
47        self.group
48            .child_mut(self.input_id)?
49            .as_any_mut()?
50            .downcast_mut::<InputLine>()
51    }
52    fn eye_mut(&mut self) -> Option<&mut RevealEye> {
53        self.group
54            .child_mut(self.eye_id)?
55            .as_any_mut()?
56            .downcast_mut::<RevealEye>()
57    }
58
59    /// The real (unmasked) field value.
60    ///
61    /// Deliberately takes `&self` rather than `&mut self`: [`View::value`]
62    /// also has the name `value` with a `&self` receiver, and Rust's method
63    /// resolution picks the first receiver-borrow level (by value, `&self`,
64    /// `&mut self`, in that order) at which *any* applicable method exists —
65    /// inherent methods win ties at the same level, but a `&mut self` inherent
66    /// method never gets a chance to compete against a `&self` trait method,
67    /// since the trait method is found first. Matching `View::value`'s `&self`
68    /// receiver keeps `mi.value()` resolving to this inherent impl (verified:
69    /// with a `&mut self` signature here, `mi.value()` silently called the
70    /// `View` trait's default `None` instead). [`Group::gather_data`] conveniently
71    /// offers the read in `&self` form (input is the first-inserted, hence
72    /// first, child).
73    pub fn value(&self) -> Option<FieldValue> {
74        self.group.gather_data().into_iter().next().flatten()
75    }
76    /// Set the field value.
77    pub fn set_value(&mut self, v: FieldValue) {
78        if let Some(i) = self.input_mut() {
79            i.set_value(v);
80        }
81    }
82
83    #[cfg(test)]
84    fn input_ref(&mut self) -> &InputLine {
85        self.input_mut().expect("input child")
86    }
87    #[cfg(test)]
88    fn input_bounds(&mut self) -> Rect {
89        self.input_mut().expect("input child").state().get_bounds()
90    }
91}
92
93#[crate::delegate(to = group)]
94impl View for MaskedInput {
95    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
96        Some(self)
97    }
98
99    // Without these, the `#[delegate]` macro would auto-forward `value`/
100    // `set_value` to `self.group.value()`/`self.group.set_value()` — and
101    // `Group` itself doesn't override either (both default to the `View`
102    // trait's no-op), so a `MaskedInput` embedded as a `Box<dyn View>` in an
103    // enclosing dialog's `Group` (the normal case: `gather_data`/`scatter_data`
104    // drive a dialog's OK/scatter passes through exactly that trait-object
105    // path) would silently gather `None` and ignore `scatter_data`, instead of
106    // reading/writing the real password. Forwarding to the inherent
107    // `value`/`set_value` here (verified not to recurse — method resolution is
108    // by the receiver's static type, not by which impl block the call sits in)
109    // keeps both the direct `mi.value()` call and the trait-object path
110    // consistent.
111    fn value(&self) -> Option<FieldValue> {
112        self.value()
113    }
114    fn set_value(&mut self, v: FieldValue) {
115        self.set_value(v);
116    }
117    // `Group::scatter_data` (a dialog's normal scatter pass) calls
118    // `set_value_ctx`, not `set_value` — same hazard as above: left to the
119    // macro, it forwards to `self.group.set_value_ctx(v, ctx)`, whose default
120    // body calls `Group`'s own (no-op) `set_value`, never reaching this type's
121    // real field. Override it too, ignoring `ctx` exactly as the trait's
122    // default does (this field needs no `Context` to update its text).
123    fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context) {
124        let _ = ctx;
125        self.set_value(v);
126    }
127
128    fn draw(&mut self, ctx: &mut DrawCtx) {
129        // Active-line only: the eye shows while this field has focus.
130        let focused = self.group.state().state.focused;
131        if let Some(eye) = self.eye_mut() {
132            eye.state_mut().state.visible = focused;
133        }
134        self.group.draw(ctx);
135    }
136
137    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
138        // Group routes the event to the focused child (input caret or eye),
139        // handles Tab between them, and fans Timer/Broadcast to both.
140        self.group.handle_event(ev, ctx);
141        // Re-sync the input's reveal from the eye after every event. The eye
142        // broadcasts REVEAL_CHANGED on any intent change, so this pass runs
143        // promptly even for a capture-delivered MouseUp.
144        let revealing = self.eye_mut().map(|e| e.is_revealing()).unwrap_or(false);
145        if let Some(input) = self.input_mut() {
146            input.set_reveal(revealing);
147        }
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::event::{KeyModifiers, MouseButtons, MouseEvent, MouseEventFlags, MouseWheel};
155    use crate::timer::TimerQueue;
156    use crate::view::Deferred;
157    use crate::{Event, FieldValue, Point, Rect};
158    use std::collections::VecDeque;
159
160    fn with_ctx<R>(mi: &mut MaskedInput, f: impl FnOnce(&mut MaskedInput, &mut Context) -> R) -> R {
161        let mut out: VecDeque<Event> = VecDeque::new();
162        let mut timers = TimerQueue::new();
163        let mut deferred: Vec<Deferred> = Vec::new();
164        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
165        f(mi, &mut ctx)
166    }
167
168    fn built() -> MaskedInput {
169        let mut mi = MaskedInput::new(Rect::new(0, 0, 12, 1), 64, '•', RevealEyeConfig::default());
170        // Give real ids as Group::insert would in a live tree, then seed a value.
171        mi.set_value(FieldValue::Text("pw".into()));
172        mi
173    }
174
175    #[test]
176    fn value_returns_the_real_text() {
177        let mi = built();
178        assert_eq!(mi.value(), Some(FieldValue::Text("pw".into())));
179    }
180
181    /// Regression: a dialog gathers/scatters its fields through `Group`'s
182    /// `gather_data`/`scatter_data`, which call `View::value`/`set_value`
183    /// through the `Box<dyn View>` vtable — a different path than calling
184    /// `mi.value()` directly on the concrete type. Without the explicit
185    /// `value`/`set_value` overrides in `impl View for MaskedInput` (that
186    /// forward to the inherent methods), the `#[delegate]` macro would instead
187    /// forward to `Group`'s own (no-op) `View::value`/`set_value`, and an
188    /// embedded `MaskedInput` would silently gather `None` / ignore scatter.
189    #[test]
190    fn value_round_trips_through_the_view_trait_object() {
191        let bounds = Rect::new(0, 0, 20, 5);
192        let mut host = Group::new(bounds);
193        let mi_id = host.insert(Box::new(built()));
194
195        let gathered = host.gather_data();
196        assert_eq!(
197            gathered,
198            vec![Some(FieldValue::Text("pw".into()))],
199            "gather_data must read the real text through the Box<dyn View> path"
200        );
201
202        let mut out: VecDeque<Event> = VecDeque::new();
203        let mut timers = TimerQueue::new();
204        let mut deferred: Vec<Deferred> = Vec::new();
205        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
206        host.scatter_data(&[Some(FieldValue::Text("newpw".into()))], &mut ctx);
207
208        let mi = host
209            .child_mut(mi_id)
210            .unwrap()
211            .as_any_mut()
212            .unwrap()
213            .downcast_mut::<MaskedInput>()
214            .unwrap();
215        assert_eq!(
216            mi.value(),
217            Some(FieldValue::Text("newpw".into())),
218            "scatter_data must write through the Box<dyn View> path too"
219        );
220    }
221
222    #[test]
223    fn eye_press_reveals_the_paired_input() {
224        let mut mi = built();
225        // Press the eye (its own cell = last column). Route through the group.
226        let down = Event::MouseDown(MouseEvent {
227            position: Point::new(11, 0),
228            buttons: MouseButtons {
229                left: true,
230                ..Default::default()
231            },
232            wheel: MouseWheel::None,
233            flags: MouseEventFlags::default(),
234            modifiers: KeyModifiers::default(),
235        });
236        with_ctx(&mut mi, |mi, ctx| {
237            let mut d = down;
238            mi.handle_event(&mut d, ctx);
239        });
240        assert!(mi.input_ref().reveal, "holding the eye reveals the input");
241
242        let up = Event::MouseUp(MouseEvent {
243            position: Point::new(11, 0),
244            buttons: MouseButtons {
245                left: true,
246                ..Default::default()
247            },
248            wheel: MouseWheel::None,
249            flags: MouseEventFlags::default(),
250            modifiers: KeyModifiers::default(),
251        });
252        with_ctx(&mut mi, |mi, ctx| {
253            let mut u = up;
254            mi.handle_event(&mut u, ctx);
255        });
256        assert!(!mi.input_ref().reveal, "releasing hides the input again");
257    }
258
259    #[test]
260    fn input_occupies_all_but_the_last_column() {
261        let mut mi = built();
262        let ib = mi.input_bounds();
263        assert_eq!(
264            ib,
265            Rect::new(0, 0, 11, 1),
266            "input is width-1, eye holds the last column"
267        );
268    }
269}