tvision_rs/widgets/input_line.rs
1//! `InputLine`, the single-line text-entry field (documented on the type).
2
3use crate::capture::TrackMask;
4use crate::command::Command;
5use crate::data::FieldValue;
6use crate::event::{Event, Key, MouseEvent};
7use crate::keymap::{self, KeyStroke, Resolve};
8use crate::text;
9use crate::theme::{Role, SurfaceRoles};
10use crate::validate::Validator;
11use crate::view::{Context, DrawCtx, Options, Point, Rect, StateFlag, View, ViewState};
12
13// ---------------------------------------------------------------------------
14// LimitMode — what the `limit` constructor argument counts
15// ---------------------------------------------------------------------------
16
17/// How the `limit` constructor argument is interpreted — which of the three
18/// internal caps it sets.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub enum LimitMode {
21 /// The default: `limit` caps the byte length (`max_len = limit - 1`); the
22 /// display width and grapheme count are unbounded.
23 #[default]
24 MaxBytes,
25 /// `limit` caps the display width (`max_width = limit`); `max_len` is 255.
26 MaxWidth,
27 /// `limit` caps the grapheme count (`max_chars = limit`); `max_len` is 255.
28 MaxChars,
29}
30
31// ---------------------------------------------------------------------------
32// InputLine
33// ---------------------------------------------------------------------------
34
35/// Where [`View::set_value`] leaves a field: which end of the text is on screen.
36///
37/// A value wider than the field can only show one end of itself. Which end is
38/// the *useful* one depends on the data — the tail of a number being entered,
39/// but the head of a path or a distinguished name, where the front is what
40/// identifies it. See [`InputLine::set_value_position`].
41#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
42pub enum ValuePosition {
43 /// Turbo Vision's behaviour and the default: the whole value is selected and
44 /// the caret sits after it, so the view shows the text's **end** and the
45 /// first keystroke replaces it.
46 #[default]
47 End,
48 /// The caret is homed and nothing is selected, so the view shows the text's
49 /// **start**.
50 Start,
51}
52
53/// A single-line text-entry field with selection, horizontal scrolling, an
54/// optional [`Validator`], and the typed [`value`](View::value)/
55/// [`set_value`](View::set_value) data protocol.
56///
57/// # Coordinate model — byte offsets vs. display columns
58///
59/// `data` is a Rust [`String`]. The cursor/selection offsets
60/// [`cur_pos`](InputLine::cur_pos) / [`sel_start`](InputLine::sel_start) /
61/// [`sel_end`](InputLine::sel_end) / `anchor` are **byte
62/// offsets** into it. Slicing a `String` at a non-`char` boundary panics, so
63/// every step over `data` goes through [`text::next`] / [`text::prev`] (whole
64/// grapheme clusters) — never `+1`/`-1`. `prev_word`/`next_word` scan ASCII
65/// spaces, whose byte offsets are always `char` boundaries.
66///
67/// [`first_pos`](InputLine::first_pos), by contrast, is a **display column**
68/// (the horizontal scroll offset). The displayed position of an offset is the
69/// display width of `data[..pos]`. For ASCII, byte == column, but for multi-byte
70/// / wide content they diverge, so the two units are kept strictly distinct here.
71///
72/// # Clipboard and command enabling
73///
74/// Cut/copy write to the clipboard via [`Context`]; paste is requested through
75/// the context and the pump reads the backend clipboard and inserts into the
76/// field, clamped to `max_len` and replacing any selection. The field keeps
77/// `cmCut`/`cmCopy` enabled while there is a selection and `cmPaste` enabled
78/// while it is active and selected, pushing those enable/disable updates as
79/// selection and focus change.
80///
81/// # Validation
82///
83/// A [`Validator`] gates the contents. Validators may also carry typed,
84/// non-text values: [`value`](View::value)/[`set_value`](View::set_value)
85/// consult the validator's [`transfer_get`](Validator::transfer_get) /
86/// [`transfer_set`](Validator::transfer_set) hook before falling back to the
87/// text itself, so a range validator round-trips an integer rather than a string.
88///
89/// Validation runs on focus loss and returns a plain boolean. Deciding validity
90/// is a read-only query (`valid(&self)`); a field that fails validation is *not*
91/// automatically re-focused, since moving focus would require mutable access to
92/// the event loop.
93///
94/// # Turbo Vision heritage
95///
96/// Ports `TInputLine` (`tinputli.cpp`/`dialogs.h`). Inheritance becomes the
97/// `View` trait plus `ViewState` composition (D2); the byte/width/char limit
98/// constants become the [`LimitMode`] enum (D1); the get/set/size data hooks
99/// become the typed [`value`](View::value)/[`set_value`](View::set_value)
100/// protocol over [`FieldValue`] (D10); and the explicit byte-offset vs.
101/// display-column split is the two-unit coordinate model (D13).
102pub struct InputLine {
103 /// View state (geometry, flags, cursor) — the composition target.
104 pub state: ViewState,
105 /// The UTF-8 text currently in the field.
106 ///
107 /// Direct reads are fine; to replace the whole content programmatically,
108 /// prefer [`View::set_value`] so the cursor and scroll position are
109 /// updated consistently. Slicing this string at a non-`char` boundary
110 /// panics, so all internal traversals go through [`text::next`] /
111 /// [`text::prev`] rather than raw byte arithmetic.
112 pub data: String,
113 /// Hard cap on `data.len()` in **bytes**.
114 ///
115 /// Set at construction time by the `limit` argument when [`LimitMode::MaxBytes`]
116 /// is active (`max_len = limit - 1`); otherwise fixed at 255. Insertions
117 /// that would push `data.len()` past this value are silently dropped.
118 /// See also [`max_width`](InputLine::max_width) and
119 /// [`max_chars`](InputLine::max_chars) for the display-width and
120 /// grapheme-count caps that the other two limit modes control.
121 pub max_len: i32,
122 /// Hard cap on the **display width** of `data` (in terminal columns).
123 ///
124 /// Active only when the field is constructed with [`LimitMode::MaxWidth`],
125 /// in which case `max_width = limit` and `max_len` is fixed at 255.
126 /// Defaults to `i32::MAX` (effectively unbounded) for the other two modes.
127 /// Wide characters such as CJK ideographs count as 2 columns each.
128 pub max_width: i32,
129 /// Hard cap on the **grapheme count** of `data`.
130 ///
131 /// Active only when the field is constructed with [`LimitMode::MaxChars`],
132 /// in which case `max_chars = limit` and `max_len` is fixed at 255.
133 /// Defaults to `i32::MAX` (effectively unbounded) for the other two modes.
134 /// A grapheme cluster (e.g. a base letter plus combining diacritic) counts
135 /// as one regardless of its byte or column size.
136 pub max_chars: i32,
137 /// Cursor position, a **byte** offset into `data`.
138 ///
139 /// Direct writes are supported — see [`cursor_request`](View::cursor_request)
140 /// for how this feeds the screen cursor. Direct writes do **not** scroll
141 /// the caret into view, though — use [`set_cursor_pos`](Self::set_cursor_pos)
142 /// for that.
143 pub cur_pos: i32,
144 /// Horizontal scroll offset, a **display column** (see the [`InputLine`]
145 /// docs: NOT a byte offset).
146 ///
147 /// Direct writes are supported — see [`cursor_request`](View::cursor_request)
148 /// for how this feeds the screen cursor. Direct writes do **not** scroll
149 /// the caret into view, though — use [`set_cursor_pos`](Self::set_cursor_pos)
150 /// for that.
151 pub first_pos: i32,
152 /// Selection start, a **byte** offset into `data`.
153 ///
154 /// Direct writes are supported and take effect immediately — nothing is
155 /// cached. Note this does not move `cur_pos` or scroll the field; pair
156 /// with a `cur_pos` write if the caret should track the selection.
157 pub sel_start: i32,
158 /// Selection end, a **byte** offset into `data`.
159 ///
160 /// Direct writes are supported and take effect immediately — nothing is
161 /// cached. Note this does not move `cur_pos` or scroll the field; pair
162 /// with a `cur_pos` write if the caret should track the selection.
163 pub sel_end: i32,
164 /// The fixed end of a keyboard/mouse block extension, a **byte** offset.
165 ///
166 /// Private, matching C++ `TInputLine::anchor`; move the caret through
167 /// [`set_cursor_pos`](Self::set_cursor_pos) or the key/mouse handling
168 /// instead of poking it directly.
169 anchor: i32,
170 /// The optional input validator, or `None` when the field is unconstrained.
171 ///
172 /// A [`Validator`] can filter individual keystrokes (`is_valid_input`),
173 /// check the whole value on focus loss (`validate`), and carry typed
174 /// non-text values via the `transfer_get`/`transfer_set` hooks so that
175 /// [`View::value`]/[`View::set_value`] round-trip an integer rather than a
176 /// string.
177 ///
178 /// You can read the validator (e.g. to call `is_status_ok`), but to
179 /// swap it out after construction use [`set_validator`](InputLine::set_validator)
180 /// rather than assigning to this field directly — that keeps the
181 /// ownership contract explicit.
182 pub validator: Option<Box<dyn Validator>>,
183 // -- validator save-state (oldData/oldCurPos/…) ------------------------
184 old_data: String,
185 old_cur_pos: i32,
186 old_first_pos: i32,
187 old_sel_start: i32,
188 old_sel_end: i32,
189 // -- mouse hold-tracking --------------------------------------------------
190 /// Absolute screen position of input-local `(0, 0)`, cached each `draw`
191 /// so the mouse-tracking capture can convert absolute mouse coords to
192 /// field-local (the `Button::abs_origin` pattern).
193 abs_origin: Point,
194 /// Whether a mouse hold-track is in flight. Guards the `MouseAuto` /
195 /// `MouseMove` / `MouseUp` tracking arms against stray events.
196 tracking: bool,
197 /// `true` for the drag-select branch (mask: move+auto); `false` for the
198 /// edge-auto-scroll branch (mask: auto only). Distinguishes which loop
199 /// body to execute in the `MouseAuto` arm.
200 tracking_drag: bool,
201 /// Whether the field selects its whole content when it gains focus.
202 ///
203 /// `true` (the default) matches Turbo Vision's `TInputLine`, where becoming
204 /// selected selects all so the first keystroke replaces the value. Set it
205 /// `false` (via [`set_select_all_on_focus`](InputLine::set_select_all_on_focus))
206 /// to suppress that select-all on focus **gain** — the caret and any existing
207 /// selection are left untouched and typing inserts rather than replacing.
208 /// Focus **loss** still clears the selection either way. Useful for
209 /// pre-filled or derived fields where select-all-then-type is surprising.
210 pub select_all_on_focus: bool,
211 /// Echo character painted in place of the real text when set. `None` = plain
212 /// field. `data`/`value()` always hold the real text; masking is draw-only.
213 /// Assumes width-1 graphemes (passwords): one echo char per `char`.
214 pub mask: Option<char>,
215 /// Transient: when true, the real text is painted despite `mask` (reveal).
216 pub reveal: bool,
217 /// Whether the field refuses every change to its text while staying fully
218 /// navigable. See [`set_read_only`](InputLine::set_read_only).
219 read_only: bool,
220 /// Which end of a too-wide value `set_value` leaves on screen. See
221 /// [`set_value_position`](InputLine::set_value_position).
222 value_position: ValuePosition,
223}
224
225impl InputLine {
226 /// Broadcast when a read-only field refuses a change, carrying the field's
227 /// own [`ViewId`](crate::ViewId) as the broadcast source so the owner can
228 /// tell *which* field was refused and explain it in its own words.
229 ///
230 /// A broadcast rather than a flag the owner polls: the deferred clipboard
231 /// paste is applied outside any keystroke the owner could poll around, and
232 /// the source id spares the owner any bookkeeping to map a refusal back to a
233 /// field. See [`set_read_only`](InputLine::set_read_only).
234 pub const READ_ONLY_REJECTED: Command = Command::custom("tv.input_line.read_only_rejected");
235
236 /// InputLine's surface triple for [`DrawCtx::content_surface`].
237 const SURFACE_ROLES: SurfaceRoles = SurfaceRoles {
238 normal: Role::InputNormal,
239 surface: Role::InputSurface,
240 inactive: Role::InputInactive,
241 };
242
243 /// Build a field from `bounds`, a `limit`, an optional `validator`, and a
244 /// [`LimitMode`] that decides what `limit` counts.
245 ///
246 /// The three internal caps are derived from the mode: `max_len` (byte cap)
247 /// is `limit - 1` clamped to a non-negative range when the mode is byte-based,
248 /// else 255; `max_width` is `limit` only in width mode, else unbounded;
249 /// `max_chars` is `limit` only in char mode, else unbounded. The field is
250 /// selectable, takes focus on first click, shows a cursor, and starts empty.
251 ///
252 /// Pass `None` for `validator` to create an unconstrained field. To attach
253 /// or replace the validator after construction, use
254 /// [`set_validator`](InputLine::set_validator). For the common case of a
255 /// byte-limited field with no validator, prefer [`with_limit`](InputLine::with_limit).
256 ///
257 /// # Note: headless / unit-test use outside a `Program`
258 ///
259 /// When constructing an `InputLine` outside a `Program` (e.g. in a unit test
260 /// with a hand-built [`crate::view::Context`]), the field will silently ignore
261 /// all key events unless `state.state.selected` is set to `true` before
262 /// driving it — the same condition a group sets when it focuses a child.
263 /// All the fields involved are `pub`, so the workaround is straightforward:
264 ///
265 /// ```rust,ignore
266 /// let mut il = InputLine::with_limit(Rect::new(0, 0, 20, 1), 64);
267 /// il.state.state.selected = true; // required to receive key events in tests
268 /// il.handle_event(&mut Event::Key(/* … */), &mut ctx);
269 /// ```
270 pub fn new(
271 bounds: Rect,
272 limit: i32,
273 validator: Option<Box<dyn Validator>>,
274 limit_mode: LimitMode,
275 ) -> Self {
276 let max_len = if limit_mode == LimitMode::MaxBytes {
277 // C++ min(max(limit-1, 0), INT_MAX-1); clamp is equivalent here
278 // (0 < i32::MAX-1 always, so it never panics).
279 (limit - 1).clamp(0, i32::MAX - 1)
280 } else {
281 255
282 };
283 let max_width = if limit_mode == LimitMode::MaxWidth {
284 limit
285 } else {
286 i32::MAX
287 };
288 let max_chars = if limit_mode == LimitMode::MaxChars {
289 limit
290 } else {
291 i32::MAX
292 };
293
294 let mut state = ViewState::new(bounds);
295 state.state.cursor_vis = true; // sfCursorVis
296 state.options = Options {
297 selectable: true,
298 first_click: true,
299 ..Default::default()
300 };
301
302 InputLine {
303 state,
304 data: String::new(),
305 max_len,
306 max_width,
307 max_chars,
308 cur_pos: 0,
309 first_pos: 0,
310 sel_start: 0,
311 sel_end: 0,
312 anchor: 0,
313 validator,
314 old_data: String::new(),
315 old_cur_pos: 0,
316 old_first_pos: 0,
317 old_sel_start: 0,
318 old_sel_end: 0,
319 abs_origin: Point::new(0, 0),
320 tracking: false,
321 tracking_drag: false,
322 select_all_on_focus: true,
323 mask: None,
324 reveal: false,
325 read_only: false,
326 value_position: ValuePosition::End,
327 }
328 }
329
330 /// Convenience constructor with no validator and the default byte-limit mode.
331 pub fn with_limit(bounds: Rect, limit: i32) -> Self {
332 Self::new(bounds, limit, None, LimitMode::MaxBytes)
333 }
334
335 /// Replace this field's validator after construction.
336 ///
337 /// Pass `Some(validator)` to attach a [`Validator`](crate::validate::Validator)
338 /// that filters keystrokes and checks the field on focus-change/close, or
339 /// `None` to remove any constraint. The previous validator (if any) is dropped.
340 ///
341 /// Most fields set their validator once via [`InputLine::new`]; use this when
342 /// the constraint is only known later (e.g. it depends on another control's
343 /// value gathered at dialog-open time).
344 ///
345 /// # Turbo Vision heritage
346 ///
347 /// Mirrors `TInputLine::setValidator`, which disposed the old validator and
348 /// assigned the new one.
349 pub fn set_validator(&mut self, validator: Option<Box<dyn crate::validate::Validator>>) {
350 self.validator = validator;
351 }
352
353 /// Enable or disable select-all on focus gain (default enabled).
354 ///
355 /// With `true` (the Turbo Vision default) the field selects its whole content
356 /// when it becomes focused, so the first keystroke replaces it. With `false`
357 /// the field keeps its caret and any existing selection on focus gain and
358 /// typing inserts at the caret — the field still clears its selection on focus
359 /// loss. See [`select_all_on_focus`](InputLine::select_all_on_focus).
360 ///
361 /// # Turbo Vision heritage
362 /// **tvision-rs extension** to `TInputLine`. `TInputLine` always selects all on
363 /// focus gain.
364 pub fn set_select_all_on_focus(&mut self, enable: bool) {
365 self.select_all_on_focus = enable;
366 }
367
368 /// Make the field refuse every change to its text while leaving it fully
369 /// navigable — the "look but don't touch" mode.
370 ///
371 /// This is **orthogonal to `disabled`**. A disabled view is skipped by focus
372 /// entirely, so its value can never be scrolled, selected or copied. A
373 /// read-only field still takes focus, moves its caret, scrolls horizontally,
374 /// select-alls, and copies; only the text is untouchable:
375 ///
376 /// | | `disabled` | `read_only` | plain |
377 /// |---|---|---|---|
378 /// | takes focus | no | **yes** | yes |
379 /// | caret / horizontal scroll | — | **yes** | yes |
380 /// | select + copy | — | **yes** | yes |
381 /// | type / delete / cut / paste | — | **refused** | yes |
382 ///
383 /// Every refused change consumes the event and broadcasts
384 /// [`READ_ONLY_REJECTED`](InputLine::READ_ONLY_REJECTED), so the owner can
385 /// tell the user why the field will not budge. Cut and paste are also grayed
386 /// in the command set, closing the menu route.
387 ///
388 /// Setting this does not change the text, the caret, or the appearance: a
389 /// read-only field is drawn exactly like an editable one, because the owner
390 /// — which knows *why* the field is read-only — is better placed to signal it.
391 ///
392 /// # Turbo Vision heritage
393 /// **tvision-rs extension** to `TInputLine`.
394 pub fn set_read_only(&mut self, read_only: bool) {
395 self.read_only = read_only;
396 }
397
398 /// Whether the field refuses changes. See [`set_read_only`](Self::set_read_only).
399 pub fn is_read_only(&self) -> bool {
400 self.read_only
401 }
402
403 /// Choose which end of the text [`View::set_value`] leaves on screen.
404 ///
405 /// A value wider than the field shows only one end of itself, and the
406 /// Turbo Vision default ([`ValuePosition::End`]) picks the tail: `set_value`
407 /// select-alls, which parks caret and view after the last character, ready
408 /// for the first keystroke to replace the value.
409 ///
410 /// That is wrong for data whose front identifies it — a path, a URL, a
411 /// distinguished name — where the operator is left staring at
412 /// `…,dc=example,dc=org`. [`ValuePosition::Start`] homes the caret and the
413 /// view instead, leaving nothing selected.
414 ///
415 /// This governs `set_value` only. Focus is separate: see
416 /// [`set_select_all_on_focus`](Self::set_select_all_on_focus).
417 ///
418 /// # Turbo Vision heritage
419 /// **tvision-rs extension** to `TInputLine`. `ValuePosition::End` is the
420 /// `TInputLine::setData` behaviour.
421 pub fn set_value_position(&mut self, position: ValuePosition) {
422 self.value_position = position;
423 }
424
425 /// Which end of the text `set_value` leaves on screen. See
426 /// [`set_value_position`](Self::set_value_position).
427 pub fn value_position(&self) -> ValuePosition {
428 self.value_position
429 }
430
431 /// Apply [`value_position`](Self::value_position) after `set_value` has
432 /// replaced `data`.
433 fn place_loaded_value(&mut self) {
434 match self.value_position {
435 ValuePosition::End => self.select_all(true, true),
436 // `home` collapses the selection, homes the caret, and scrolls the
437 // field fully left.
438 ValuePosition::Start => self.home(),
439 }
440 }
441
442 /// Refuse a change on a read-only field: broadcast
443 /// [`READ_ONLY_REJECTED`](Self::READ_ONLY_REJECTED) naming this field and
444 /// report `true` so the caller drops the mutation. `false` on an editable
445 /// field, where the caller proceeds as usual.
446 fn refuse_change(&self, ctx: &mut Context) -> bool {
447 if !self.read_only {
448 return false;
449 }
450 ctx.broadcast(Self::READ_ONLY_REJECTED, self.state.id());
451 true
452 }
453
454 /// Set (or clear) the echo character. `Some(ch)` masks the display with `ch`;
455 /// `None` restores the plain field. The stored value is unaffected.
456 ///
457 /// # Turbo Vision heritage
458 /// **tvision-rs extension** to `TInputLine`.
459 pub fn set_mask(&mut self, mask: Option<char>) {
460 self.mask = mask;
461 }
462
463 /// Momentarily show the real text despite `mask` (password reveal). Ignored
464 /// when the field is not masked.
465 ///
466 /// # Turbo Vision heritage
467 /// **tvision-rs extension** to `TInputLine`.
468 pub fn set_reveal(&mut self, reveal: bool) {
469 self.reveal = reveal;
470 }
471
472 /// Whether the display is currently masked (masked and not revealed).
473 fn masking(&self) -> bool {
474 self.mask.is_some() && !self.reveal
475 }
476
477 /// The echo string for `s`: the mask char once per `char`. Only called while
478 /// `masking()` is true, so `self.mask` is `Some`.
479 fn echo_of(&self, s: &str) -> String {
480 let ch = self.mask.unwrap_or('•');
481 std::iter::repeat_n(ch, s.chars().count()).collect()
482 }
483
484 // -- geometry helpers (byte ↔ column) ----------------------------------
485
486 /// The display column of the prefix `data[..pos]` (`pos` is a byte offset).
487 /// The screen-column ↔ byte bridge.
488 fn displayed_pos(&self, pos: i32) -> i32 {
489 text::width(&self.data[..pos as usize]) as i32
490 }
491
492 /// Whether the field can scroll by `delta` (`delta < 0` left, `> 0` right).
493 /// Right uses display-width arithmetic.
494 fn can_scroll(&self, delta: i32) -> bool {
495 if delta < 0 {
496 self.first_pos > 0
497 } else if delta > 0 {
498 text::width(&self.data) as i32 - self.first_pos + 2 > self.state.size.x
499 } else {
500 false
501 }
502 }
503
504 /// Clamp `first_pos` so `cur_pos`'s display column stays inside the visible
505 /// window — pulls the scroll left/right as needed. Shared by the
506 /// keyboard-editing tail, `paste_text`, and `set_cursor_pos`; matches C++
507 /// `TInputLine`'s repeated `firstPos` clamp bracketing it into
508 /// `[curWidth - size.x + 2, curWidth]`.
509 fn scroll_cursor_into_view(&mut self) {
510 let cur_width = self.displayed_pos(self.cur_pos);
511 if self.first_pos > cur_width {
512 self.first_pos = cur_width;
513 }
514 let i = cur_width - self.state.size.x + 2;
515 if self.first_pos < i {
516 self.first_pos = i;
517 }
518 }
519
520 /// Move the caret to byte offset `pos`, collapsing any selection and
521 /// scrolling the field so the caret is visible.
522 ///
523 /// `pos` is clamped to `[0, data.len()]`; if the clamped offset does not
524 /// land on a `char` boundary it snaps down to the previous one (the same
525 /// boundary-snap idiom `check_valid` and [`View::set_value`] already use
526 /// when clamping to `max_len`).
527 ///
528 /// # Turbo Vision heritage
529 /// C++ code assigns the public `TInputLine::curPos` field directly; this
530 /// setter does the same and also collapses the selection and scrolls the
531 /// caret into view.
532 pub fn set_cursor_pos(&mut self, pos: i32) {
533 let mut cut = pos.clamp(0, self.data.len() as i32) as usize;
534 while cut > 0 && !self.data.is_char_boundary(cut) {
535 cut -= 1;
536 }
537 self.cur_pos = cut as i32;
538 self.sel_start = 0;
539 self.sel_end = 0;
540 self.anchor = self.cur_pos;
541 self.scroll_cursor_into_view();
542 }
543
544 /// Move the caret to the start of the field. Extension — see
545 /// [`set_cursor_pos`](Self::set_cursor_pos).
546 pub fn home(&mut self) {
547 self.set_cursor_pos(0);
548 }
549
550 /// Move the caret to the end of the field. Extension — see
551 /// [`set_cursor_pos`](Self::set_cursor_pos).
552 pub fn end(&mut self) {
553 self.set_cursor_pos(self.data.len() as i32);
554 }
555
556 // -- selection / deletion (byte offsets) -------------------------------
557
558 /// Remove the selected range `data[sel_start..sel_end]`, leaving the cursor
559 /// at `sel_start`.
560 fn delete_select(&mut self) {
561 if self.sel_start < self.sel_end {
562 self.data
563 .replace_range(self.sel_start as usize..self.sel_end as usize, "");
564 self.cur_pos = self.sel_start;
565 }
566 }
567
568 /// Select the grapheme under the cursor (one [`text::next`] step) and delete it.
569 fn delete_current(&mut self) {
570 let cp = self.cur_pos as usize;
571 if cp < self.data.len() {
572 let step = text::next(&self.data[cp..])
573 .map(|(len, _)| len)
574 .unwrap_or(0);
575 self.sel_start = self.cur_pos;
576 self.sel_end = self.cur_pos + step as i32;
577 self.delete_select();
578 }
579 }
580
581 /// Order `sel_start`/`sel_end` around the `anchor` after a block extension.
582 fn adjust_select_block(&mut self) {
583 if self.cur_pos < self.anchor {
584 self.sel_start = self.cur_pos;
585 self.sel_end = self.anchor;
586 } else {
587 self.sel_start = self.anchor;
588 self.sel_end = self.cur_pos;
589 }
590 }
591
592 /// Select the whole field (`enable = true`) or deselect it (`enable =
593 /// false`), and optionally scroll the cursor into view (`scroll = true`).
594 ///
595 /// When `enable` is true the cursor moves to the end of `data` and the
596 /// selection covers `[0, data.len()]`. When false both the cursor and
597 /// the selection are collapsed to position 0.
598 ///
599 /// Pass `scroll = true` when the field is gaining focus (so the end of a
600 /// long value scrolls into view). Pass `scroll = false` from [`set_state`](crate::view::View::set_state)
601 /// where the viewport position should be left as-is.
602 ///
603 /// This method does **not** trigger a redraw on its own — the event loop
604 /// redraws the whole tree. The screen cursor needs no separate update: it
605 /// is derived fresh from `cur_pos`/`first_pos` via
606 /// [`cursor_request`](View::cursor_request) on the next pump. Callers that
607 /// also need to refresh cut/copy/paste command graying call
608 /// `update_commands` separately.
609 pub fn select_all(&mut self, enable: bool, scroll: bool) {
610 self.sel_start = 0;
611 if enable {
612 self.cur_pos = self.data.len() as i32;
613 self.sel_end = self.cur_pos;
614 } else {
615 self.cur_pos = 0;
616 self.sel_end = 0;
617 }
618 if scroll {
619 self.first_pos = (self.displayed_pos(self.cur_pos) - self.state.size.x + 2).max(0);
620 }
621 }
622
623 /// True only when this field is both active and selected. Command
624 /// enable/disable updates are pushed only while both hold.
625 fn can_update_commands(&self) -> bool {
626 self.state.state.active && self.state.state.selected
627 }
628
629 /// Push enable/disable updates for cut/copy (enabled only while a selection
630 /// exists) and paste (always enabled while this field is active+selected).
631 /// Only called when [`can_update_commands`](Self::can_update_commands) holds.
632 fn update_commands(&self, ctx: &mut Context) {
633 let has_selection = self.sel_start < self.sel_end;
634 // Copy follows the selection either way — a read-only field is meant to
635 // be copied FROM. Cut and paste change the text, so they stay gray while
636 // read-only: the menu route must not do what the keyboard route refuses.
637 if has_selection {
638 if self.read_only {
639 ctx.disable_command(Command::CUT);
640 } else {
641 ctx.enable_command(Command::CUT);
642 }
643 ctx.enable_command(Command::COPY);
644 } else {
645 ctx.disable_command(Command::CUT);
646 ctx.disable_command(Command::COPY);
647 }
648 if self.read_only {
649 ctx.disable_command(Command::PASTE);
650 } else {
651 // cmPaste is always enabled when this field is active+selected.
652 ctx.enable_command(Command::PASTE);
653 }
654 }
655
656 // -- validator save/restore/check --------------------------------------
657
658 /// Snapshot the field for the validator's restore-on-reject.
659 fn save_state(&mut self) {
660 if self.validator.is_some() {
661 self.old_data.clear();
662 self.old_data.push_str(&self.data);
663 self.old_cur_pos = self.cur_pos;
664 self.old_first_pos = self.first_pos;
665 self.old_sel_start = self.sel_start;
666 self.old_sel_end = self.sel_end;
667 }
668 }
669
670 /// Undo to the last [`save_state`](Self::save_state).
671 fn restore_state(&mut self) {
672 if self.validator.is_some() {
673 self.data.clear();
674 self.data.push_str(&self.old_data);
675 self.cur_pos = self.old_cur_pos;
676 self.first_pos = self.old_first_pos;
677 self.sel_start = self.old_sel_start;
678 self.sel_end = self.old_sel_end;
679 }
680 }
681
682 /// Run the validator's input check over the current `data`; on reject,
683 /// restore the snapshot and report `false`; on accept, clamp to the byte cap
684 /// and pull the cursor back to the new end if it sat past the old one.
685 /// Returns whether the input is (still) valid.
686 fn check_valid(&mut self, no_auto_fill: bool) -> bool {
687 if self.validator.is_none() {
688 return true;
689 }
690 let old_len = self.data.len() as i32;
691 // isValidInput may modify the candidate in place.
692 let mut candidate = self.data.clone();
693 let validator = self.validator.as_ref().unwrap();
694 if !validator.is_valid_input(&mut candidate, no_auto_fill) {
695 self.restore_state();
696 false
697 } else {
698 // Clamp to maxLen on a char boundary (truncate never splits a char).
699 if candidate.len() as i32 > self.max_len {
700 let mut cut = self.max_len as usize;
701 while cut > 0 && !candidate.is_char_boundary(cut) {
702 cut -= 1;
703 }
704 candidate.truncate(cut);
705 }
706 let new_len = candidate.len() as i32;
707 self.data = candidate;
708 // Note: a future mutating validator that SHRINKS data could leave
709 // cur_pos past end-of-string / mid-grapheme. No bundled validator
710 // shrinks, so this is not handled; an auto-fill validator would need
711 // to re-clamp cur_pos to a char boundary <= data.len() to avoid a
712 // slicing panic.
713 if self.cur_pos >= old_len && new_len > old_len {
714 self.cur_pos = new_len;
715 }
716 true
717 }
718 }
719
720 // -- clipboard paste ------------------------------------------------------
721
722 /// Insert `text` from the clipboard at the current cursor position,
723 /// replacing any active selection and clamping the result to `max_len`.
724 /// Called by the pump's `Deferred::InputLinePaste` apply arm once the backend
725 /// has supplied the clipboard text: insert the pasted bytes at the cursor,
726 /// replacing the selection, clamped so the total byte length does not exceed
727 /// the byte cap. Tabs/newlines are replaced with spaces. After insertion the
728 /// cursor sits at the end of the pasted text and the selection is cleared.
729 ///
730 /// A no-op on a [read-only](Self::set_read_only) field. Both routes into a
731 /// deferred paste are already refused before they get here, so this is the
732 /// belt to their braces — and it is silent, because without a `Context` it
733 /// cannot broadcast the refusal.
734 pub fn paste_text(&mut self, text: &str) {
735 if self.read_only {
736 return;
737 }
738 self.save_state();
739 // Replace the current selection before inserting.
740 self.delete_select();
741 // Replace tabs/newlines with spaces, insert character by character,
742 // stopping when max_len would be exceeded. For simplicity we insert the
743 // whole normalised string in one go after clamping.
744 let normalized: String = text
745 .chars()
746 .map(|c| {
747 if c == '\t' || c == '\r' || c == '\n' {
748 ' '
749 } else {
750 c
751 }
752 })
753 .collect();
754 // How many bytes we can still accept.
755 let room = (self.max_len - self.data.len() as i32).max(0) as usize;
756 // Clamp `normalized` to `room` bytes at a char boundary.
757 let clamped = if normalized.len() <= room {
758 &normalized[..]
759 } else {
760 let mut cut = room;
761 while cut > 0 && !normalized.is_char_boundary(cut) {
762 cut -= 1;
763 }
764 &normalized[..cut]
765 };
766 if !clamped.is_empty() {
767 self.data.insert_str(self.cur_pos as usize, clamped);
768 self.cur_pos += clamped.len() as i32;
769 }
770 self.sel_start = 0;
771 self.sel_end = 0;
772 // firstPos scroll-follow (column arithmetic).
773 self.scroll_cursor_into_view();
774 self.check_valid(true);
775 }
776
777 // -- mouse helpers (used by the press-and-hold track arms) -------------
778
779 /// The byte offset under the mouse (view-local position already applied by
780 /// the group).
781 fn mouse_pos(&self, m: &MouseEvent) -> i32 {
782 let mx = m.position.x.max(1);
783 let pos = (mx + self.first_pos - 1).max(0);
784 // scroll(columns) → byte length of that many columns into data.
785 text::scroll(&self.data, pos, false).0 as i32
786 }
787
788 /// The auto-scroll direction for a mouse at the edge. Used by the mouse-down
789 /// arm and the hold-repeat (`MouseAuto`) arm in both the edge-scroll and
790 /// drag-select branches.
791 fn mouse_delta(&self, m: &MouseEvent) -> i32 {
792 if m.position.x <= 0 {
793 -1
794 } else if m.position.x >= self.state.size.x - 1 {
795 1
796 } else {
797 0
798 }
799 }
800
801 // -- clipboard helpers (extracted from the command arm) --------------
802
803 /// Cut: copy the current selection to the clipboard, then delete it. The
804 /// clipboard operation is guarded by the selection test; the cut command is
805 /// always consumed regardless of whether a selection existed, which the
806 /// callers handle. Whenever a mask is configured (`self.mask.is_some()`),
807 /// the clipboard write is skipped — reveal is for viewing, not
808 /// exfiltrating, so even a revealed masked field must not leak cleartext —
809 /// but the delete still happens unconditionally.
810 fn do_cut(&mut self, ctx: &mut Context) {
811 if self.sel_start < self.sel_end {
812 if self.mask.is_none() {
813 let sel = self.data[self.sel_start as usize..self.sel_end as usize].to_string();
814 ctx.set_clipboard(sel);
815 }
816 self.save_state();
817 self.delete_select();
818 self.check_valid(true);
819 self.sel_start = 0;
820 self.sel_end = 0;
821 }
822 }
823
824 /// Copy the current selection to the clipboard, keeping it (the
825 /// `Command::COPY` body). Whenever a mask is configured (`self.mask.is_some()`),
826 /// this is a no-op — reveal is for viewing, not exfiltrating, so cleartext
827 /// must never leave a masked field via the clipboard, revealed or not.
828 fn do_copy(&mut self, ctx: &mut Context) {
829 if self.sel_start < self.sel_end && self.mask.is_none() {
830 let sel = self.data[self.sel_start as usize..self.sel_end as usize].to_string();
831 ctx.set_clipboard(sel);
832 }
833 }
834
835 /// Publish the current selection as the X11/Wayland PRIMARY selection, so
836 /// another client can middle-click-paste it.
837 ///
838 /// Called only when a **mouse** selection completes. Keyboard selection does
839 /// not publish: shift+arrow would re-take X selection ownership on every
840 /// keystroke for no real gain.
841 ///
842 /// Whenever a mask is configured (`self.mask.is_some()`) this is a no-op —
843 /// the same rule as [`do_copy`](Self::do_copy): reveal is for viewing, not
844 /// exfiltrating, so a masked field must never publish cleartext, revealed or
845 /// not. Read-only is deliberately NOT a guard here: read-only blocks writing
846 /// into the field, not reading out of it.
847 fn publish_primary(&self, ctx: &mut Context) {
848 if self.sel_start < self.sel_end && self.mask.is_none() {
849 let sel = self.data[self.sel_start as usize..self.sel_end as usize].to_string();
850 ctx.set_primary(sel);
851 }
852 }
853
854 /// Request an async paste via the broker (the `Command::PASTE` body).
855 fn do_paste(&mut self, ctx: &mut Context) {
856 if let Some(id) = self.state.id() {
857 ctx.request_input_line_paste(id);
858 }
859 }
860
861 // -- keymap dispatch ----------------------------------------------------
862
863 /// Apply a resolved editor command within the single-line repertoire.
864 /// Returns `true` if handled; `false` means "not ours — let it bubble".
865 fn apply_input_command(&mut self, cmd: Command, ctx: &mut Context) -> bool {
866 // Everything that changes the text is refused on a read-only field. The
867 // command is still reported handled, so the event is consumed and does
868 // not bubble on to be interpreted by something else.
869 if matches!(
870 cmd,
871 Command::BACK_SPACE
872 | Command::DEL_WORD_LEFT
873 | Command::DEL_CHAR
874 | Command::DEL_WORD
875 | Command::DEL_LINE
876 | Command::CUT
877 | Command::PASTE
878 ) && self.refuse_change(ctx)
879 {
880 return true;
881 }
882 match cmd {
883 Command::CHAR_LEFT => {
884 self.cur_pos -= text::prev(&self.data, self.cur_pos as usize) as i32
885 }
886 Command::CHAR_RIGHT => {
887 let cp = self.cur_pos as usize;
888 let step = text::next(&self.data[cp..]).map(|(l, _)| l).unwrap_or(0);
889 self.cur_pos += step as i32;
890 }
891 Command::WORD_LEFT => self.cur_pos = prev_word(&self.data, self.cur_pos),
892 Command::WORD_RIGHT => self.cur_pos = next_word(&self.data, self.cur_pos),
893 Command::LINE_START => self.cur_pos = 0,
894 Command::LINE_END => self.cur_pos = self.data.len() as i32,
895 Command::BACK_SPACE => {
896 if self.sel_start == self.sel_end {
897 self.sel_start =
898 self.cur_pos - text::prev(&self.data, self.cur_pos as usize) as i32;
899 self.sel_end = self.cur_pos;
900 }
901 self.delete_select();
902 self.check_valid(true);
903 }
904 Command::DEL_WORD_LEFT => {
905 // kbCtrlBack / kbAltBack — delete the previous word.
906 if self.sel_start == self.sel_end {
907 self.sel_start = prev_word(&self.data, self.cur_pos);
908 self.sel_end = self.cur_pos;
909 }
910 self.delete_select();
911 self.check_valid(true);
912 }
913 Command::DEL_CHAR => {
914 if self.sel_start == self.sel_end {
915 self.delete_current();
916 } else {
917 self.delete_select();
918 }
919 self.check_valid(true);
920 }
921 Command::DEL_WORD => {
922 // kbCtrlDel — delete to the next word.
923 if self.sel_start == self.sel_end {
924 self.sel_start = self.cur_pos;
925 self.sel_end = next_word(&self.data, self.cur_pos);
926 }
927 self.delete_select();
928 self.check_valid(true);
929 }
930 Command::INS_MODE => {
931 // C++ setState(sfCursorIns, !(state & sfCursorIns)). sfCursorIns
932 // is NOT a propagating StateFlag, so flip it directly on ViewState.
933 self.state.state.cursor_ins = !self.state.state.cursor_ins;
934 }
935 Command::DEL_LINE => {
936 // Ctrl-Y clears the field (the C++ default's else-if).
937 self.data.clear();
938 self.cur_pos = 0;
939 }
940 Command::SELECT_ALL => {
941 self.sel_start = 0;
942 self.sel_end = self.data.len() as i32;
943 self.cur_pos = self.data.len() as i32;
944 }
945 Command::CUT => {
946 self.do_cut(ctx);
947 return true;
948 }
949 Command::COPY => {
950 self.do_copy(ctx);
951 return true;
952 }
953 Command::PASTE => {
954 self.do_paste(ctx);
955 return true;
956 }
957 _ => return false, // outside the single-line repertoire → bubble
958 }
959 true
960 }
961}
962
963/// `prevWord` (`tinputli.cpp`) — the byte offset of the start of the word before
964/// `pos`. Scans ASCII spaces backwards; space bytes are never inside a multibyte
965/// sequence, so every returned offset is a `char` boundary.
966fn prev_word(s: &str, pos: i32) -> i32 {
967 let b = s.as_bytes();
968 let mut i = pos - 1;
969 while i >= 1 {
970 if b[i as usize] != b' ' && b[(i - 1) as usize] == b' ' {
971 return i;
972 }
973 i -= 1;
974 }
975 0
976}
977
978/// `nextWord` (`tinputli.cpp`) — the byte offset of the start of the word after
979/// `pos`. Scans ASCII spaces forward (see [`prev_word`] re boundaries).
980fn next_word(s: &str, pos: i32) -> i32 {
981 let b = s.as_bytes();
982 let len = b.len() as i32;
983 let mut i = pos;
984 while i < len - 1 {
985 if b[i as usize] == b' ' && b[(i + 1) as usize] != b' ' {
986 return i + 1;
987 }
988 i += 1;
989 }
990 len
991}
992
993impl View for InputLine {
994 fn state(&self) -> &ViewState {
995 &self.state
996 }
997
998 fn state_mut(&mut self) -> &mut ViewState {
999 &mut self.state
1000 }
1001
1002 /// Exposes the concrete `InputLine` so the pump's
1003 /// [`InputLinePaste`](crate::view::Deferred::InputLinePaste) broker can
1004 /// downcast and call [`paste_text`](InputLine::paste_text).
1005 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1006 Some(self)
1007 }
1008
1009 /// The screen-cursor column, derived fresh from `cur_pos`/`first_pos` on
1010 /// every call — the port of C++ `TInputLine::draw`'s tail
1011 /// `setCursor(displayedPos(curPos)-firstPos+1, 0)`, which re-derives the
1012 /// cursor every paint rather than caching it. Because this recomputes from
1013 /// the live fields instead of reading a cache, direct writes to `cur_pos`/
1014 /// `first_pos` are always reflected on the next pump. Mirrors the base
1015 /// [`View::cursor_request`] focus/visibility gate.
1016 fn cursor_request(&self) -> Option<Point> {
1017 if self.state.state.focused && self.state.state.cursor_vis {
1018 Some(Point::new(
1019 self.displayed_pos(self.cur_pos) - self.first_pos + 1,
1020 0,
1021 ))
1022 } else {
1023 None
1024 }
1025 }
1026
1027 /// Render the field: background fill, scrolled text, scroll arrows at the
1028 /// edges when the content overflows, and the selection highlight.
1029 ///
1030 /// Colors come from the theme roles: [`Role::InputNormal`] for the
1031 /// background and unselected text of a focused field (or a never-selectable
1032 /// one) within an active pane, [`Role::InputSurface`] for a non-focused
1033 /// selectable field in that same active pane, [`Role::InputInactive`] once
1034 /// the owning pane recedes, [`Role::InputArrow`] for the `◄`/`►` overflow
1035 /// indicators, and [`Role::InputSelected`] for highlighted text. Because
1036 /// tvision-rs has no attribute-only paint, the selected substring is **redrawn** (not just
1037 /// re-attributed) in the selected style at the correct scroll offset — the
1038 /// visible glyphs of the scrolled window, not the raw head of the selection.
1039 ///
1040 /// The screen cursor position is **not** set here; cursor placement lives
1041 /// in [`cursor_request`](View::cursor_request), called by the event loop
1042 /// before each redraw.
1043 fn draw(&mut self, ctx: &mut DrawCtx) {
1044 // Cache absolute origin for the mouse-tracking capture: the
1045 // MouseTrackCapture converts absolute mouse coords to field-local via
1046 // this value, mirroring the Button `abs_origin` pattern.
1047 self.abs_origin = ctx.origin();
1048 let size = self.state.size;
1049 // Surface selection: the three-surface rule is the default (see
1050 // `DrawCtx::content_surface`). `owner_active` recedes the whole field to
1051 // InputInactive regardless of focus; within an active pane, own focus
1052 // picks well-vs-surface — the focused field is the InputNormal well,
1053 // an unfocused *selectable* sibling sits on InputSurface, and a field
1054 // that can never take focus (`selectable == false`) always stays
1055 // InputNormal (there is no focus contest for it to lose). classic_blue
1056 // collapses all three roles to white-on-blue, so unthemed input is
1057 // unchanged.
1058 let color = ctx.content_surface(
1059 Self::SURFACE_ROLES,
1060 self.state.state.focused,
1061 self.state.options.selectable,
1062 );
1063 let arrow = ctx.style(Role::InputArrow);
1064 let selected = ctx.style(Role::InputSelected);
1065 let left_arrow = ctx.glyphs().input_left_arrow;
1066 let right_arrow = ctx.glyphs().input_right_arrow;
1067
1068 // Fill the whole row with the background color.
1069 ctx.fill(Rect::new(0, 0, size.x, 1), ' ', color);
1070 // Masked display: echo one char per character (assumes width-1 graphemes,
1071 // which passwords are). `self.data` / `value()` stay the real text.
1072 let echo = self.masking().then(|| self.echo_of(&self.data));
1073 let shown: &str = echo.as_deref().unwrap_or(&self.data);
1074 // Scrolled text from column 1, offset by first_pos.
1075 if size.x > 1 {
1076 // The text window is columns 1..size.x; clip there via a sub-ctx so a
1077 // glyph cannot spill into col 0 or past the right edge.
1078 let mut sub = ctx.sub(Rect::new(1, 0, size.x, 1));
1079 sub.put_str_part(0, 0, shown, self.first_pos, color);
1080 }
1081
1082 // Scroll arrows.
1083 if self.can_scroll(1) {
1084 ctx.put_char(size.x - 1, 0, right_arrow, arrow);
1085 }
1086 if self.can_scroll(-1) {
1087 ctx.put_char(0, 0, left_arrow, arrow);
1088 }
1089
1090 // Selection highlight. There is no attr-only paint, so we REDRAW the
1091 // selected substring in the selected style at its screen column —
1092 // byte-identical output. Suppressed while masked so no cleartext leaks
1093 // (selection still works functionally; only the highlight is hidden).
1094 if !self.masking() && self.state.state.selected && self.sel_start < self.sel_end {
1095 // `l`/`r` are the display columns of the selection ends relative to
1096 // the scroll window; the highlight covers view columns [l+1 .. r+1).
1097 let l = (self.displayed_pos(self.sel_start) - self.first_pos).max(0);
1098 let r = (self.displayed_pos(self.sel_end) - self.first_pos).min(size.x - 2);
1099 if l < r {
1100 // We REDRAW (no attr-only paint), so the glyphs must be the ones
1101 // the scrolled main pass drew, NOT the head of sel_text. When the
1102 // selection starts left of the window (`first_pos >
1103 // displayed_pos(sel_start)`), `l` clamped to 0 but the substring
1104 // must skip those off-left columns — feed the skip as text_indent,
1105 // exactly as the main pass skips `first_pos` columns. Clip to
1106 // [l+1 .. r+1) so the right scroll-arrow cell (>= size.x-1) is never
1107 // overwritten.
1108 let skip = (self.first_pos - self.displayed_pos(self.sel_start)).max(0);
1109 let mut sub = ctx.sub(Rect::new(l + 1, 0, r + 1, 1));
1110 let sel_text = &self.data[self.sel_start as usize..self.sel_end as usize];
1111 sub.put_str_part(0, 0, sel_text, skip, selected);
1112 }
1113 }
1114 }
1115
1116 /// Process keyboard, mouse, and command events while the field is selected.
1117 ///
1118 /// **Keyboard:** printable characters are inserted at the cursor (replacing
1119 /// any active selection, with validator filtering and all three caps checked).
1120 /// Navigation keys (arrows, Home, End, Ctrl-arrows, Ins, Delete, Backspace,
1121 /// Ctrl-Y) are dispatched through the global keymap and applied by
1122 /// `apply_input_command`. Shift-held
1123 /// movement extends the selection block. Unhandled keys (Tab, Enter, Escape,
1124 /// modified characters outside the repertoire) are left live so the enclosing
1125 /// dialog can route them.
1126 ///
1127 /// **Mouse:** a single click positions the cursor; a double-click selects
1128 /// all. Click-and-drag or a click on a scroll-arrow arms a press-and-hold
1129 /// tracking capture that continues updating selection or scroll position on
1130 /// each [`Event::MouseAuto`] / [`Event::MouseMove`] tick until mouse-up.
1131 ///
1132 /// **Commands:** [`Command::CUT`], [`Command::COPY`], and [`Command::PASTE`]
1133 /// are consumed here; other commands fall through.
1134 ///
1135 /// After each handled event, cut/copy/paste command graying is refreshed via
1136 /// `update_commands` (only while both active
1137 /// and selected).
1138 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
1139 // Mouse-down auto-select is the group's job; nothing to do while unselected.
1140 if !self.state.state.selected {
1141 return;
1142 }
1143
1144 match ev {
1145 // -- Mouse positioning + hold-tracking ------------------------------
1146 //
1147 // The two hold loops (edge auto-scroll, drag-select) both start from
1148 // the same mouse-down — they become the first iteration here, then
1149 // arm the capture for subsequent ticks.
1150 Event::MouseDown(m) => {
1151 let m = *m;
1152 let delta = self.mouse_delta(&m);
1153 if m.buttons.middle {
1154 // X11 middle-click paste. FIRST in the chain on purpose: a
1155 // middle-click on an edge column must paste, not start the
1156 // edge auto-scroll, and it arms no tracking loop — this is a
1157 // one-shot gesture, not a drag. `paste_text` calls
1158 // `save_state` itself once the pump delivers the text.
1159 if !self.refuse_change(ctx)
1160 && let Some(id) = self.state.id()
1161 {
1162 self.cur_pos = self.mouse_pos(&m);
1163 // The paste lands AT the click, replacing nothing.
1164 self.sel_start = 0;
1165 self.sel_end = 0;
1166 self.anchor = self.cur_pos;
1167 ctx.request_input_line_paste_primary(id);
1168 }
1169 } else if self.can_scroll(delta) {
1170 // Edge auto-scroll: first iteration steps first_pos by delta.
1171 self.first_pos += delta;
1172 // Arm auto-only repeat.
1173 if let Some(id) = self.state.id() {
1174 self.tracking = true;
1175 self.tracking_drag = false;
1176 ctx.start_mouse_track(
1177 id,
1178 self.abs_origin,
1179 TrackMask {
1180 mouse_auto: true,
1181 ..Default::default()
1182 },
1183 );
1184 }
1185 } else if m.flags.double_click {
1186 // C++ tinputli.cpp:322 selectAll(True) — scroll arg defaults
1187 // to True (dialogs.h:177), so double-click selects-all AND
1188 // scrolls the end into view. No tracking loop for this branch.
1189 self.select_all(true, true);
1190 self.publish_primary(ctx);
1191 } else {
1192 // C++ tinputli.cpp:324-338 — drag-select loop.
1193 // First iteration: `anchor = mousePos(event); curPos = mousePos(event);
1194 // adjustSelectBlock()`.
1195 let pos = self.mouse_pos(&m);
1196 self.anchor = pos;
1197 self.cur_pos = pos;
1198 self.adjust_select_block();
1199 // Arm move+auto tracking.
1200 if let Some(id) = self.state.id() {
1201 self.tracking = true;
1202 self.tracking_drag = true;
1203 ctx.start_mouse_track(
1204 id,
1205 self.abs_origin,
1206 TrackMask {
1207 mouse_move: true,
1208 mouse_auto: true,
1209 ..Default::default()
1210 },
1211 );
1212 }
1213 }
1214 ev.clear();
1215 }
1216
1217 // -- Mouse auto (evMouseAuto) — loop body, guarded by tracking --
1218 //
1219 // For the edge-scroll branch (tinputli.cpp:315-318):
1220 // `if canScroll(delta) firstPos += delta`
1221 //
1222 // For the drag-select branch (tinputli.cpp:327-335):
1223 // `if event.what==evMouseAuto: delta=mouseDelta; if canScroll(delta) firstPos+=delta`
1224 // then `curPos=mousePos; adjustSelectBlock`
1225 Event::MouseAuto(m) if self.tracking => {
1226 let m = *m;
1227 let delta = self.mouse_delta(&m);
1228 if self.can_scroll(delta) {
1229 // C++ tinputli.cpp:328-330 (drag branch auto body) /
1230 // tinputli.cpp:315-318 (edge branch): edge-scroll
1231 self.first_pos += delta;
1232 }
1233 if self.tracking_drag {
1234 // C++ tinputli.cpp:332-334 (drag branch, both auto and move):
1235 // `curPos = mousePos(event); adjustSelectBlock()`
1236 self.cur_pos = self.mouse_pos(&m);
1237 self.adjust_select_block();
1238 }
1239 ev.clear();
1240 }
1241
1242 // -- Mouse move (evMouseMove) — drag-select loop body (move ticks)
1243 //
1244 // C++ tinputli.cpp:332-334 (inside the move|auto loop, for non-auto
1245 // events): `curPos=mousePos(event); adjustSelectBlock()`.
1246 // The edge-scroll track is auto-only, so a move during an edge track
1247 // must FALL THROUGH unconsumed (same split-loop structure as the
1248 // scrollbar arms).
1249 Event::MouseMove(m) if self.tracking && self.tracking_drag => {
1250 let m = *m;
1251 // Drag-select: move the cursor to the mouse and re-order the block.
1252 self.cur_pos = self.mouse_pos(&m);
1253 self.adjust_select_block();
1254 ev.clear();
1255 }
1256
1257 // -- Mouse up — post-loop (tracking ends). Guarded by `tracking`
1258 // (MouseUp is not mask-gated in Group::wants).
1259 Event::MouseUp(_) if self.tracking => {
1260 if self.tracking_drag {
1261 // The sweep is over — publish it. A plain click (no sweep)
1262 // leaves sel_start == sel_end, so this is a no-op there and
1263 // does not clobber the user's selection with "".
1264 self.publish_primary(ctx);
1265 }
1266 self.tracking = false;
1267 self.tracking_drag = false;
1268 ev.clear();
1269 }
1270
1271 // -- Keyboard --------------------------------------------------
1272 Event::KeyDown(ke) => {
1273 self.save_state();
1274 let shift = ke.modifiers.shift;
1275 let stroke = KeyStroke::from_event(*ke);
1276 let cmd = match keymap::resolve_global(None, stroke) {
1277 Resolve::Command(c) => Some(c),
1278 // A `Prefix` (input fields use no 2-key chords) or `None` both
1279 // fall through to the printable/bubble path.
1280 _ => None,
1281 };
1282
1283 // Shift-extend applies only to movement commands with Shift held.
1284 let is_move = matches!(cmd, Some(c) if
1285 c == Command::CHAR_LEFT
1286 || c == Command::CHAR_RIGHT
1287 || c == Command::WORD_LEFT
1288 || c == Command::WORD_RIGHT
1289 || c == Command::LINE_START
1290 || c == Command::LINE_END);
1291 let extend_block = is_move && shift;
1292 if extend_block {
1293 if self.cur_pos == self.sel_end {
1294 self.anchor = self.sel_start;
1295 } else if self.sel_start == self.sel_end {
1296 self.anchor = self.cur_pos;
1297 } else {
1298 self.anchor = self.sel_end;
1299 }
1300 }
1301
1302 // The post-dispatch tail clears the selection on any non-extend
1303 // movement. These commands must bypass that reset:
1304 // * SELECT_ALL — its effect IS the selection.
1305 // * PASTE — `do_paste` only QUEUES a deferred paste; the tail runs
1306 // synchronously first, so zeroing the selection here would make
1307 // the deferred `paste_text` find nothing to replace (regression).
1308 // * COPY — keep the visible selection after copying (faithful to
1309 // the old Command-arm COPY).
1310 // * CUT — `do_cut` already zeroed the selection; listed for
1311 // consistency (harmless either way).
1312 let keep_selection = matches!(
1313 cmd,
1314 Some(Command::SELECT_ALL | Command::CUT | Command::COPY | Command::PASTE)
1315 );
1316
1317 let mut handled = true;
1318 match cmd {
1319 Some(c) => handled = self.apply_input_command(c, ctx),
1320 None => {
1321 // Printable insertion: only a plain Char with no ctrl/alt.
1322 match ke.key {
1323 Key::Char(c)
1324 if !ke.modifiers.ctrl
1325 && !ke.modifiers.alt
1326 && self.refuse_change(ctx) =>
1327 {
1328 // Read-only: swallow the keystroke (and tell the
1329 // owner) instead of inserting it.
1330 let _ = c;
1331 }
1332 Key::Char(c) if !ke.modifiers.ctrl && !ke.modifiers.alt => {
1333 // Printable insertion. Tabs/newlines → space (faithful).
1334 let ch = if c == '\t' || c == '\r' || c == '\n' {
1335 ' '
1336 } else {
1337 c
1338 };
1339 let mut key_text = [0u8; 4];
1340 let key_text = ch.encode_utf8(&mut key_text);
1341 let len = key_text.len() as i32;
1342
1343 self.delete_select();
1344 if self.state.state.cursor_ins {
1345 self.delete_current();
1346 }
1347 if self.check_valid(true) {
1348 let data_m = text::measure(&self.data);
1349 let key_m = text::measure(key_text);
1350 if self.data.len() as i32 + len <= self.max_len
1351 && (data_m.width + key_m.width) as i32 <= self.max_width
1352 && (data_m.grapheme_count + key_m.grapheme_count) as i32
1353 <= self.max_chars
1354 {
1355 // firstPos is a column; pull it back to the cursor
1356 // column if the cursor scrolled off the left.
1357 let cur_col = self.displayed_pos(self.cur_pos);
1358 if self.first_pos > cur_col {
1359 self.first_pos = cur_col;
1360 }
1361 self.data.insert_str(self.cur_pos as usize, key_text);
1362 self.cur_pos += len;
1363 }
1364 self.check_valid(false);
1365 }
1366 }
1367 _ => handled = false,
1368 }
1369 }
1370 }
1371
1372 if !handled {
1373 // Unhandled key (Tab, Enter, a modified char, …): leave the
1374 // event LIVE and uncleared so the group/dialog still sees it
1375 // (the C++ `default: … else return;`).
1376 return;
1377 }
1378
1379 if extend_block {
1380 self.adjust_select_block();
1381 } else if !keep_selection {
1382 self.sel_start = 0;
1383 self.sel_end = 0;
1384 }
1385
1386 // firstPos scroll-follow (column arithmetic).
1387 self.scroll_cursor_into_view();
1388 ev.clear();
1389 }
1390
1391 // -- evCommand clipboard block --------------------------------------
1392 // Only reached when selected (the outer guard returns otherwise).
1393 Event::Command(cmd) => {
1394 // Only CUT/COPY/PASTE are handled via the command channel — the
1395 // input line must NOT newly react to movement/select commands that
1396 // arrive here (the keymap-driven repertoire applies to KeyDown).
1397 // The command is always consumed regardless of whether a
1398 // selection exists; the clipboard operation is guarded inside each.
1399 match *cmd {
1400 // Cut and paste change the text: refused (and consumed) on a
1401 // read-only field. Copy is always allowed — reading a value
1402 // out is the point of the mode.
1403 Command::CUT => {
1404 if !self.refuse_change(ctx) {
1405 self.do_cut(ctx);
1406 }
1407 ev.clear();
1408 }
1409 Command::COPY => {
1410 self.do_copy(ctx);
1411 ev.clear();
1412 }
1413 Command::PASTE => {
1414 if !self.refuse_change(ctx) {
1415 self.do_paste(ctx);
1416 }
1417 ev.clear();
1418 }
1419 _ => {}
1420 }
1421 }
1422
1423 // -- bracketed paste ------------------------------------------------
1424 // A terminal paste (middle-click, Shift-Ctrl-V, an X primary-selection
1425 // paste) arrives as an `Event::Paste` once bracketed paste is enabled.
1426 // The `Command::PASTE` arm above only reaches text through the async
1427 // clipboard broker (OS clipboard / internal buffer); this is the
1428 // terminal handing us the bytes directly, so insert them the same way
1429 // the deferred `InputLinePaste` broker does — via `paste_text`, which
1430 // replaces any selection and clamps to `max_len`. The `Editor` widget
1431 // already handles `Event::Paste`; without this arm a single-line field
1432 // silently dropped every terminal paste. Only reached when selected
1433 // (the outer guard returns otherwise).
1434 Event::Paste(text) => {
1435 let text = std::mem::take(text);
1436 if !self.refuse_change(ctx) {
1437 self.paste_text(&text);
1438 }
1439 ev.clear();
1440 }
1441
1442 _ => {}
1443 }
1444
1445 // Command graying: refresh the cut/copy/paste enable state. The
1446 // early-return for unhandled KeyDown already exited above; this covers
1447 // mouse, keyboard (handled), and command events.
1448 if self.can_update_commands() {
1449 self.update_commands(ctx);
1450 }
1451 }
1452
1453 /// Apply a state-flag change and react to focus transitions.
1454 ///
1455 /// Flips the requested flag on [`ViewState`], then:
1456 ///
1457 /// - On [`StateFlag::Selected`] (or [`StateFlag::Active`] while the field is
1458 /// already selected): calls [`select_all(enable, false)`](InputLine::select_all)
1459 /// so the field is fully selected when it gains focus and deselected when it
1460 /// loses it.
1461 /// - When the active-and-selected condition changes (e.g. the field gains or
1462 /// loses focus): pushes cut/copy/paste command enable/disable updates via
1463 /// `update_commands`. This is what grays the
1464 /// Edit menu items when focus leaves the field.
1465 fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
1466 // Command graying: sample the enable condition BEFORE the flag flip so
1467 // we can detect the transition.
1468 let update_before = self.can_update_commands();
1469
1470 // Base behaviour (replicated from View::set_state — no `super`).
1471 self.state.set_flag(flag, enable);
1472 if flag == StateFlag::Focused {
1473 let source = self.state.id();
1474 ctx.broadcast(
1475 if enable {
1476 Command::RECEIVED_FOCUS
1477 } else {
1478 Command::RELEASED_FOCUS
1479 },
1480 source,
1481 );
1482 }
1483 if flag == StateFlag::Selected || (flag == StateFlag::Active && self.state.state.selected) {
1484 // `select_all_on_focus == false` suppresses the select-all on focus
1485 // GAIN (`enable == true`) but still clears the selection on focus
1486 // LOSS (`enable == false`), so a drag-selection never lingers.
1487 if self.select_all_on_focus || !enable {
1488 self.select_all(enable, false);
1489 }
1490 }
1491 // Command graying: if the enable condition changed, push the
1492 // enable/disable updates.
1493 let update_after = self.can_update_commands();
1494 if update_before != update_after {
1495 self.update_commands(ctx);
1496 }
1497 }
1498
1499 /// With a validator: the validate command reports the validator's status;
1500 /// any other non-cancel command runs the validator and fails if invalid.
1501 /// Without a validator: always valid.
1502 fn valid(&mut self, cmd: Command, ctx: &mut Context) -> bool {
1503 if let Some(validator) = &self.validator {
1504 if cmd == Command::VALID {
1505 return validator.is_status_ok();
1506 } else if cmd != Command::CANCEL && !validator.validate(&self.data, ctx) {
1507 // validator.validate pops the validator's error box (via
1508 // ctx.request_message_box) on the way to returning false, then we
1509 // refocus the offending field.
1510 if let Some(id) = self.state.id() {
1511 ctx.request_focus(id);
1512 }
1513 return false;
1514 }
1515 }
1516 true
1517 }
1518
1519 /// Return the field's current value as a [`FieldValue`].
1520 ///
1521 /// If the attached validator supports typed transfer (`transfer_get`
1522 /// returns `Some`), that typed value is returned — for example, a
1523 /// [`RangeValidator`](crate::validate::RangeValidator) with transfer
1524 /// enabled yields `FieldValue::Int(n)` rather than `FieldValue::Text`.
1525 /// Otherwise (no validator, or transfer disabled) the raw field text is
1526 /// returned as `FieldValue::Text`.
1527 ///
1528 /// Call this from a dialog's gather pass (or directly) to read the field's
1529 /// value in a type-safe way. For a plain text field with no validator the
1530 /// result is always `Some(FieldValue::Text(…))`.
1531 fn value(&self) -> Option<FieldValue> {
1532 // A transfer-enabled validator (a range validator, say) produces a typed
1533 // value; otherwise the result is the field's text.
1534 if let Some(v) = self
1535 .validator
1536 .as_ref()
1537 .and_then(|val| val.transfer_get(&self.data))
1538 {
1539 return Some(v);
1540 }
1541 Some(FieldValue::Text(self.data.clone()))
1542 }
1543
1544 /// Load a value into the field, replacing the current contents, and select all.
1545 ///
1546 /// If the attached validator supports typed transfer (`transfer_set` returns
1547 /// `Some`), the validator formats the value into the display text (e.g.
1548 /// `FieldValue::Int(42)` becomes `"42"`) and [`select_all(true, true)`](InputLine::select_all)
1549 /// is called. Otherwise, a `FieldValue::Text` value is loaded directly,
1550 /// **truncated to `max_len` bytes** at the nearest `char` boundary if it
1551 /// is too long, and the field is selected. A `FieldValue::Int` into a field
1552 /// with no transfer-enabled validator is silently ignored (type mismatch).
1553 ///
1554 /// Use this from a dialog's scatter pass or any time you need to populate
1555 /// the field programmatically and want the cursor/scroll state reset.
1556 fn set_value(&mut self, v: FieldValue) {
1557 // A transfer-enabled validator formats the typed value into the field
1558 // text; otherwise the Text path is used. Select-all runs either way.
1559 if let Some(text) = self.validator.as_ref().and_then(|val| val.transfer_set(&v)) {
1560 self.data = text;
1561 self.place_loaded_value();
1562 return;
1563 }
1564 // When transfer is disabled and `v` is `Int` (not `Text`), the body
1565 // below is skipped entirely — no data change, no `select_all`. An `Int`
1566 // into a non-transfer field is a type mismatch the typed model rightly
1567 // drops; this is intentional, not an oversight.
1568 #[allow(irrefutable_let_patterns)]
1569 if let FieldValue::Text(s) = v {
1570 // Truncate to maxLen.
1571 let limit = self.max_len as usize;
1572 self.data = if s.len() <= limit {
1573 s
1574 } else {
1575 let mut cut = limit;
1576 while cut > 0 && !s.is_char_boundary(cut) {
1577 cut -= 1;
1578 }
1579 s[..cut].to_string()
1580 };
1581 self.place_loaded_value();
1582 }
1583 }
1584}
1585
1586// ---------------------------------------------------------------------------
1587// Tests
1588// ---------------------------------------------------------------------------
1589
1590#[cfg(test)]
1591mod tests {
1592 use super::*;
1593 use crate::backend::{HeadlessBackend, Renderer};
1594 use crate::event::{
1595 KeyEvent, KeyModifiers, MouseButtons, MouseEvent, MouseEventFlags, MouseWheel,
1596 };
1597 use crate::screen::Buffer;
1598 use crate::theme::Theme;
1599 use crate::timer::TimerQueue;
1600 use crate::view::{Deferred, Point};
1601 use std::collections::VecDeque;
1602
1603 // -- helpers ------------------------------------------------------------
1604
1605 fn render(il: &mut InputLine) -> String {
1606 let theme = Theme::classic_blue();
1607 let size = il.state.size;
1608 let (backend, screen) = HeadlessBackend::new(size.x as u16, size.y as u16);
1609 let mut r = Renderer::new(Box::new(backend));
1610 r.render(|buf: &mut Buffer| {
1611 let bounds = il.state.get_bounds();
1612 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1613 il.draw(&mut dc);
1614 });
1615 screen.snapshot()
1616 }
1617
1618 fn with_ctx<R>(f: impl FnOnce(&mut Context) -> R) -> (Vec<Event>, R) {
1619 let mut out = VecDeque::new();
1620 let mut timers = TimerQueue::new();
1621 let mut deferred: Vec<Deferred> = Vec::new();
1622 let r = {
1623 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1624 f(&mut ctx)
1625 };
1626 (out.into_iter().collect(), r)
1627 }
1628
1629 /// Like `with_ctx` but also returns the deferred vec (for capture assertions).
1630 fn with_ctx_d<R>(f: impl FnOnce(&mut Context) -> R) -> (Vec<Event>, Vec<Deferred>, R) {
1631 let mut out = VecDeque::new();
1632 let mut timers = TimerQueue::new();
1633 let mut deferred: Vec<Deferred> = Vec::new();
1634 let r = {
1635 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1636 f(&mut ctx)
1637 };
1638 (out.into_iter().collect(), deferred, r)
1639 }
1640
1641 fn key(k: Key) -> Event {
1642 Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
1643 }
1644
1645 fn ctrl_key(k: Key) -> Event {
1646 Event::KeyDown(KeyEvent::new(
1647 k,
1648 KeyModifiers {
1649 ctrl: true,
1650 ..Default::default()
1651 },
1652 ))
1653 }
1654
1655 fn char_key(c: char) -> Event {
1656 Event::KeyDown(KeyEvent::new(Key::Char(c), KeyModifiers::default()))
1657 }
1658
1659 /// Build a selected field with `data`, cursor at the end, no scroll.
1660 fn field(width: i32, data: &str) -> InputLine {
1661 let mut il = InputLine::with_limit(Rect::new(0, 0, width, 1), 256);
1662 il.state.state.selected = true;
1663 il.data = data.to_string();
1664 il.cur_pos = data.len() as i32;
1665 il
1666 }
1667
1668 fn send_key(il: &mut InputLine, ev: &mut Event) {
1669 with_ctx(|ctx| il.handle_event(ev, ctx));
1670 }
1671
1672 fn mouse_down_at(x: i32, y: i32) -> Event {
1673 Event::MouseDown(MouseEvent {
1674 position: Point::new(x, y),
1675 buttons: MouseButtons {
1676 left: true,
1677 ..Default::default()
1678 },
1679 flags: MouseEventFlags::default(),
1680 wheel: MouseWheel::None,
1681 modifiers: KeyModifiers::default(),
1682 })
1683 }
1684
1685 /// A middle-button press — the X11 paste gesture.
1686 fn middle_down_at(x: i32, y: i32) -> Event {
1687 Event::MouseDown(MouseEvent {
1688 position: Point::new(x, y),
1689 buttons: MouseButtons {
1690 middle: true,
1691 ..Default::default()
1692 },
1693 flags: MouseEventFlags::default(),
1694 wheel: MouseWheel::None,
1695 modifiers: KeyModifiers::default(),
1696 })
1697 }
1698
1699 fn mouse_auto_at(x: i32, y: i32) -> Event {
1700 Event::MouseAuto(MouseEvent {
1701 position: Point::new(x, y),
1702 buttons: MouseButtons {
1703 left: true,
1704 ..Default::default()
1705 },
1706 ..Default::default()
1707 })
1708 }
1709
1710 fn mouse_move_at(x: i32, y: i32) -> Event {
1711 Event::MouseMove(MouseEvent {
1712 position: Point::new(x, y),
1713 buttons: MouseButtons {
1714 left: true,
1715 ..Default::default()
1716 },
1717 ..Default::default()
1718 })
1719 }
1720
1721 fn mouse_up_at(x: i32, y: i32) -> Event {
1722 Event::MouseUp(MouseEvent {
1723 position: Point::new(x, y),
1724 ..Default::default()
1725 })
1726 }
1727
1728 /// Build a selected field with an id (simulating Group::insert).
1729 fn field_with_id(width: i32, data: &str) -> (InputLine, crate::view::ViewId) {
1730 let mut il = field(width, data);
1731 let id = crate::view::ViewId::next();
1732 il.state.id = Some(id);
1733 (il, id)
1734 }
1735
1736 // -- snapshot -----------------------------------------------------------
1737
1738 /// A field with content shorter than its width: text from col 1, no arrows.
1739 #[test]
1740 fn snapshot_basic_field() {
1741 let mut il = field(12, "hello");
1742 il.cur_pos = 0;
1743 il.first_pos = 0;
1744 insta::assert_snapshot!(render(&mut il));
1745 }
1746
1747 /// A selection covering "ell" is highlighted.
1748 #[test]
1749 fn snapshot_with_selection() {
1750 let mut il = field(12, "hello");
1751 il.sel_start = 1;
1752 il.sel_end = 4;
1753 il.first_pos = 0;
1754 insta::assert_snapshot!(render(&mut il));
1755 }
1756
1757 /// A string wider than the field, scrolled — both arrows present.
1758 #[test]
1759 fn snapshot_scrolled_both_arrows() {
1760 let mut il = field(8, "abcdefghijklmnop");
1761 il.first_pos = 4;
1762 il.cur_pos = 8;
1763 insta::assert_snapshot!(render(&mut il));
1764 }
1765
1766 /// DISCRIMINATING: a scrolled field whose selection covers the start
1767 /// (`sel_start = 0`, off the visible left edge). Because tvision-rs REDRAWS the
1768 /// selection (no attr-only paint), the highlighted cells must show the
1769 /// *visible scrolled glyphs* ("efgh…"), NOT the head of the string ("abcd…").
1770 /// This is exactly the state `select_all(true, true)` produces on a long
1771 /// field gaining focus.
1772 #[test]
1773 fn snapshot_scrolled_selection_from_start() {
1774 let mut il = field(8, "abcdefghijklmnop");
1775 il.first_pos = 4; // visible window starts at column 4 ('e')
1776 il.sel_start = 0; // selection begins off the left edge
1777 il.sel_end = 16; // …and runs to the end
1778 il.cur_pos = 16;
1779 let snap = render(&mut il);
1780 // The visible text is "efghij" (cols 1..7), arrows at 0 and 7. The
1781 // highlighted glyphs must be the scrolled ones, not "abcd…".
1782 assert!(
1783 snap.contains("◄efghij►"),
1784 "selection redraw must keep the scrolled glyphs, got:\n{snap}"
1785 );
1786 insta::assert_snapshot!(snap);
1787 }
1788
1789 /// classic_blue frozen: InputSurface, InputNormal, and InputInactive all
1790 /// resolve to the same colour in `classic_blue`, so a default field
1791 /// renders byte-identically to the pre-existing golden regardless of
1792 /// which of the three the three-surface rule picks. The fixture is
1793 /// unfocused + owner_active, which is the discriminating path — it now
1794 /// selects `Role::InputSurface` by DEFAULT (no opt-in needed). Guards the
1795 /// zero-pixel-change guarantee of the focus-surface generalization; keeps
1796 /// the pre-existing golden (explicit snapshot name) rather than minting a
1797 /// new one under the renamed test.
1798 #[test]
1799 fn snapshot_default_three_surface_classic_blue_identical() {
1800 let mut il = field(12, "hello");
1801 il.cur_pos = 0;
1802 il.first_pos = 0;
1803
1804 let snap = render(&mut il);
1805 insta::assert_snapshot!("snapshot_self_focus_classic_blue_identical", snap);
1806 }
1807
1808 // -- editing: ASCII -----------------------------------------------------
1809
1810 #[test]
1811 fn insert_char_at_cursor() {
1812 let mut il = field(12, "");
1813 let mut ev = char_key('a');
1814 send_key(&mut il, &mut ev);
1815 assert!(ev.is_nothing());
1816 assert_eq!(il.data, "a");
1817 assert_eq!(il.cur_pos, 1);
1818 }
1819
1820 #[test]
1821 fn home_end_left_right() {
1822 let mut il = field(12, "abc");
1823 let mut ev = key(Key::Home);
1824 send_key(&mut il, &mut ev);
1825 assert_eq!(il.cur_pos, 0);
1826 let mut ev = key(Key::Right);
1827 send_key(&mut il, &mut ev);
1828 assert_eq!(il.cur_pos, 1);
1829 let mut ev = key(Key::End);
1830 send_key(&mut il, &mut ev);
1831 assert_eq!(il.cur_pos, 3);
1832 let mut ev = key(Key::Left);
1833 send_key(&mut il, &mut ev);
1834 assert_eq!(il.cur_pos, 2);
1835 }
1836
1837 #[test]
1838 fn backspace_and_delete() {
1839 let mut il = field(12, "abc"); // cur at 3
1840 let mut ev = key(Key::Backspace);
1841 send_key(&mut il, &mut ev);
1842 assert_eq!(il.data, "ab");
1843 assert_eq!(il.cur_pos, 2);
1844
1845 let mut il = field(12, "abc");
1846 il.cur_pos = 0;
1847 let mut ev = key(Key::Delete);
1848 send_key(&mut il, &mut ev);
1849 assert_eq!(il.data, "bc");
1850 assert_eq!(il.cur_pos, 0);
1851 }
1852
1853 #[test]
1854 fn ctrl_y_clears() {
1855 let mut il = field(12, "abc");
1856 let mut ev = ctrl_key(Key::Char('y'));
1857 send_key(&mut il, &mut ev);
1858 assert_eq!(il.data, "");
1859 assert_eq!(il.cur_pos, 0);
1860 assert!(ev.is_nothing());
1861 }
1862
1863 #[test]
1864 fn ctrl_word_nav() {
1865 let mut il = field(20, "foo bar baz");
1866 il.cur_pos = 0;
1867 let mut ev = ctrl_key(Key::Right);
1868 send_key(&mut il, &mut ev);
1869 assert_eq!(il.cur_pos, 4, "to start of 'bar'");
1870 let mut ev = ctrl_key(Key::Right);
1871 send_key(&mut il, &mut ev);
1872 assert_eq!(il.cur_pos, 8, "to start of 'baz'");
1873 let mut ev = ctrl_key(Key::Left);
1874 send_key(&mut il, &mut ev);
1875 assert_eq!(il.cur_pos, 4, "back to start of 'bar'");
1876 }
1877
1878 #[test]
1879 fn unhandled_key_left_live() {
1880 // Tab and Enter are not edit/nav keys: the event must stay live so the
1881 // dialog can act on it (Esc/Enter routing).
1882 let mut il = field(12, "abc");
1883 let mut ev = key(Key::Tab);
1884 send_key(&mut il, &mut ev);
1885 assert!(!ev.is_nothing(), "Tab must propagate uncleared");
1886 let mut ev = key(Key::Enter);
1887 send_key(&mut il, &mut ev);
1888 assert!(!ev.is_nothing(), "Enter must propagate uncleared");
1889 }
1890
1891 #[test]
1892 fn ins_toggles_cursor_ins() {
1893 let mut il = field(12, "abc");
1894 assert!(!il.state.state.cursor_ins);
1895 let mut ev = key(Key::Insert);
1896 send_key(&mut il, &mut ev);
1897 assert!(il.state.state.cursor_ins);
1898 let mut ev = key(Key::Insert);
1899 send_key(&mut il, &mut ev);
1900 assert!(!il.state.state.cursor_ins);
1901 }
1902
1903 // -- editing: MULTI-BYTE (mandatory) ------------------------------------
1904
1905 #[test]
1906 fn insert_multibyte_no_panic() {
1907 let mut il = field(12, "");
1908 let mut ev = char_key('ä'); // 2 bytes
1909 send_key(&mut il, &mut ev);
1910 assert_eq!(il.data, "ä");
1911 assert_eq!(il.cur_pos, 2, "cursor advances by byte length");
1912 let mut ev = char_key('€'); // 3 bytes
1913 send_key(&mut il, &mut ev);
1914 assert_eq!(il.data, "ä€");
1915 assert_eq!(il.cur_pos, 5);
1916 }
1917
1918 #[test]
1919 fn backspace_over_multibyte_no_panic() {
1920 let mut il = field(12, "aä€"); // bytes: a(1) ä(2) €(3) = 6
1921 assert_eq!(il.cur_pos, 6);
1922 let mut ev = key(Key::Backspace);
1923 send_key(&mut il, &mut ev);
1924 assert_eq!(il.data, "aä", "deleted the 3-byte €");
1925 assert_eq!(il.cur_pos, 3);
1926 let mut ev = key(Key::Backspace);
1927 send_key(&mut il, &mut ev);
1928 assert_eq!(il.data, "a", "deleted the 2-byte ä");
1929 assert_eq!(il.cur_pos, 1);
1930 }
1931
1932 #[test]
1933 fn delete_multibyte_no_panic() {
1934 let mut il = field(12, "aä€");
1935 il.cur_pos = 1; // before ä
1936 let mut ev = key(Key::Delete);
1937 send_key(&mut il, &mut ev);
1938 assert_eq!(il.data, "a€", "deleted the 2-byte ä");
1939 assert_eq!(il.cur_pos, 1);
1940 }
1941
1942 #[test]
1943 fn left_right_over_multibyte_no_panic() {
1944 let mut il = field(12, "aä€");
1945 il.cur_pos = 0;
1946 let mut ev = key(Key::Right);
1947 send_key(&mut il, &mut ev);
1948 assert_eq!(il.cur_pos, 1, "over 'a'");
1949 let mut ev = key(Key::Right);
1950 send_key(&mut il, &mut ev);
1951 assert_eq!(il.cur_pos, 3, "over 2-byte 'ä'");
1952 let mut ev = key(Key::Right);
1953 send_key(&mut il, &mut ev);
1954 assert_eq!(il.cur_pos, 6, "over 3-byte '€'");
1955 let mut ev = key(Key::Left);
1956 send_key(&mut il, &mut ev);
1957 assert_eq!(il.cur_pos, 3, "back over '€'");
1958 }
1959
1960 #[test]
1961 fn ctrl_word_nav_over_multibyte_no_panic() {
1962 // Words separated by ASCII spaces, but containing multibyte chars.
1963 let mut il = field(20, "äé foo");
1964 il.cur_pos = 0;
1965 let mut ev = ctrl_key(Key::Right);
1966 send_key(&mut il, &mut ev);
1967 // "äé" is 4 bytes, then a space at byte 4, then 'f' at byte 5.
1968 assert_eq!(il.cur_pos, 5, "to start of 'foo'");
1969 let mut ev = ctrl_key(Key::Left);
1970 send_key(&mut il, &mut ev);
1971 assert_eq!(il.cur_pos, 0, "back to start");
1972 }
1973
1974 // -- valid() ------------------------------------------------------------
1975
1976 struct RejectAll;
1977 impl Validator for RejectAll {
1978 fn is_valid(&self, _s: &str) -> bool {
1979 false
1980 }
1981 }
1982
1983 #[test]
1984 fn valid_with_rejecting_validator() {
1985 let mut il = InputLine::new(
1986 Rect::new(0, 0, 12, 1),
1987 256,
1988 Some(Box::new(RejectAll)),
1989 LimitMode::MaxBytes,
1990 );
1991 il.data = "x".to_string();
1992 // A non-cancel command runs validate → false (and requests an error box).
1993 assert!(
1994 !with_ctx(|ctx| il.valid(Command::OK, ctx)).1,
1995 "rejecting validator blocks OK"
1996 );
1997 // cmCancel always passes (no validation).
1998 assert!(
1999 with_ctx(|ctx| il.valid(Command::CANCEL, ctx)).1,
2000 "cmCancel bypasses validation"
2001 );
2002 // cmValid consults status (RejectAll's status is the default OK).
2003 assert!(
2004 with_ctx(|ctx| il.valid(Command::VALID, ctx)).1,
2005 "cmValid consults status (OK)"
2006 );
2007 }
2008
2009 #[test]
2010 fn valid_without_validator_is_true() {
2011 let mut il = field(12, "anything");
2012 assert!(with_ctx(|ctx| il.valid(Command::OK, ctx)).1);
2013 assert!(with_ctx(|ctx| il.valid(Command::CANCEL, ctx)).1);
2014 assert!(with_ctx(|ctx| il.valid(Command::VALID, ctx)).1);
2015 }
2016
2017 /// A validator that rejects every candidate keystroke (`isValidInput` →
2018 /// false), but leaves `isValid` at its default. This exercises the
2019 /// reject/restore path in `check_valid`: the keyboard insertion branch
2020 /// `save_state()`s, mutates, then `check_valid(true)` rejects and
2021 /// `restore_state()`s — which the existing `is_valid`-only validators never
2022 /// reach (their `check_valid(true)` always returns true).
2023 struct RejectAllInput;
2024 impl Validator for RejectAllInput {
2025 fn is_valid_input(&self, _s: &mut String, _suppress: bool) -> bool {
2026 false
2027 }
2028 }
2029
2030 /// DISCRIMINATING: with a validator that rejects all input, a printable
2031 /// keystroke must revert the field to its pre-keystroke `data`/`cur_pos`,
2032 /// proving `save_state` → `check_valid(true)`'s reject branch →
2033 /// `restore_state` ran (the `is_valid`-only validators above never reach it,
2034 /// since their `check_valid(true)` always returns true).
2035 ///
2036 /// BITES if `restore_state`'s body is no-op'd: the keystroke first
2037 /// `delete_select()`s the active selection (`"bc"`), so without restore the
2038 /// field would be left mutated (`data == "adef"`, `cur_pos == 1`) instead of
2039 /// reverted (`data == "abcdef"`, `cur_pos == 4`).
2040 ///
2041 /// Note: `sel_start`/`sel_end` are NOT asserted against the saved 1/3 — the
2042 /// faithful C++ resets `selStart = selEnd = 0` after a printable key
2043 /// regardless of the validator outcome (`tinputli.cpp:459`, tvision-rs lines
2044 /// 643-645), so those offsets legitimately end at 0 here.
2045 #[test]
2046 fn rejected_input_restores_pre_keystroke_state() {
2047 let mut il = InputLine::new(
2048 Rect::new(0, 0, 12, 1),
2049 256,
2050 Some(Box::new(RejectAllInput)),
2051 LimitMode::MaxBytes,
2052 );
2053 il.state.state.selected = true;
2054 // A non-empty active selection + a cursor not at 0, so that the
2055 // keystroke's delete_select() visibly mutates the field and a no-op'd
2056 // restore_state would leave that mutation in place.
2057 il.data = "abcdef".to_string();
2058 il.cur_pos = 4;
2059 il.first_pos = 0;
2060 il.sel_start = 1;
2061 il.sel_end = 3;
2062
2063 // Drive a printable keystroke. The insertion branch does
2064 // save_state → delete_select → check_valid(true)=false → restore_state.
2065 let mut ev = char_key('Z');
2066 send_key(&mut il, &mut ev);
2067
2068 // Reverted to the saved snapshot: the rejected input changed nothing.
2069 assert_eq!(il.data, "abcdef", "rejected input must not change data");
2070 assert_eq!(il.cur_pos, 4, "cur_pos restored from save_state");
2071 assert_eq!(il.first_pos, 0, "first_pos restored from save_state");
2072 }
2073
2074 // -- value / set_value ----------------------------------------------------
2075
2076 #[test]
2077 fn value_set_value_round_trip() {
2078 let mut il = field(12, "");
2079 il.set_value(FieldValue::Text("hello".to_string()));
2080 assert_eq!(il.data, "hello");
2081 assert_eq!(il.value(), Some(FieldValue::Text("hello".to_string())));
2082 // set_value selects all (enable=true): cursor at end, sel covers all.
2083 assert_eq!(il.sel_start, 0);
2084 assert_eq!(il.sel_end, 5);
2085 assert_eq!(il.cur_pos, 5);
2086 }
2087
2088 // -- value / set_value with a transfer-enabled validator ------------------
2089
2090 /// REGRESSION GUARD: with NO validator, `value()` still yields `Text`
2091 /// (the transfer hooks default to `None`, so the Text path is unchanged).
2092 #[test]
2093 fn value_no_validator_is_text() {
2094 let mut il = field(12, "");
2095 il.data = "42".to_string();
2096 assert_eq!(il.value(), Some(FieldValue::Text("42".to_string())));
2097 }
2098
2099 /// REGRESSION GUARD: a validator is PRESENT but transfer is OFF — `value()`
2100 /// must still yield `Text`. Pins the `and_then(...) → None` fall-through (the
2101 /// exact path that breaks if the transfer gate is later inverted or
2102 /// `transfer_get` made unconditional); no other test bites it.
2103 #[test]
2104 fn value_with_non_transfer_validator_is_text() {
2105 use crate::validate::RangeValidator;
2106 // RangeValidator with transfer NOT enabled → transfer_get returns None.
2107 let rv = RangeValidator::new(0, 100);
2108 let mut il = InputLine::new(
2109 Rect::new(0, 0, 12, 1),
2110 256,
2111 Some(Box::new(rv)),
2112 LimitMode::MaxBytes,
2113 );
2114 il.data = "42".to_string();
2115 assert_eq!(il.value(), Some(FieldValue::Text("42".to_string())));
2116 }
2117
2118 #[test]
2119 fn value_with_transfer_validator_is_int() {
2120 use crate::validate::RangeValidator;
2121 let mut rv = RangeValidator::new(0, 100);
2122 rv.set_transfer(true);
2123 let mut il = InputLine::new(
2124 Rect::new(0, 0, 12, 1),
2125 256,
2126 Some(Box::new(rv)),
2127 LimitMode::MaxBytes,
2128 );
2129 il.data = "42".to_string();
2130 assert_eq!(il.value(), Some(FieldValue::Int(42)));
2131 }
2132
2133 #[test]
2134 fn set_value_with_transfer_validator_formats_int() {
2135 use crate::validate::RangeValidator;
2136 let mut rv = RangeValidator::new(0, 100);
2137 rv.set_transfer(true);
2138 let mut il = InputLine::new(
2139 Rect::new(0, 0, 12, 1),
2140 256,
2141 Some(Box::new(rv)),
2142 LimitMode::MaxBytes,
2143 );
2144 il.set_value(FieldValue::Int(42));
2145 assert_eq!(il.data, "42", "Int formatted into the field text");
2146 // selectAll runs on the transfer path too.
2147 assert_eq!(il.sel_start, 0);
2148 assert_eq!(il.sel_end, 2);
2149 assert_eq!(il.cur_pos, 2);
2150 }
2151
2152 // -- cursor / firstPos scroll-follow ------------------------------------
2153
2154 /// ASCII scroll-follow: a string wider than the field, cursor at the end.
2155 /// firstPos must follow so the cursor stays visible.
2156 #[test]
2157 fn scroll_follow_ascii() {
2158 // width 6 (so text area is cols 1..6 = 5 columns).
2159 let mut il = field(6, "");
2160 il.state.state.focused = true; // cursor_request gates on focused
2161 for c in "abcdefgh".chars() {
2162 let mut ev = char_key(c);
2163 send_key(&mut il, &mut ev);
2164 }
2165 assert_eq!(il.data, "abcdefgh");
2166 assert_eq!(il.cur_pos, 8);
2167 // cur_width = 8. firstPos clamp: i = cur_width - size.x + 2 = 8-6+2 = 4.
2168 assert_eq!(il.first_pos, 4, "firstPos follows the cursor (column)");
2169 // cursor screen col = displayedPos(curPos) - firstPos + 1 = 8-4+1 = 5.
2170 assert_eq!(il.cursor_request(), Some(Point::new(5, 0)));
2171 }
2172
2173 /// DISCRIMINATING multibyte scroll-follow: distinguishes the column-vs-byte
2174 /// bug. A field of WIDE glyphs ("中中中中", each 2 columns wide, 3 bytes) in a
2175 /// field narrower than its width: firstPos must be in COLUMNS, not bytes.
2176 #[test]
2177 fn scroll_follow_wide_glyphs_is_columns_not_bytes() {
2178 // size.x = 6 → text area 5 columns. "中" is width 2, len 3 bytes.
2179 let mut il = field(6, "");
2180 il.state.state.focused = true; // cursor_request gates on focused
2181 for _ in 0..4 {
2182 let mut ev = char_key('中');
2183 send_key(&mut il, &mut ev);
2184 }
2185 // data = "中中中中": 12 bytes, 8 display columns.
2186 assert_eq!(il.data.len(), 12);
2187 assert_eq!(text::width(&il.data), 8);
2188 assert_eq!(il.cur_pos, 12, "cur_pos is a BYTE offset (12)");
2189 // cur_width (COLUMNS) = displayedPos(12) = 8.
2190 // firstPos clamp: i = 8 - 6 + 2 = 4 (a COLUMN). If firstPos were treated
2191 // as bytes it would be 12 - 6 + 2 = 8 — this asserts the column value.
2192 assert_eq!(
2193 il.first_pos, 4,
2194 "firstPos is a display COLUMN (4), not a byte offset (would be 8)"
2195 );
2196 // cursor screen col = displayedPos(curPos) - firstPos + 1 = 8 - 4 + 1 = 5.
2197 assert_eq!(
2198 il.cursor_request(),
2199 Some(Point::new(5, 0)),
2200 "cursor column = displayedPos(curPos) - firstPos + 1"
2201 );
2202 }
2203
2204 // -- cursor_request / set_cursor_pos (direct-write desync regression) ---
2205
2206 /// REGRESSION: writing `cur_pos`/`first_pos` directly (bypassing any
2207 /// setter) must be reflected on the very next `cursor_request` — there is
2208 /// no cached cursor to desync, since it is derived fresh every call.
2209 #[test]
2210 fn cursor_request_reflects_direct_field_writes() {
2211 let mut il = field(12, "hello world");
2212 il.state.state.focused = true;
2213 il.select_all(true, true);
2214 il.cur_pos = 0;
2215 il.first_pos = 0;
2216 assert_eq!(il.cursor_request(), Some(Point::new(1, 0)));
2217 }
2218
2219 #[test]
2220 fn set_cursor_pos_collapses_selection() {
2221 let mut il = field(12, "hello world");
2222 il.state.state.focused = true;
2223 il.sel_start = 2;
2224 il.sel_end = 7;
2225 il.first_pos = 0;
2226 il.set_cursor_pos(3);
2227 assert_eq!(il.cur_pos, 3);
2228 assert_eq!(il.sel_start, 0);
2229 assert_eq!(il.sel_end, 0);
2230 assert_eq!(
2231 il.cursor_request(),
2232 Some(Point::new(4, 0)),
2233 "col = displayedPos(3) - first_pos(0) + 1"
2234 );
2235 }
2236
2237 #[test]
2238 fn set_cursor_pos_clamps_past_end() {
2239 let mut il = field(12, "abc");
2240 il.set_cursor_pos(100);
2241 assert_eq!(il.cur_pos, 3, "clamped to data.len()");
2242 }
2243
2244 #[test]
2245 fn set_cursor_pos_scrolls_into_view_when_offscreen_right() {
2246 // width 6 (text area is 5 columns).
2247 let mut il = field(6, "abcdefgh");
2248 il.first_pos = 0;
2249 il.set_cursor_pos(8); // end of data
2250 // cur_width = displayedPos(8) = 8; i = 8 - 6 + 2 = 4.
2251 assert_eq!(
2252 il.first_pos, 4,
2253 "first_pos scrolled so the caret stays visible"
2254 );
2255 assert!(
2256 il.displayed_pos(il.cur_pos) - il.first_pos < il.state.size.x - 1,
2257 "caret column must stay within the visible window"
2258 );
2259 }
2260
2261 /// No panic when the requested offset lands mid-grapheme; it snaps down to
2262 /// the previous `char` boundary.
2263 #[test]
2264 fn set_cursor_pos_snaps_off_boundary_to_previous_boundary() {
2265 // bytes: a(1) ä(2, offsets 1..3) €(3, offsets 3..6).
2266 let mut il = field(12, "aä€");
2267 il.set_cursor_pos(2); // inside the 2-byte 'ä'
2268 assert_eq!(il.cur_pos, 1, "snapped down to the boundary before 'ä'");
2269 }
2270
2271 #[test]
2272 fn home_end_smoke() {
2273 let mut il = field(12, "hello");
2274 il.cur_pos = 2;
2275 il.home();
2276 assert_eq!(il.cur_pos, 0);
2277 il.end();
2278 assert_eq!(il.cur_pos, 5);
2279 }
2280
2281 // -- mouse single-shot --------------------------------------------------
2282
2283 #[test]
2284 fn mouse_down_positions_cursor() {
2285 let mut il = field(12, "hello");
2286 il.cur_pos = 0;
2287 // Click at view-local x=3 → pos = mouse.x + firstPos - 1 = 3 + 0 - 1 = 2.
2288 let mut ev = Event::MouseDown(MouseEvent {
2289 position: Point::new(3, 0),
2290 buttons: MouseButtons {
2291 left: true,
2292 ..Default::default()
2293 },
2294 ..Default::default()
2295 });
2296 send_key(&mut il, &mut ev);
2297 assert!(ev.is_nothing(), "mouse-down is consumed");
2298 assert_eq!(il.cur_pos, 2);
2299 }
2300
2301 /// DISCRIMINATING (M1): a field NARROWER than its content, double-clicked,
2302 /// must select-all AND SCROLL the end into view. The C++ selectAll(True)'s
2303 /// scroll arg defaults to True (dialogs.h:177); the `false` regression would
2304 /// leave first_pos at 0.
2305 #[test]
2306 fn double_click_scrolls_end_into_view() {
2307 // width 8, content 16 cols. Click at x=3 (not an edge → delta 0, so the
2308 // double-click branch runs).
2309 let mut il = field(8, "abcdefghijklmnop");
2310 il.cur_pos = 0;
2311 il.first_pos = 0;
2312 let mut ev = Event::MouseDown(MouseEvent {
2313 position: Point::new(3, 0),
2314 buttons: MouseButtons {
2315 left: true,
2316 ..Default::default()
2317 },
2318 flags: crate::event::MouseEventFlags {
2319 double_click: true,
2320 ..Default::default()
2321 },
2322 ..Default::default()
2323 });
2324 send_key(&mut il, &mut ev);
2325 assert!(ev.is_nothing(), "mouse-down is consumed");
2326 // select_all(true, true): cur_pos = 16, sel covers all.
2327 assert_eq!(il.cur_pos, 16);
2328 assert_eq!(il.sel_start, 0);
2329 assert_eq!(il.sel_end, 16);
2330 // The scroll: first_pos = max(0, displayedPos(16) - 8 + 2) = 16-8+2 = 10.
2331 // With the `false` regression this would stay 0 — so this BITES.
2332 assert!(
2333 il.first_pos > 0,
2334 "double-click must scroll the end into view (first_pos > 0), got {}",
2335 il.first_pos
2336 );
2337 assert_eq!(
2338 il.first_pos, 10,
2339 "first_pos = displayedPos(curPos) - size.x + 2"
2340 );
2341 }
2342
2343 /// DISCRIMINATING (m1): a single edge mouse-down on a scrolled-out field
2344 /// scrolls by ONE step (the C++ do/while's first iteration always runs),
2345 /// before any deferred press-and-hold auto-repeat.
2346 #[test]
2347 fn single_edge_mouse_down_scrolls_one_step() {
2348 // width 8, content 16 cols, scrolled so the left edge can scroll left.
2349 let mut il = field(8, "abcdefghijklmnop");
2350 il.first_pos = 5;
2351 il.cur_pos = 8;
2352 // Click at the left edge (x=0 → mouse_delta = -1, can_scroll(-1) true).
2353 let mut ev = Event::MouseDown(MouseEvent {
2354 position: Point::new(0, 0),
2355 buttons: MouseButtons {
2356 left: true,
2357 ..Default::default()
2358 },
2359 ..Default::default()
2360 });
2361 send_key(&mut il, &mut ev);
2362 assert!(ev.is_nothing(), "mouse-down is consumed");
2363 assert_eq!(
2364 il.first_pos, 4,
2365 "single edge mouse-down scrolls one step left"
2366 );
2367
2368 // Right edge: x = size.x - 1 = 7 → mouse_delta = 1. can_scroll(1) true
2369 // while content extends past the window.
2370 let mut il = field(8, "abcdefghijklmnop");
2371 il.first_pos = 2;
2372 il.cur_pos = 8;
2373 let mut ev = Event::MouseDown(MouseEvent {
2374 position: Point::new(7, 0),
2375 buttons: MouseButtons {
2376 left: true,
2377 ..Default::default()
2378 },
2379 ..Default::default()
2380 });
2381 send_key(&mut il, &mut ev);
2382 assert_eq!(
2383 il.first_pos, 3,
2384 "single edge mouse-down scrolls one step right"
2385 );
2386 }
2387
2388 // -- set_state selects all ----------------------------------------------
2389
2390 #[test]
2391 fn set_state_selected_selects_all() {
2392 let mut il = field(12, "hello");
2393 il.sel_start = 0;
2394 il.sel_end = 0;
2395 il.state.state.selected = false;
2396 with_ctx(|ctx| il.set_state(StateFlag::Selected, true, ctx));
2397 assert!(il.state.state.selected);
2398 assert_eq!(il.sel_start, 0);
2399 assert_eq!(il.sel_end, 5, "selectAll on becoming selected");
2400 assert_eq!(il.cur_pos, 5);
2401 }
2402
2403 #[test]
2404 fn set_state_opt_out_does_not_select_all_on_focus() {
2405 let mut il = field(12, "hello");
2406 il.set_select_all_on_focus(false);
2407 il.sel_start = 0;
2408 il.sel_end = 0;
2409 il.cur_pos = 0;
2410 il.state.state.selected = false;
2411 with_ctx(|ctx| il.set_state(StateFlag::Selected, true, ctx));
2412 assert!(il.state.state.selected, "still becomes selected (focused)");
2413 assert_eq!(
2414 il.sel_end, 0,
2415 "opted out: no select-all on focus gain (selection untouched)"
2416 );
2417 assert_eq!(
2418 il.cur_pos, 0,
2419 "opted out: caret not moved to end on focus gain"
2420 );
2421 }
2422
2423 #[test]
2424 fn set_state_opt_out_still_clears_selection_on_focus_loss() {
2425 let mut il = field(12, "hello");
2426 il.set_select_all_on_focus(false);
2427 // A pre-existing (e.g. drag) selection while focused.
2428 il.state.state.selected = true;
2429 il.sel_start = 1;
2430 il.sel_end = 4;
2431 with_ctx(|ctx| il.set_state(StateFlag::Selected, false, ctx));
2432 assert!(!il.state.state.selected);
2433 assert_eq!(
2434 il.sel_end, 0,
2435 "focus loss clears the selection even when opted out of select-all-on-focus"
2436 );
2437 }
2438
2439 // -- drag-select tracking (evMouseMove | evMouseAuto) ---------------------
2440 //
2441 // These tests drive the tracking arms directly (as the pump's Deferred::MouseTrack
2442 // apply does) with field-local positions. The capture itself is unit-tested
2443 // in capture::tests; here we verify the widget's loop body is correct.
2444
2445 /// Mouse-down in the text area (not on an edge) arms drag-select tracking:
2446 /// anchor + cursor at the click, `tracking == true`, `tracking_drag == true`,
2447 /// and a `PushCapture` is deferred.
2448 #[test]
2449 fn track_drag_mouse_down_arms_capture() {
2450 let (mut il, _id) = field_with_id(20, "hello world");
2451 // Mouse-down at col 4 (character 'd' area, well inside the field).
2452 let mut ev = mouse_down_at(4, 0);
2453 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2454 assert!(ev.is_nothing(), "mouse-down consumed");
2455 assert!(il.tracking, "tracking armed");
2456 assert!(il.tracking_drag, "drag branch selected");
2457 assert!(
2458 deferred
2459 .iter()
2460 .any(|d| matches!(d, Deferred::PushCapture(_))),
2461 "PushCapture deferred for drag-select tracking"
2462 );
2463 // anchor and cur_pos are both at the clicked column (field-local: col 4 →
2464 // first_pos=0, so byte offset for col 3 = 3).
2465 assert_eq!(il.anchor, il.cur_pos, "anchor == cursor at click time");
2466 }
2467
2468 /// `MouseMove` while tracking (drag-select): cursor moves to the new position
2469 /// and the selection block is adjusted (tinputli.cpp:332-334).
2470 #[test]
2471 fn track_drag_move_extends_selection() {
2472 let (mut il, _id) = field_with_id(20, "hello world");
2473 // Down at col 2 (byte 1 = 'e').
2474 let mut ev = mouse_down_at(2, 0);
2475 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2476 assert!(il.tracking_drag);
2477
2478 // Move to col 8 (byte 7 = 'o').
2479 let mut ev = mouse_move_at(8, 0);
2480 let (_, _, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2481 assert!(ev.is_nothing(), "tracked move consumed");
2482 assert!(il.tracking, "still tracking after move");
2483 // sel_start <= anchor, sel_end >= anchor.
2484 assert!(il.sel_start <= il.anchor, "sel_start ≤ anchor");
2485 assert!(il.sel_end >= il.anchor, "sel_end ≥ anchor");
2486 // The selection must span more than a single point.
2487 assert!(
2488 il.sel_end > il.sel_start,
2489 "selection extends: sel_start={} sel_end={}",
2490 il.sel_start,
2491 il.sel_end
2492 );
2493 }
2494
2495 /// `MouseAuto` while tracking (drag-select): if the cursor is at the left edge
2496 /// (x <= 0), `first_pos` decrements (edge-scroll; tinputli.cpp:327-330).
2497 /// Also updates `cur_pos` and `sel` (the drag body still runs after edge-scroll).
2498 #[test]
2499 fn track_drag_auto_edge_scrolls_and_updates_cursor() {
2500 // Build a long string in a narrow field so we can trigger the edge scroll.
2501 let (mut il, _id) = field_with_id(8, "abcdefghijklmnop");
2502 il.first_pos = 5; // scrolled right a bit
2503 il.cur_pos = 5; // cursor in the middle
2504
2505 // Mouse-down in the middle of the field to arm tracking.
2506 let mut ev = mouse_down_at(4, 0);
2507 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2508 let first_pos_before = il.first_pos;
2509
2510 // MouseAuto at x = 0 (left edge): `mouse_delta` returns -1, `can_scroll(-1)`
2511 // should return true (first_pos > 0), so first_pos should decrease.
2512 let mut ev = mouse_auto_at(0, 0);
2513 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2514 assert!(ev.is_nothing(), "tracked auto consumed");
2515 assert!(il.tracking, "still tracking");
2516 assert!(
2517 il.first_pos < first_pos_before,
2518 "first_pos scrolled left: was {}, now {}",
2519 first_pos_before,
2520 il.first_pos
2521 );
2522 }
2523
2524 /// `MouseUp` clears the tracking flag (post-loop code).
2525 #[test]
2526 fn track_drag_mouse_up_clears_tracking() {
2527 let (mut il, _id) = field_with_id(20, "hello world");
2528 let mut ev = mouse_down_at(4, 0);
2529 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2530 assert!(il.tracking);
2531
2532 let mut ev = mouse_up_at(4, 0);
2533 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2534 assert!(ev.is_nothing(), "MouseUp consumed");
2535 assert!(!il.tracking, "tracking cleared on MouseUp");
2536 }
2537
2538 /// A stray `MouseUp` (not tracking) falls through — the guard.
2539 #[test]
2540 fn track_stray_mouse_up_falls_through() {
2541 let (mut il, _id) = field_with_id(20, "hello world");
2542 // No tracking armed.
2543 let mut ev = mouse_up_at(4, 0);
2544 let (_, _, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2545 assert!(
2546 !ev.is_nothing(),
2547 "stray MouseUp falls through (not consumed)"
2548 );
2549 }
2550
2551 /// A `MouseMove` during an EDGE-scroll track falls through unconsumed —
2552 /// the C++ edge loop is auto-only-masked (two-separate-masked-loops, same
2553 /// guard discipline as the scrollbar arms).
2554 #[test]
2555 fn track_move_during_edge_track_falls_through() {
2556 let (mut il, _id) = field_with_id(8, "abcdefghijklmnop");
2557 il.first_pos = 0;
2558
2559 // Arm the edge branch (auto-only) via a right-edge down.
2560 let mut down = mouse_down_at(7, 0);
2561 with_ctx_d(|ctx| il.handle_event(&mut down, ctx));
2562 assert!(il.tracking && !il.tracking_drag, "edge track armed");
2563 let cur_pos_before = il.cur_pos;
2564
2565 // A MouseMove must fall through: unconsumed, no cursor/selection change.
2566 let mut mv = mouse_move_at(3, 0);
2567 with_ctx_d(|ctx| il.handle_event(&mut mv, ctx));
2568 assert!(
2569 !mv.is_nothing(),
2570 "MouseMove during edge track falls through unconsumed"
2571 );
2572 assert_eq!(il.cur_pos, cur_pos_before, "no cursor change");
2573 }
2574
2575 // -- edge auto-scroll tracking (evMouseAuto only) -------------------------
2576
2577 /// Mouse-down on the right scroll edge (x >= size.x-1) arms auto-only tracking
2578 /// and does the first `first_pos += delta` step
2579 /// (tinputli.cpp:313-320 first iteration).
2580 #[test]
2581 fn track_edge_scroll_arms_capture() {
2582 // Field width 8, long string so can_scroll(1) is true.
2583 let (mut il, _id) = field_with_id(8, "abcdefghijklmnop");
2584 il.first_pos = 0;
2585
2586 // x = size.x - 1 = 7 → mouse_delta returns +1.
2587 let mut ev = mouse_down_at(7, 0);
2588 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2589 assert!(ev.is_nothing(), "consumed");
2590 assert!(il.tracking, "tracking armed for edge scroll");
2591 assert!(!il.tracking_drag, "edge branch, not drag branch");
2592 assert!(
2593 deferred
2594 .iter()
2595 .any(|d| matches!(d, Deferred::PushCapture(_))),
2596 "PushCapture deferred for edge auto-scroll"
2597 );
2598 // First iteration ran: first_pos scrolled right by 1.
2599 assert_eq!(il.first_pos, 1, "first_pos incremented on first iteration");
2600 }
2601
2602 /// `MouseAuto` while edge-scroll tracking repeats the scroll
2603 /// (tinputli.cpp:315-318).
2604 #[test]
2605 fn track_edge_scroll_auto_repeats() {
2606 let (mut il, _id) = field_with_id(8, "abcdefghijklmnop");
2607 il.first_pos = 0;
2608
2609 // Arm tracking via right-edge down.
2610 let mut ev = mouse_down_at(7, 0);
2611 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2612 let first_pos_after_down = il.first_pos;
2613
2614 // MouseAuto at x = 7 again → delta = +1, can_scroll(1) = true.
2615 let mut ev = mouse_auto_at(7, 0);
2616 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2617 assert!(ev.is_nothing(), "auto consumed");
2618 assert!(
2619 il.first_pos > first_pos_after_down,
2620 "first_pos scrolled further: was {}, now {}",
2621 first_pos_after_down,
2622 il.first_pos
2623 );
2624 // Cursor should NOT have been moved (edge branch does not drag-select).
2625 assert!(!il.tracking_drag, "edge branch stays edge branch");
2626 }
2627
2628 // -- updateCommands / canUpdateCommands graying ---------------------------
2629
2630 /// `canUpdateCommands()` is true only when both active AND selected.
2631 #[test]
2632 fn b1_can_update_commands_requires_active_and_selected() {
2633 let mut il = field(12, "hello");
2634 il.state.state.selected = true;
2635 il.state.state.active = false;
2636 assert!(
2637 !il.can_update_commands(),
2638 "selected but not active → canUpdate = false"
2639 );
2640 il.state.state.active = true;
2641 assert!(
2642 il.can_update_commands(),
2643 "both active+selected → canUpdate = true"
2644 );
2645 }
2646
2647 /// When active+selected, a handled key event pushes deferred
2648 /// Enable/Disable ops for cmCut/cmCopy based on whether a selection exists
2649 /// (faithful to updateCommands tail at tinputli.cpp:431).
2650 #[test]
2651 fn b1_key_event_updates_commands_when_active_selected() {
2652 let mut il = field(12, "hello");
2653 il.state.state.active = true;
2654 // Build a selection: sel_start=0, sel_end=3.
2655 il.sel_start = 0;
2656 il.sel_end = 3;
2657
2658 // A Home key: no selection change, but the tail always runs.
2659 let mut ev = key(Key::Home);
2660 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2661 // After Home, sel cleared (not extend_block): sel_start=sel_end=0.
2662 // So cmCut/cmCopy should be DISABLED.
2663 let has_disable_cut = deferred
2664 .iter()
2665 .any(|d| matches!(d, Deferred::DisableCommand(Command::CUT)));
2666 let has_disable_copy = deferred
2667 .iter()
2668 .any(|d| matches!(d, Deferred::DisableCommand(Command::COPY)));
2669 let has_enable_paste = deferred
2670 .iter()
2671 .any(|d| matches!(d, Deferred::EnableCommand(Command::PASTE)));
2672 assert!(has_disable_cut, "cmCut disabled when no selection");
2673 assert!(has_disable_copy, "cmCopy disabled when no selection");
2674 assert!(
2675 has_enable_paste,
2676 "cmPaste always enabled when active+selected"
2677 );
2678 }
2679
2680 /// Shift+Home extends the selection, so cmCut/cmCopy should be ENABLED.
2681 #[test]
2682 fn b1_extend_selection_enables_cut_copy() {
2683 let mut il = field(12, "hello");
2684 il.state.state.active = true;
2685 il.cur_pos = 5; // at end
2686 il.sel_start = 0;
2687 il.sel_end = 0;
2688
2689 // Shift+Home: extends selection from end to start.
2690 let mut ev = Event::KeyDown(KeyEvent::new(
2691 Key::Home,
2692 KeyModifiers {
2693 shift: true,
2694 ..Default::default()
2695 },
2696 ));
2697 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2698 // sel_start=0, sel_end=5 → selection exists → cmCut/cmCopy enabled.
2699 let has_enable_cut = deferred
2700 .iter()
2701 .any(|d| matches!(d, Deferred::EnableCommand(Command::CUT)));
2702 let has_enable_copy = deferred
2703 .iter()
2704 .any(|d| matches!(d, Deferred::EnableCommand(Command::COPY)));
2705 assert!(has_enable_cut, "cmCut enabled with selection");
2706 assert!(has_enable_copy, "cmCopy enabled with selection");
2707 }
2708
2709 /// `set_state` with sfSelected (gaining focus) transitions canUpdate from
2710 /// false→true, so update_commands is pushed (deferred ops for cmCut/cmCopy/
2711 /// cmPaste appear).
2712 #[test]
2713 fn b1_set_state_selected_pushes_update_commands() {
2714 let mut il = field(12, "");
2715 il.state.state.active = true;
2716 il.state.state.selected = false;
2717
2718 // set_state(Selected, true) → canUpdate transitions false→true.
2719 let (_, deferred, ()) = with_ctx_d(|ctx| il.set_state(StateFlag::Selected, true, ctx));
2720 let has_any_cmd = deferred
2721 .iter()
2722 .any(|d| matches!(d, Deferred::EnableCommand(_) | Deferred::DisableCommand(_)));
2723 assert!(
2724 has_any_cmd,
2725 "set_state(Selected,true) must push command enable/disable ops (B1)"
2726 );
2727 }
2728
2729 // -- clipboard cut/copy/paste ---------------------------------------------
2730
2731 /// cmCut with a selection: copies to clipboard (SetClipboard deferred) and
2732 /// deletes the selection from the field (faithful to tinputli.cpp:408-417).
2733 #[test]
2734 fn b3_cut_copies_to_clipboard_and_deletes_selection() {
2735 let mut il = field(12, "hello world");
2736 il.state.state.active = true;
2737 il.sel_start = 6; // "world"
2738 il.sel_end = 11;
2739
2740 let mut ev = Event::Command(Command::CUT);
2741 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2742 assert!(ev.is_nothing(), "cmCut is consumed");
2743 // Selection text copied to clipboard via deferred SetClipboard.
2744 let clipboard_text = deferred.iter().find_map(|d| {
2745 if let Deferred::SetClipboard(s) = d {
2746 Some(s.as_str())
2747 } else {
2748 None
2749 }
2750 });
2751 assert_eq!(
2752 clipboard_text,
2753 Some("world"),
2754 "SetClipboard must carry the selection text"
2755 );
2756 // The selection is deleted from the field.
2757 assert_eq!(il.data, "hello ", "selection deleted after cut");
2758 assert_eq!(il.sel_start, 0);
2759 assert_eq!(il.sel_end, 0);
2760 }
2761
2762 /// cmCopy with a selection: copies to clipboard, field unchanged.
2763 #[test]
2764 fn b3_copy_copies_to_clipboard_keeps_selection() {
2765 let mut il = field(12, "hello world");
2766 il.state.state.active = true;
2767 il.sel_start = 0;
2768 il.sel_end = 5;
2769 let data_before = il.data.clone();
2770
2771 let mut ev = Event::Command(Command::COPY);
2772 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2773 assert!(ev.is_nothing(), "cmCopy is consumed");
2774 let clipboard_text = deferred.iter().find_map(|d| {
2775 if let Deferred::SetClipboard(s) = d {
2776 Some(s.as_str())
2777 } else {
2778 None
2779 }
2780 });
2781 assert_eq!(clipboard_text, Some("hello"));
2782 assert_eq!(il.data, data_before, "copy does not modify the field");
2783 }
2784
2785 /// Masked field: neither `do_copy` nor `do_cut` may leak the cleartext value
2786 /// to the clipboard (Task 3 of the InputLine-masking plan). Cut still edits
2787 /// (deletes the selection) — only the clipboard write is suppressed.
2788 #[test]
2789 fn masked_copy_and_cut_do_not_leak_cleartext() {
2790 fn clipboard_writes(deferred: &[Deferred]) -> usize {
2791 deferred
2792 .iter()
2793 .filter(|d| matches!(d, Deferred::SetClipboard(_)))
2794 .count()
2795 }
2796
2797 let mut il = InputLine::with_limit(Rect::new(0, 0, 20, 1), 64);
2798 il.set_value(FieldValue::Text("secret".into()));
2799 il.set_mask(Some('•'));
2800 il.select_all(true, false); // select the whole value
2801
2802 let (_, deferred, ()) = with_ctx_d(|ctx| il.do_copy(ctx));
2803 assert_eq!(
2804 clipboard_writes(&deferred),
2805 0,
2806 "masked copy must not write cleartext"
2807 );
2808
2809 // Cut still edits (clears the selection) but writes nothing to the clipboard.
2810 let (_, deferred2, ()) = with_ctx_d(|ctx| il.do_cut(ctx));
2811 assert_eq!(
2812 clipboard_writes(&deferred2),
2813 0,
2814 "masked cut must not write cleartext"
2815 );
2816 assert_eq!(il.data, "", "cut still deletes the selection");
2817 }
2818
2819 /// A REVEALED masked field must still never leak cleartext to the OS
2820 /// clipboard: reveal is for viewing, not exfiltrating. Guard on
2821 /// `mask.is_none()` rather than `!masking()`, so `do_copy`/`do_cut` skip
2822 /// the clipboard write whenever a mask is configured, revealed or not.
2823 #[test]
2824 fn revealed_masked_field_still_never_copies_cleartext() {
2825 fn clipboard_writes(deferred: &[Deferred]) -> usize {
2826 deferred
2827 .iter()
2828 .filter(|d| matches!(d, Deferred::SetClipboard(_)))
2829 .count()
2830 }
2831
2832 let mut il = InputLine::with_limit(Rect::new(0, 0, 20, 1), 64);
2833 il.set_value(FieldValue::Text("secret".into()));
2834 il.set_mask(Some('•'));
2835 il.set_reveal(true);
2836 il.select_all(true, false); // select the whole value
2837
2838 let (_, deferred, ()) = with_ctx_d(|ctx| il.do_copy(ctx));
2839 assert_eq!(
2840 clipboard_writes(&deferred),
2841 0,
2842 "revealed masked copy must not write cleartext"
2843 );
2844
2845 // Cut still edits (clears the selection) but writes nothing to the clipboard.
2846 let (_, deferred2, ()) = with_ctx_d(|ctx| il.do_cut(ctx));
2847 assert_eq!(
2848 clipboard_writes(&deferred2),
2849 0,
2850 "revealed masked cut must not write cleartext"
2851 );
2852 assert_eq!(il.data, "", "cut still deletes the selection");
2853 }
2854
2855 /// cmPaste defers an InputLinePaste with the field's id.
2856 #[test]
2857 fn b3_paste_defers_input_line_paste_with_id() {
2858 let (mut il, id) = field_with_id(20, "hello");
2859 il.state.state.active = true;
2860
2861 let mut ev = Event::Command(Command::PASTE);
2862 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2863 assert!(ev.is_nothing(), "cmPaste is consumed");
2864 let paste_id = deferred.iter().find_map(|d| {
2865 if let Deferred::InputLinePaste(i) = d {
2866 Some(*i)
2867 } else {
2868 None
2869 }
2870 });
2871 assert_eq!(
2872 paste_id,
2873 Some(id),
2874 "InputLinePaste deferred with the field's own id"
2875 );
2876 }
2877
2878 /// `paste_text` inserts at the cursor, replacing any selection, clamped to
2879 /// max_len.
2880 #[test]
2881 fn b3_paste_text_inserts_at_cursor_replaces_selection_clamps() {
2882 // Paste with no selection: inserts at cursor.
2883 let mut il = field(20, "helo");
2884 il.cur_pos = 3; // before 'o', position of missing 'l'
2885 il.paste_text("l");
2886 assert_eq!(il.data, "hello", "paste inserts at cursor");
2887 assert_eq!(il.cur_pos, 4, "cursor advances past inserted text");
2888
2889 // Paste replacing a selection.
2890 let mut il = field(20, "hello world");
2891 il.sel_start = 6;
2892 il.sel_end = 11;
2893 il.paste_text("Rust");
2894 assert_eq!(il.data, "hello Rust", "paste replaces selection");
2895 assert_eq!(il.sel_start, 0);
2896 assert_eq!(il.sel_end, 0);
2897
2898 // Paste clamped to max_len (limit=5 → max_len=4 bytes).
2899 let mut il = InputLine::with_limit(Rect::new(0, 0, 20, 1), 5);
2900 il.state.state.selected = true;
2901 il.data = "abc".to_string();
2902 il.cur_pos = 3;
2903 il.paste_text("XXXX"); // 4 bytes, only 1 fits (max_len=4, 3 already used)
2904 assert_eq!(
2905 il.data, "abcX",
2906 "paste clamped to max_len: only 1 char fits"
2907 );
2908 assert_eq!(il.cur_pos, 4);
2909 }
2910
2911 /// A terminal bracketed paste (`Event::Paste`) inserts at the cursor and is
2912 /// consumed — the regression fix for single-line fields silently dropping
2913 /// every terminal paste (middle-click / Shift-Ctrl-V) that the `Editor`
2914 /// already handled. Also proves it replaces an active selection.
2915 #[test]
2916 fn bracketed_paste_event_inserts_and_consumes() {
2917 // Insert at the cursor (which `field` places at end).
2918 let mut il = field(20, "abc");
2919 let mut ev = Event::Paste("XYZ".to_string());
2920 with_ctx(|ctx| il.handle_event(&mut ev, ctx));
2921 assert_eq!(il.data, "abcXYZ", "bracketed paste inserts at the cursor");
2922 assert!(ev.is_nothing(), "the paste event is consumed");
2923
2924 // Replace an active selection.
2925 let mut il = field(20, "hello world");
2926 il.sel_start = 6;
2927 il.sel_end = 11;
2928 let mut ev = Event::Paste("Rust".to_string());
2929 with_ctx(|ctx| il.handle_event(&mut ev, ctx));
2930 assert_eq!(
2931 il.data, "hello Rust",
2932 "bracketed paste replaces the selection"
2933 );
2934
2935 // An unselected field ignores the paste (the outer guard).
2936 let mut il = field(20, "abc");
2937 il.state.state.selected = false;
2938 let mut ev = Event::Paste("XYZ".to_string());
2939 with_ctx(|ctx| il.handle_event(&mut ev, ctx));
2940 assert_eq!(il.data, "abc", "an unselected field drops the paste");
2941 }
2942
2943 /// Cut without a selection is a no-op data-wise but the event IS consumed.
2944 /// Cut/copy always consume the event regardless of selection; the clipboard
2945 /// operation is only performed when a selection exists.
2946 #[test]
2947 fn b3_cut_without_selection_consumes_event() {
2948 let mut il = field(12, "hello");
2949 il.state.state.active = true;
2950 il.sel_start = 0;
2951 il.sel_end = 0; // no selection
2952
2953 let data_before = il.data.clone();
2954 let mut ev = Event::Command(Command::CUT);
2955 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
2956 // C++ always clears the event for cmCut/cmCopy, even without a selection.
2957 assert!(ev.is_nothing(), "cut always consumes the event");
2958 assert_eq!(il.data, data_before, "no data change without selection");
2959 assert!(
2960 !deferred
2961 .iter()
2962 .any(|d| matches!(d, Deferred::SetClipboard(_))),
2963 "no SetClipboard when no selection"
2964 );
2965 }
2966
2967 // -- Phase 3: global-keymap dispatch ------------------------------------
2968
2969 /// Regression: under the default (WordStar) preset the field's editing keys
2970 /// still work — plain Backspace deletes, Home moves to start.
2971 #[test]
2972 fn keymap_default_backspace_and_nav_still_work() {
2973 let mut il = field(12, "abc"); // cursor at end (3)
2974 let mut ev = key(Key::Backspace);
2975 send_key(&mut il, &mut ev);
2976 assert_eq!(il.data, "ab");
2977 let mut ev = key(Key::Home);
2978 send_key(&mut il, &mut ev);
2979 assert_eq!(il.cur_pos, 0);
2980 }
2981
2982 /// Under the CUA preset, Ctrl-A selects all and Ctrl-C copies the selection
2983 /// to the clipboard (via the SetClipboard deferred, like the existing
2984 /// copy/cut tests).
2985 #[test]
2986 fn cua_ctrl_c_copies_in_input_line() {
2987 let _g = crate::keymap::GlobalKeymapGuard::new(crate::keymap::Keymap::cua());
2988 let (mut il, _id) = field_with_id(12, "hello");
2989 il.state.state.active = true;
2990
2991 // Ctrl-A → SELECT_ALL.
2992 let mut ev = ctrl_key(Key::Char('a'));
2993 send_key(&mut il, &mut ev);
2994 assert_eq!(il.sel_start, 0);
2995 assert_eq!(il.sel_end, 5);
2996
2997 // Ctrl-C → COPY: the selection text lands on the clipboard.
2998 let mut ev = ctrl_key(Key::Char('c'));
2999 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3000 let clipboard_text = deferred.iter().find_map(|d| {
3001 if let Deferred::SetClipboard(s) = d {
3002 Some(s.as_str())
3003 } else {
3004 None
3005 }
3006 });
3007 assert_eq!(clipboard_text, Some("hello"));
3008 // COPY must LEAVE the selection intact (the KeyDown tail's
3009 // sel-reset is bypassed for clipboard commands).
3010 assert_eq!(il.sel_start, 0, "selection survives COPY");
3011 assert_eq!(il.sel_end, 5, "selection survives COPY");
3012
3013 // PASTE over the live selection must replace it: do_paste queues a
3014 // deferred InputLinePaste, and the selection must still be present for
3015 // the pump's paste_text/delete_select to act on (regression guard — the
3016 // tail must not have zeroed it).
3017 let mut ev = ctrl_key(Key::Char('v'));
3018 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3019 assert!(
3020 deferred
3021 .iter()
3022 .any(|d| matches!(d, Deferred::InputLinePaste(_))),
3023 "Ctrl-V queues a deferred paste"
3024 );
3025 assert_eq!(
3026 il.sel_end, 5,
3027 "selection still live when the deferred paste runs"
3028 );
3029 }
3030
3031 /// Under every preset, plain Enter resolves to NEW_LINE — outside the
3032 /// single-line repertoire — so it must remain LIVE/unhandled and bubble to
3033 /// the dialog (default-button / focus / cancel routing).
3034 #[test]
3035 fn enter_tab_esc_bubble_under_every_preset() {
3036 for preset in [
3037 crate::keymap::Keymap::word_star(),
3038 crate::keymap::Keymap::cua(),
3039 crate::keymap::Keymap::emacs(),
3040 ] {
3041 let _g = crate::keymap::GlobalKeymapGuard::new(preset);
3042 let mut il = field(12, "x");
3043 let mut ev = key(Key::Enter);
3044 send_key(&mut il, &mut ev);
3045 assert!(
3046 matches!(ev, Event::KeyDown(_)),
3047 "Enter must remain live (bubble) under the active preset"
3048 );
3049 }
3050 }
3051
3052 #[test]
3053 fn set_validator_replaces_constructor_validator() {
3054 use crate::validate::FilterValidator;
3055 // Build with no validator, then attach one that only allows digits.
3056 let mut line = InputLine::new(Rect::new(0, 0, 10, 1), 9, None, LimitMode::default());
3057 assert!(line.validator.is_none());
3058
3059 line.set_validator(Some(Box::new(FilterValidator::new("0123456789"))));
3060 assert!(line.validator.is_some());
3061 // The freshly-attached validator rejects a non-digit keystroke.
3062 let mut non_digit = String::from("a");
3063 let mut digit = String::from("7");
3064 assert!(
3065 !line
3066 .validator
3067 .as_ref()
3068 .unwrap()
3069 .is_valid_input(&mut non_digit, false)
3070 );
3071 assert!(
3072 line.validator
3073 .as_ref()
3074 .unwrap()
3075 .is_valid_input(&mut digit, false)
3076 );
3077
3078 // Clearing it removes the constraint.
3079 line.set_validator(None);
3080 assert!(line.validator.is_none());
3081 }
3082
3083 // -- owner-active background --------------------------------------------
3084
3085 /// Render `il` with `theme` into a fresh buffer and return the background
3086 /// colour of the fill cell at column 8 (past the "hello" text, inside the
3087 /// row fill, away from any selection highlight). `owner_active` drives the
3088 /// [`DrawCtx`] directly (the direct-`DrawCtx` pattern from
3089 /// `Group::group_draw_sets_child_owner_active_from_group_focused`) so the
3090 /// field's own `state.focused` can be varied independently.
3091 fn fill_bg(il: &mut InputLine, theme: &Theme, owner_active: bool) -> crate::color::Color {
3092 let size = il.state.size;
3093 let mut buf = Buffer::new(size.x as u16, size.y as u16);
3094 let bounds = il.state.get_bounds();
3095 let mut dc = DrawCtx::new(&mut buf, theme, bounds, bounds.a);
3096 dc.set_owner_active(owner_active);
3097 il.draw(&mut dc);
3098 buf.get(8, 0).style().bg
3099 }
3100
3101 /// InputLine's default surface is the three-surface rule
3102 /// ([`DrawCtx::content_surface`](crate::view::DrawCtx::content_surface)):
3103 /// an inactive pane recedes to `InputInactive` regardless of the field's
3104 /// own focus; within an active pane a focused (or never-selectable) field
3105 /// is the `InputNormal` well, and an unfocused *selectable* sibling sits
3106 /// on `InputSurface`. Uses a theme where all three roles differ
3107 /// (classic_blue makes them identical, see
3108 /// `snapshot_default_three_surface_classic_blue_identical`).
3109 #[test]
3110 fn surface_follows_three_surface_rule() {
3111 use crate::color::{Color, Style};
3112
3113 let mut theme = Theme::classic_blue();
3114 theme.set_style(
3115 Role::InputSurface,
3116 Style::new(Color::Bios(0x0), Color::Bios(0x7)),
3117 );
3118 theme.set_style(
3119 Role::InputInactive,
3120 Style::new(Color::Bios(0x7), Color::Bios(0x4)),
3121 );
3122 let normal_bg = theme.style(Role::InputNormal).bg;
3123 let surface_bg = theme.style(Role::InputSurface).bg;
3124 let inactive_bg = theme.style(Role::InputInactive).bg;
3125 assert!(
3126 normal_bg != surface_bg && surface_bg != inactive_bg && normal_bg != inactive_bg,
3127 "test theme must distinguish all three roles"
3128 );
3129
3130 let mut il = field(12, "hello");
3131 il.first_pos = 0;
3132
3133 // Active pane, focused field → the well.
3134 il.state.state.focused = true;
3135 assert_eq!(fill_bg(&mut il, &theme, true), normal_bg);
3136
3137 // Active pane, unfocused SELECTABLE field → the pane surface (a
3138 // selectable sibling won the focus contest).
3139 il.state.state.focused = false;
3140 assert_eq!(fill_bg(&mut il, &theme, true), surface_bg);
3141
3142 // Inactive pane → receded, regardless of the field's own focus.
3143 il.state.state.focused = true;
3144 assert_eq!(fill_bg(&mut il, &theme, false), inactive_bg);
3145 il.state.state.focused = false;
3146 assert_eq!(fill_bg(&mut il, &theme, false), inactive_bg);
3147
3148 // Active pane, unfocused NON-selectable field → InputNormal: it can
3149 // never win (or lose) a focus contest, so it always stays the well.
3150 il.state.state.focused = false;
3151 il.state.options.selectable = false;
3152 assert_eq!(fill_bg(&mut il, &theme, true), normal_bg);
3153 }
3154
3155 #[test]
3156 fn mask_helpers_track_state_and_echo() {
3157 let mut il = InputLine::with_limit(Rect::new(0, 0, 10, 1), 64);
3158 assert!(!il.masking(), "unmasked by default");
3159 il.set_mask(Some('•'));
3160 assert!(il.masking(), "masking once a mask char is set");
3161 assert_eq!(il.echo_of("abc"), "•••", "one echo char per char");
3162 il.set_reveal(true);
3163 assert!(!il.masking(), "reveal suspends masking");
3164 il.set_reveal(false);
3165 il.set_mask(None);
3166 assert!(!il.masking(), "clearing the mask disables masking");
3167 }
3168
3169 #[test]
3170 fn masked_draw_shows_echo_not_data_and_value_is_real() {
3171 use crate::screen::Buffer;
3172 use crate::theme::Theme;
3173 use crate::view::DrawCtx;
3174
3175 let mut il = InputLine::with_limit(Rect::new(0, 0, 8, 1), 64);
3176 il.set_value(FieldValue::Text("secret".into()));
3177 il.set_mask(Some('•'));
3178
3179 let theme = Theme::classic_blue();
3180 let mut buf = Buffer::new(8, 1);
3181 {
3182 let mut dc = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 8, 1), Point::new(0, 0));
3183 il.draw(&mut dc);
3184 }
3185 // Text is painted from column 1. Masked → bullets, never the letters.
3186 let row: String = (0..8).map(|x| buf.get(x, 0).symbol()).collect();
3187 assert!(row.contains('•'), "masked field paints bullets: {row:?}");
3188 assert!(
3189 !row.contains('s') && !row.contains('e'),
3190 "no cleartext: {row:?}"
3191 );
3192 // The stored value is still the real password.
3193 assert_eq!(il.value(), Some(FieldValue::Text("secret".into())));
3194
3195 // Revealing paints the real text.
3196 il.set_reveal(true);
3197 let mut buf2 = Buffer::new(8, 1);
3198 {
3199 let mut dc = DrawCtx::new(&mut buf2, &theme, Rect::new(0, 0, 8, 1), Point::new(0, 0));
3200 il.draw(&mut dc);
3201 }
3202 let row2: String = (0..8).map(|x| buf2.get(x, 0).symbol()).collect();
3203 assert!(
3204 row2.contains('s') && row2.contains('e'),
3205 "revealed shows real: {row2:?}"
3206 );
3207 }
3208
3209 // -- value position -----------------------------------------------------
3210
3211 #[test]
3212 fn set_value_defaults_to_showing_the_end() {
3213 // Turbo Vision's behaviour: select-all, caret after the text, view at the
3214 // tail — ready for the first keystroke to replace the value.
3215 let mut il = field(10, "");
3216 il.set_value(FieldValue::Text("cn=admin,dc=example,dc=org".into()));
3217 assert_eq!(il.value_position(), ValuePosition::End);
3218 assert_eq!(il.cur_pos, il.data.len() as i32, "caret at the end");
3219 assert_eq!((il.sel_start, il.sel_end), (0, il.data.len() as i32));
3220 assert!(il.first_pos > 0, "the view scrolled to show the tail");
3221 }
3222
3223 #[test]
3224 fn value_position_start_shows_the_head_instead() {
3225 // For a DN or a path the front is what identifies it.
3226 let mut il = field(10, "");
3227 il.set_value_position(ValuePosition::Start);
3228 il.set_value(FieldValue::Text("cn=admin,dc=example,dc=org".into()));
3229 assert_eq!(il.cur_pos, 0, "caret homed");
3230 assert_eq!((il.sel_start, il.sel_end), (0, 0), "nothing selected");
3231 assert_eq!(il.first_pos, 0, "the view shows the start");
3232 }
3233
3234 #[test]
3235 fn value_position_applies_on_the_validator_transfer_path_too() {
3236 use crate::validate::RangeValidator;
3237 let mut rv = RangeValidator::new(0, 1_000_000);
3238 rv.set_transfer(true);
3239 let mut il = InputLine::new(
3240 Rect::new(0, 0, 4, 1),
3241 256,
3242 Some(Box::new(rv)),
3243 LimitMode::MaxBytes,
3244 );
3245 il.set_value_position(ValuePosition::Start);
3246 il.set_value(FieldValue::Int(123_456));
3247 assert_eq!(il.data, "123456");
3248 assert_eq!(il.cur_pos, 0, "the typed-transfer path honours it as well");
3249 assert_eq!(il.first_pos, 0);
3250 }
3251
3252 // -- read-only mode -----------------------------------------------------
3253
3254 /// Every `Event::Broadcast` of `READ_ONLY_REJECTED` in `out`, with its source.
3255 fn rejections(out: &[Event]) -> Vec<Option<crate::view::ViewId>> {
3256 out.iter()
3257 .filter_map(|e| match e {
3258 Event::Broadcast { command, source }
3259 if *command == InputLine::READ_ONLY_REJECTED =>
3260 {
3261 Some(*source)
3262 }
3263 _ => None,
3264 })
3265 .collect()
3266 }
3267
3268 fn read_only_field(width: i32, data: &str) -> (InputLine, crate::view::ViewId) {
3269 let (mut il, id) = field_with_id(width, data);
3270 il.set_read_only(true);
3271 (il, id)
3272 }
3273
3274 #[test]
3275 fn read_only_refuses_every_editing_key() {
3276 // Each key that would change the text: the value survives, the event is
3277 // consumed (so nothing else reinterprets it), and the owner is told.
3278 for make in [
3279 || key(Key::Backspace),
3280 || key(Key::Delete),
3281 || ctrl_key(Key::Char('y')), // DEL_LINE — clears the field
3282 || char_key('x'),
3283 ] {
3284 let (mut il, id) = read_only_field(12, "abc");
3285 il.cur_pos = 1;
3286 let mut ev = make();
3287 let (out, ()) = with_ctx(|ctx| il.handle_event(&mut ev, ctx));
3288 assert_eq!(il.data, "abc", "read-only text must survive {ev:?}");
3289 assert!(ev.is_nothing(), "the refused event is consumed");
3290 assert_eq!(
3291 rejections(&out),
3292 vec![Some(id)],
3293 "the owner is told, and which field it was"
3294 );
3295 }
3296 }
3297
3298 #[test]
3299 fn an_editable_field_still_edits() {
3300 // Guards against the refusal leaking into normal fields.
3301 let (mut il, _) = field_with_id(12, "abc");
3302 let mut ev = char_key('x');
3303 let (out, ()) = with_ctx(|ctx| il.handle_event(&mut ev, ctx));
3304 assert_eq!(il.data, "abcx");
3305 assert!(
3306 rejections(&out).is_empty(),
3307 "no refusal on an editable field"
3308 );
3309 }
3310
3311 #[test]
3312 fn read_only_allows_caret_movement_and_selection() {
3313 let (mut il, _) = read_only_field(12, "hello");
3314 il.cur_pos = 5;
3315 for (ev_key, want) in [(Key::Left, 4), (Key::Home, 0), (Key::End, 5)] {
3316 let mut ev = key(ev_key);
3317 let (out, ()) = with_ctx(|ctx| il.handle_event(&mut ev, ctx));
3318 assert_eq!(il.cur_pos, want, "{ev_key:?} must still move the caret");
3319 assert!(rejections(&out).is_empty(), "movement is not a change");
3320 }
3321 // Select-all is a selection, not an edit.
3322 il.select_all(true, true);
3323 assert_eq!((il.sel_start, il.sel_end), (0, 5));
3324 assert_eq!(il.data, "hello");
3325 }
3326
3327 #[test]
3328 fn read_only_copies_but_refuses_cut_and_paste() {
3329 // Copy is the whole point of the mode: a value you cannot edit must
3330 // still be one you can take with you.
3331 let (mut il, _id) = read_only_field(20, "cn=admin,dc=example");
3332 il.state.state.active = true;
3333 il.sel_start = 0;
3334 il.sel_end = 8;
3335 let mut ev = Event::Command(Command::COPY);
3336 let (out, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3337 assert_eq!(
3338 deferred.iter().find_map(|d| match d {
3339 Deferred::SetClipboard(s) => Some(s.as_str()),
3340 _ => None,
3341 }),
3342 Some("cn=admin"),
3343 "copy reaches the clipboard"
3344 );
3345 assert!(rejections(&out).is_empty(), "copy is not a change");
3346
3347 // Cut would remove the selection; paste would replace it.
3348 let (mut il, _) = read_only_field(20, "cn=admin,dc=example");
3349 il.state.state.active = true;
3350 il.sel_start = 0;
3351 il.sel_end = 8;
3352 let mut ev = Event::Command(Command::CUT);
3353 let (out, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3354 assert_eq!(
3355 il.data, "cn=admin,dc=example",
3356 "cut must not remove anything"
3357 );
3358 assert!(
3359 !deferred
3360 .iter()
3361 .any(|d| matches!(d, Deferred::SetClipboard(_))),
3362 "a refused cut writes nothing to the clipboard either"
3363 );
3364 assert_eq!(rejections(&out).len(), 1);
3365
3366 let mut ev = Event::Command(Command::PASTE);
3367 let (out, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3368 assert!(
3369 !deferred
3370 .iter()
3371 .any(|d| matches!(d, Deferred::InputLinePaste(_))),
3372 "a refused paste never asks the broker for clipboard text"
3373 );
3374 assert_eq!(rejections(&out).len(), 1);
3375 assert_eq!(il.data, "cn=admin,dc=example");
3376 }
3377
3378 #[test]
3379 fn read_only_refuses_a_terminal_paste() {
3380 // Bracketed paste hands us the bytes directly — no command to gray.
3381 let (mut il, id) = read_only_field(20, "abc");
3382 let mut ev = Event::Paste("pasted".to_string());
3383 let (out, ()) = with_ctx(|ctx| il.handle_event(&mut ev, ctx));
3384 assert_eq!(il.data, "abc");
3385 assert!(ev.is_nothing(), "the paste is consumed, not passed on");
3386 assert_eq!(rejections(&out), vec![Some(id)]);
3387 }
3388
3389 #[test]
3390 fn read_only_paste_text_is_inert() {
3391 // The deferred-paste apply arm calls this directly, with no Context to
3392 // refuse through — so it must simply do nothing.
3393 let (mut il, _) = read_only_field(20, "abc");
3394 il.paste_text("pasted");
3395 assert_eq!(il.data, "abc");
3396 }
3397
3398 #[test]
3399 fn read_only_grays_cut_and_paste_but_not_copy() {
3400 let (mut il, _) = read_only_field(20, "hello");
3401 il.state.state.active = true;
3402 il.sel_start = 0;
3403 il.sel_end = 5; // a selection exists: copy is meaningful
3404 let (_, deferred, ()) = with_ctx_d(|ctx| il.update_commands(ctx));
3405 let enabled: Vec<Command> = deferred
3406 .iter()
3407 .filter_map(|d| match d {
3408 Deferred::EnableCommand(c) => Some(*c),
3409 _ => None,
3410 })
3411 .collect();
3412 let disabled: Vec<Command> = deferred
3413 .iter()
3414 .filter_map(|d| match d {
3415 Deferred::DisableCommand(c) => Some(*c),
3416 _ => None,
3417 })
3418 .collect();
3419 assert!(enabled.contains(&Command::COPY), "copy stays available");
3420 assert!(disabled.contains(&Command::CUT), "cut is grayed");
3421 assert!(disabled.contains(&Command::PASTE), "paste is grayed");
3422 }
3423
3424 #[test]
3425 fn read_only_is_focusable_where_disabled_is_not() {
3426 // The distinction the mode exists for: a disabled field cannot be
3427 // reached at all, a read-only one can.
3428 let (mut il, _) = read_only_field(12, "abc");
3429 assert!(il.has_focusable_leaf(), "a read-only field takes focus");
3430 il.state.state.disabled = true;
3431 assert!(!il.has_focusable_leaf(), "a disabled field does not");
3432 }
3433
3434 // -- X11 PRIMARY selection (middle-click paste) ---------------------------
3435 //
3436 // Middle-click pastes the PRIMARY selection at the click point; completing a
3437 // MOUSE selection publishes it. Keyboard selection deliberately does not
3438 // publish — it would re-take X ownership on every arrow key.
3439
3440 fn primary_pastes(deferred: &[Deferred]) -> Vec<crate::view::ViewId> {
3441 deferred
3442 .iter()
3443 .filter_map(|d| match d {
3444 Deferred::InputLinePastePrimary(i) => Some(*i),
3445 _ => None,
3446 })
3447 .collect()
3448 }
3449
3450 fn primary_writes(deferred: &[Deferred]) -> Vec<String> {
3451 deferred
3452 .iter()
3453 .filter_map(|d| match d {
3454 Deferred::SetPrimary(t) => Some(t.clone()),
3455 _ => None,
3456 })
3457 .collect()
3458 }
3459
3460 /// Middle-click puts the caret where you clicked, then asks the pump for the
3461 /// PRIMARY selection. Column 6 → byte 5 (`mouse_pos`: col - 1 at first_pos 0).
3462 #[test]
3463 fn middle_click_defers_a_primary_paste_at_the_clicked_column() {
3464 let (mut il, id) = field_with_id(20, "hello world");
3465 let mut ev = middle_down_at(6, 0);
3466 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3467
3468 assert!(ev.is_nothing(), "middle click is consumed");
3469 assert_eq!(il.cur_pos, 5, "caret lands where the click was");
3470 assert_eq!(primary_pastes(&deferred), vec![id]);
3471 }
3472
3473 /// Middle-click is a one-shot paste, not the start of a drag: it must not
3474 /// arm the drag-select tracking loop the left button uses.
3475 #[test]
3476 fn middle_click_arms_no_drag_tracking() {
3477 let (mut il, _id) = field_with_id(20, "hello world");
3478 let mut ev = middle_down_at(6, 0);
3479 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3480
3481 assert!(!il.tracking, "no tracking armed");
3482 assert!(!il.tracking_drag, "no drag branch armed");
3483 }
3484
3485 /// The paste replaces nothing: an existing selection is dropped and the text
3486 /// lands at the click point, matching how X11 text widgets behave.
3487 #[test]
3488 fn middle_click_clears_any_existing_selection() {
3489 let (mut il, _id) = field_with_id(20, "hello world");
3490 il.select_all(true, false);
3491 assert!(
3492 il.sel_start < il.sel_end,
3493 "precondition: something selected"
3494 );
3495
3496 let mut ev = middle_down_at(3, 0);
3497 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3498
3499 assert_eq!(il.sel_start, il.sel_end, "selection dropped");
3500 }
3501
3502 /// Middle-click on an EDGE column still pastes — it must not be swallowed by
3503 /// the edge auto-scroll branch that the left button uses there.
3504 #[test]
3505 fn middle_click_on_the_edge_column_still_pastes() {
3506 let (mut il, id) = field_with_id(20, "hello world");
3507 let mut ev = middle_down_at(0, 0);
3508 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3509
3510 assert!(ev.is_nothing(), "consumed at the edge too");
3511 assert!(!il.tracking, "no edge auto-scroll armed");
3512 assert_eq!(primary_pastes(&deferred), vec![id]);
3513 }
3514
3515 /// Finishing a drag-select publishes the swept text as the PRIMARY
3516 /// selection, so another X client can middle-click-paste it.
3517 #[test]
3518 fn finishing_a_drag_select_publishes_the_primary_selection() {
3519 let (mut il, _id) = field_with_id(20, "hello world");
3520 // Down at col 2 (byte 1) …
3521 let mut ev = mouse_down_at(2, 0);
3522 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3523 // … drag to col 5 (byte 4) …
3524 let mut ev = mouse_move_at(5, 0);
3525 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3526 // … and release.
3527 let mut ev = mouse_up_at(5, 0);
3528 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3529
3530 assert_eq!(
3531 primary_writes(&deferred),
3532 vec!["ell".to_string()],
3533 "the swept bytes 1..4 of \"hello world\""
3534 );
3535 }
3536
3537 /// A release that selected nothing (a plain click) publishes nothing —
3538 /// otherwise every click would clobber the user's selection with "".
3539 #[test]
3540 fn a_click_without_a_sweep_publishes_no_primary_selection() {
3541 let (mut il, _id) = field_with_id(20, "hello world");
3542 let mut ev = mouse_down_at(4, 0);
3543 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3544 let mut ev = mouse_up_at(4, 0);
3545 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3546
3547 assert!(primary_writes(&deferred).is_empty());
3548 }
3549
3550 /// Double-click selects all, and that is a mouse selection too.
3551 #[test]
3552 fn double_click_select_all_publishes_the_primary_selection() {
3553 let (mut il, _id) = field_with_id(20, "hello");
3554 let mut ev = Event::MouseDown(MouseEvent {
3555 position: Point::new(3, 0),
3556 buttons: MouseButtons {
3557 left: true,
3558 ..Default::default()
3559 },
3560 flags: MouseEventFlags {
3561 double_click: true,
3562 ..Default::default()
3563 },
3564 wheel: MouseWheel::None,
3565 modifiers: KeyModifiers::default(),
3566 });
3567 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3568
3569 assert_eq!(primary_writes(&deferred), vec!["hello".to_string()]);
3570 }
3571
3572 /// THE SECURITY RULE. A masked field must never publish cleartext to
3573 /// PRIMARY — revealed or not — exactly as `do_copy`/`do_cut` already refuse
3574 /// the CLIPBOARD. Middle-click paste INTO a masked field is still fine; it
3575 /// is only the outbound direction that leaks.
3576 #[test]
3577 fn a_masked_field_never_publishes_the_primary_selection() {
3578 let mut il = InputLine::with_limit(Rect::new(0, 0, 20, 1), 64);
3579 il.state.id = Some(crate::view::ViewId::next());
3580 il.state.state.selected = true;
3581 il.set_value(FieldValue::Text("secret".into()));
3582 il.set_mask(Some('\u{2022}'));
3583 il.set_reveal(true); // even revealed
3584
3585 let mut ev = mouse_down_at(1, 0);
3586 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3587 let mut ev = mouse_move_at(6, 0);
3588 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3589 let mut ev = mouse_up_at(6, 0);
3590 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3591
3592 assert!(
3593 il.sel_start < il.sel_end,
3594 "precondition: a selection exists"
3595 );
3596 assert!(
3597 primary_writes(&deferred).is_empty(),
3598 "revealed masked field must not leak cleartext to PRIMARY"
3599 );
3600 }
3601
3602 /// A read-only field refuses a middle-click paste the same way it refuses
3603 /// cmPaste — and broadcasts the refusal, so the owner can beep.
3604 #[test]
3605 fn a_read_only_field_refuses_a_middle_click_paste() {
3606 let (mut il, id) = read_only_field(20, "locked");
3607 let mut ev = middle_down_at(3, 0);
3608 let (out, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3609
3610 assert!(ev.is_nothing(), "still consumed — the gesture was ours");
3611 assert!(
3612 primary_pastes(&deferred).is_empty(),
3613 "no PRIMARY paste requested"
3614 );
3615 assert_eq!(rejections(&out), vec![Some(id)], "refusal broadcast");
3616 }
3617
3618 /// Read-only blocks writing INTO the field, not reading OUT of it: sweeping
3619 /// a selection in a read-only field still publishes PRIMARY (that is the
3620 /// point of read-only — "navigable and copyable, but not editable").
3621 #[test]
3622 fn a_read_only_field_still_publishes_its_mouse_selection() {
3623 let (mut il, _id) = read_only_field(20, "hello world");
3624 let mut ev = mouse_down_at(2, 0);
3625 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3626 let mut ev = mouse_move_at(5, 0);
3627 with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3628 let mut ev = mouse_up_at(5, 0);
3629 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3630
3631 assert_eq!(primary_writes(&deferred), vec!["ell".to_string()]);
3632 }
3633
3634 /// Keyboard selection is deliberately NOT published: shift+arrow would
3635 /// re-take X selection ownership on every keystroke.
3636 #[test]
3637 fn keyboard_selection_does_not_publish_the_primary_selection() {
3638 let (mut il, _id) = field_with_id(20, "hello world");
3639 il.cur_pos = 0;
3640 il.sel_start = 0;
3641 il.sel_end = 0;
3642 let mut ev = Event::KeyDown(KeyEvent::new(
3643 Key::Right,
3644 KeyModifiers {
3645 shift: true,
3646 ..Default::default()
3647 },
3648 ));
3649 let (_, deferred, ()) = with_ctx_d(|ctx| il.handle_event(&mut ev, ctx));
3650
3651 assert!(
3652 il.sel_start < il.sel_end,
3653 "precondition: shift+Right selected"
3654 );
3655 assert!(primary_writes(&deferred).is_empty());
3656 }
3657}