Skip to main content

tvision_rs/widgets/
editor.rs

1//! `Editor`, the gap-buffer text editor, and its `Memo` / `FileEditor` / `EditWindow` relatives.
2
3use crate::keymap::{self, KeyStroke, Resolve};
4use crate::theme::Role;
5use crate::view::{
6    Context, DrawCtx, GrowMode, Options, Point, Rect, StateFlag, View, ViewId, ViewState,
7};
8use crate::widgets::{Indicator, ScrollBar};
9
10// ---------------------------------------------------------------------------
11// module-private flag constants (kept off Command — these are bit words)
12// ---------------------------------------------------------------------------
13
14/// Redraw the indicator/scrollbars/cursor only (no text repaint).
15const UF_UPDATE: u8 = 0x01;
16/// Repaint just the current line.
17const UF_LINE: u8 = 0x02;
18/// Repaint the whole view.
19const UF_VIEW: u8 = 0x04;
20
21// ---------------------------------------------------------------------------
22// select-mode flags — the `select_mode` argument of `Editor::set_cur_ptr`
23//
24// Kept as plain `u8` bits rather than a struct-of-bools: `set_cur_ptr` combines
25// these with bitwise arithmetic (`sm | SM_EXTEND`, `select_mode & SM_DOUBLE`)
26// at every call site, mirroring C++'s `ushort` flag word — a deliberate
27// non-conversion so the signature stays call-site-compatible with that
28// arithmetic.
29// ---------------------------------------------------------------------------
30
31/// Extend the current selection to the new cursor position, instead of
32/// collapsing it to a point at `p`.
33pub const SM_EXTEND: u8 = 0x01;
34/// Word-granular selection (double-click): snap both ends to word boundaries.
35pub const SM_DOUBLE: u8 = 0x02;
36/// Line-granular selection (triple-click): snap both ends to line boundaries.
37pub const SM_TRIPLE: u8 = 0x04;
38
39// The search-option flags. `pub(crate)` (the `editor` module is private and only
40// `Editor`/`Encoding`/`LineEnding` are re-exported; `search()` takes a plain
41// `opts: u16`).
42/// Match case exactly.
43pub(crate) const EF_CASE_SENSITIVE: u16 = 0x0001;
44/// Reject matches that fall inside a larger word.
45pub(crate) const EF_WHOLE_WORDS_ONLY: u16 = 0x0002;
46// The flags that drive the find/replace dialogs.
47/// Prompt before each substitution.
48pub(crate) const EF_PROMPT_ON_REPLACE: u16 = 0x0004;
49/// Replace every match.
50pub(crate) const EF_REPLACE_ALL: u16 = 0x0008;
51/// The operation is a replace, not a find.
52pub(crate) const EF_DO_REPLACE: u16 = 0x0010;
53/// Rename the existing file to `<name>~` before saving.
54pub(crate) const EF_BACKUP_FILES: u16 = 0x0100;
55
56/// The fixed content width (the maximum line length).
57const MAX_LINE_LENGTH: i32 = 256;
58
59/// Which mouse-button hold is in flight, mirroring the scroll-bar tracking
60/// discipline. `None` in [`Editor::track`] means no hold is active; the tracked
61/// `MouseMove`/`MouseAuto`/wheel/`MouseUp` arms are guarded on it, so a stray
62/// event falls through unconsumed.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64enum EditorTrack {
65    /// A primary-button drag that extends the selection. `select_mode` is seeded
66    /// by the press (`SM_EXTEND`/`SM_DOUBLE`/`SM_TRIPLE`) and gains `SM_EXTEND`
67    /// after every move, so a word- or line-granular drag (double/triple-click)
68    /// keeps growing in that granularity.
69    Select {
70        /// The live select-mode byte (`SM_*` bits).
71        select_mode: u8,
72    },
73    /// A middle-button pan: each tick scrolls by the mouse delta and never
74    /// touches the cursor or selection.
75    Pan {
76        /// The previous tick's view-local mouse position.
77        last: Point,
78        /// Whether the pointer has actually moved since the press.
79        ///
80        /// The middle button carries two gestures, told apart by movement: a
81        /// press released where it started is the X11 middle-click paste; a
82        /// press that moves is the pan. So the press arms `moved: false` and
83        /// runs no pan body — which is what the C++ `while (mouseEvent(...))`
84        /// loop does anyway (teditor1.cpp:540-551).
85        moved: bool,
86    },
87}
88
89/// Sentinel returned by the buffer scan helpers to mean "not found".
90const SEARCH_FAILED: usize = usize::MAX;
91
92// ---------------------------------------------------------------------------
93// Line ending / encoding enums
94// ---------------------------------------------------------------------------
95
96/// How line breaks are stored when text is inserted.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub enum LineEnding {
99    /// `"\r\n"`.
100    CrLf,
101    /// `"\n"`.
102    Lf,
103    /// `"\r"`.
104    Cr,
105}
106
107impl LineEnding {
108    /// The byte sequence this line ending writes.
109    fn bytes(self) -> &'static [u8] {
110        match self {
111            LineEnding::Lf => b"\n",
112            LineEnding::Cr => b"\r",
113            LineEnding::CrLf => b"\r\n",
114        }
115    }
116}
117
118/// How multibyte characters are stepped over.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub enum Encoding {
121    /// Width-aware (grapheme) stepping.
122    Default,
123    /// Every byte is one column.
124    SingleByte,
125}
126
127/// The line ending used for newly inserted breaks: [`LineEnding::Lf`], the
128/// modern-host default.
129const DEFAULT_LINE_ENDING: LineEnding = LineEnding::Lf;
130
131// ---------------------------------------------------------------------------
132// getCharType / isWordBoundary / isWordChar (teditor2.cpp)
133// ---------------------------------------------------------------------------
134
135/// Classify a byte for word-boundary detection (whitespace / line break /
136/// punctuation / word character).
137fn get_char_type(ch: u8) -> u8 {
138    match ch {
139        b'\t' | b' ' | 0 => 0,
140        b'\n' | b'\r' => 1,
141        b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' => 2,
142        _ => 3,
143    }
144}
145
146/// True when `a` and `b` fall in different character classes.
147fn is_word_boundary(a: u8, b: u8) -> bool {
148    get_char_type(a) != get_char_type(b)
149}
150
151/// True unless `ch` is whitespace or punctuation — i.e. it is part of a word.
152fn is_word_char(ch: u8) -> bool {
153    !matches!(
154        ch,
155        b' ' | b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' | 0
156    )
157}
158
159/// Number of line breaks in `buf`, counting `\r\n` as one.
160fn count_lines(buf: &[u8]) -> i32 {
161    let mut lines = 0;
162    let mut i = 0;
163    while i < buf.len() {
164        if buf[i] == b'\r' {
165            lines += 1;
166            if i + 1 < buf.len() && buf[i + 1] == b'\n' {
167                i += 1;
168            }
169        } else if buf[i] == b'\n' {
170            lines += 1;
171        }
172        i += 1;
173    }
174    lines
175}
176
177/// Case-sensitive substring search. Returns the byte offset of the first match,
178/// or [`SEARCH_FAILED`].
179fn scan(block: &[u8], needle: &[u8]) -> usize {
180    let len = needle.len();
181    if len == 0 {
182        return SEARCH_FAILED;
183    }
184    let size = block.len();
185    let mut i = 0;
186    while i < size {
187        let mut j = i;
188        let mut k = 0;
189        while j < size && block[j] == needle[k] {
190            j += 1;
191            k += 1;
192            if k == len {
193                return i;
194            }
195        }
196        i += 1;
197    }
198    SEARCH_FAILED
199}
200
201/// Case-insensitive substring search.
202fn i_scan(block: &[u8], needle: &[u8]) -> usize {
203    let len = needle.len();
204    if len == 0 {
205        return SEARCH_FAILED;
206    }
207    let size = block.len();
208    let mut i = 0;
209    while i < size {
210        let mut j = i;
211        let mut k = 0;
212        while j < size && block[j].eq_ignore_ascii_case(&needle[k]) {
213            j += 1;
214            k += 1;
215            if k == len {
216                return i;
217            }
218        }
219        i += 1;
220    }
221    SEARCH_FAILED
222}
223
224// ---------------------------------------------------------------------------
225// Grapheme stepping over raw (possibly-invalid-UTF-8) bytes
226// ---------------------------------------------------------------------------
227//
228// The buffer holds raw bytes (an invalid byte is reachable via the public
229// `insert_text(&[u8])`). `from_utf8_lossy` would expand an invalid byte into the
230// 3-byte U+FFFD, so advancing by `text::next`'s byte length on the lossy string
231// over-shoots the logical buffer and desyncs the cursor from a grapheme
232// boundary. These helpers step over exactly the **logical** bytes consumed: a
233// valid grapheme advances by its real length; an invalid lead byte advances by 1.
234
235/// Byte length of the first grapheme in `chunk` (raw bytes), or `None` when
236/// empty. An invalid UTF-8 lead byte consumes exactly 1 byte.
237fn next_grapheme_byte_len(chunk: &[u8]) -> Option<usize> {
238    next_grapheme_with_width(chunk).map(|(len, _)| len)
239}
240
241/// Byte length and display width of the first grapheme in `chunk` (raw bytes),
242/// or `None` when empty. An invalid lead byte → `(1, 1)` (one logical byte, one
243/// replacement column).
244fn next_grapheme_with_width(chunk: &[u8]) -> Option<(usize, usize)> {
245    if chunk.is_empty() {
246        return None;
247    }
248    // Decode only the valid UTF-8 prefix; if the very first byte is invalid the
249    // prefix is empty and we advance one raw byte.
250    let valid = match std::str::from_utf8(chunk) {
251        Ok(s) => s,
252        Err(e) => {
253            let upto = e.valid_up_to();
254            if upto == 0 {
255                return Some((1, 1));
256            }
257            // SAFETY: `..upto` is the verified-valid prefix.
258            unsafe { std::str::from_utf8_unchecked(&chunk[..upto]) }
259        }
260    };
261    match crate::text::next(valid) {
262        Some((len, w)) => Some((len.max(1), w)),
263        // Non-empty raw bytes but no decodable grapheme → advance one byte.
264        None => Some((1, 1)),
265    }
266}
267
268/// Byte length of the **last** grapheme in `chunk` (raw bytes); how far back the
269/// cursor steps. A trailing invalid byte steps back exactly 1 byte.
270fn prev_grapheme_byte_len(chunk: &[u8]) -> usize {
271    if chunk.is_empty() {
272        return 0;
273    }
274    // Find the longest valid-UTF-8 suffix and step back one grapheme within it.
275    // If the final byte is invalid, the suffix is empty → step back 1 raw byte.
276    match std::str::from_utf8(chunk) {
277        Ok(s) => crate::text::prev(s, s.len()).max(1),
278        Err(e) => {
279            let upto = e.valid_up_to();
280            if upto == chunk.len() {
281                // Whole chunk valid (unreachable here, but keep total): step back
282                // one grapheme.
283                // SAFETY: the whole chunk is valid UTF-8.
284                let s = unsafe { std::str::from_utf8_unchecked(chunk) };
285                crate::text::prev(s, s.len()).max(1)
286            } else {
287                // A byte at/after `upto` is invalid. If the LAST byte is part of
288                // the invalid run, step back 1; otherwise the valid prefix ends
289                // before the invalid byte and the cursor was already past it.
290                1
291            }
292        }
293    }
294}
295
296// ---------------------------------------------------------------------------
297// Editor
298// ---------------------------------------------------------------------------
299
300/// A gap-buffer text editor: a leaf [`View`] holding a single `Vec<u8>` split by
301/// a movable gap, with a cursor, a selection, single-level undo, and a viewport
302/// (`delta`) onto a content extent (`limit`). It references two sibling scroll
303/// bars and an indicator on the window frame, runs Find / Replace dialogs, and
304/// cuts/copies/pastes through a shared internal clipboard editor.
305///
306/// # The context-threading split (the central seam)
307///
308/// Redraw work needs a [`Context`], but a [`View`] has none at construction, so
309/// requesting a redraw is **split from performing it**:
310///
311/// * The **core editing methods take no `Context`** — they mutate logical state
312///   and only OR bits into `update_flags`. `update`
313///   only records what changed; it never repaints inline.
314/// * `&mut Context` is threaded **only** into `do_update`, `unlock`,
315///   `handle_event`, `set_state`, and the public ctx-taking entries
316///   (`apply_scroll_delta`, `insert_text`). `unlock` flushes when the lock count
317///   hits 0; `handle_event` flushes at the end for the arms that ran unlocked.
318/// * `change_bounds` is geometry-only plus a `delta` clamp plus a view-update
319///   request — scroll-bar params republish on the next flush.
320///
321/// This makes the entire gap-buffer + edit core context-free and unit-testable in
322/// isolation, where the real oracle (logical buffer state) lives.
323///
324/// # Siblings by `ViewId`
325///
326/// The editor holds `h_scroll_bar`/`v_scroll_bar`/
327/// `indicator` as [`Option<ViewId>`], never pointers. Every cross-view read/write
328/// is routed through the event loop: read the bar values into `delta`, publish
329/// range/value, set the indicator value, show/hide. The editor is its own
330/// concrete downcast target (it is *not* a `Scroller`).
331///
332/// # Grapheme text
333///
334/// The character-stepping helpers read logical bytes across the gap into a small
335/// buffer, `str`-decode the contiguous slice, and step whole grapheme clusters
336/// via [`text::next`](crate::text::next)/[`text::prev`](crate::text::prev). There is no fixed-size character stack
337/// buffer.
338///
339/// # Mouse hold-tracking
340///
341/// The two mouse-down hold loops (drag-select and pan) become tracked event arms:
342/// the `MouseDown` arm runs the first loop iteration and arms the capture; the
343/// move/auto/wheel arms are the loop bodies; `MouseUp` clears. Which loop is in
344/// flight lives in `EditorTrack` (`Select` carries the live select mode; `Pan`
345/// carries the last mouse position). A wheel during a drag-select forwards to both scroll
346/// bars and self-posts a delta-sync, so the new offset lands on the next pump.
347/// Outside a hold, a wheel falls through unconsumed (the editor's event mask
348/// excludes the wheel).
349///
350/// Search/replace state — the find string, the replacement string, and the
351/// `EF_*` option flags — is **per-editor**: each editor independently
352/// remembers its own last search. (C++ Turbo Vision kept these in class-static
353/// globals shared across every editor; per-instance is the intentional
354/// deviation, and is usually what a user wants.)
355///
356/// # Turbo Vision heritage
357///
358/// Ports `TEditor` (`teditor1.cpp`, `teditor2.cpp`, `edits.cpp`). Up-pointers to
359/// the scroll bars and indicator become [`ViewId`] handles brokered by the event
360/// loop (deviation D3); raw byte indices become grapheme-aware stepping (deviation
361/// D13); color lookups become [`Role`]s; serialization is dropped.
362pub struct Editor {
363    /// View state (geometry, flags, etc.) — the composition target.
364    state: ViewState,
365    /// The text buffer: `buf_len` logical bytes split by a `gap_len`-byte gap at
366    /// `cur_ptr`. Always physically `buf_size` bytes long; gap bytes are stale.
367    buffer: Vec<u8>,
368    /// Physical buffer capacity (never grows in the base editor; see
369    /// [`set_buf_size`](Editor::set_buf_size)).
370    buf_size: usize,
371    /// Logical text length. Invariant: `buf_len + gap_len == buf_size`.
372    buf_len: usize,
373    /// Gap size at `cur_ptr`.
374    gap_len: usize,
375    /// Selection start (logical offset).
376    sel_start: usize,
377    /// Selection end (logical offset).
378    sel_end: usize,
379    /// Cursor position (logical offset); the gap sits here physically.
380    cur_ptr: usize,
381    /// Cursor `(col, row)` in display coordinates.
382    cur_pos: Point,
383    /// Viewport top-left (scroll offset) in display coordinates.
384    delta: Point,
385    /// Content extent `(x = max line length, y = line count)`.
386    limit: Point,
387    /// The display row that `draw_ptr` corresponds to.
388    draw_line: i32,
389    /// Logical offset of the start of line `draw_line`.
390    draw_ptr: usize,
391    /// Bytes deleted since the last undo checkpoint (undo accounting).
392    del_count: usize,
393    /// Bytes inserted since the last undo checkpoint.
394    ins_count: usize,
395    /// Buffer allocation succeeded.
396    is_valid: bool,
397    /// Undo is enabled (always true in the base editor).
398    can_undo: bool,
399    /// File-editor mode: the buffer grows on demand and the save commands are
400    /// enabled while focused. False for the plain editor / memo (fixed buffer).
401    file_editor: bool,
402    /// Whether this editor IS the internal clipboard editor. Set by the pump
403    /// drain when the register-clipboard-editor deferred effect is processed.
404    pub(crate) is_clipboard: bool,
405    /// The buffer has unsaved changes.
406    modified: bool,
407    /// A persistent selection is in progress (selection mode toggled on).
408    selecting: bool,
409    /// Overwrite (vs insert) mode.
410    overwrite: bool,
411    /// Replicate leading whitespace on Enter.
412    auto_indent: bool,
413    /// Nested update locks; flush happens when this returns to 0.
414    lock_count: u8,
415    /// Pending redraw flags (`UF_*` bits).
416    update_flags: u8,
417    /// The pending first stroke of a two-key chord. Set when a key resolves to
418    /// [`Resolve::Prefix`]; combined with the next stroke and then cleared.
419    /// Replaces a small prefix state machine (idle / Ctrl-Q / Ctrl-K).
420    pending: Option<KeyStroke>,
421    /// Line ending used for newly inserted breaks.
422    line_ending: LineEnding,
423    /// Character-stepping encoding.
424    encoding: Encoding,
425    /// Horizontal scroll bar, by id (`None` = absent).
426    h_scroll_bar: Option<ViewId>,
427    /// Vertical scroll bar, by id (`None` = absent).
428    v_scroll_bar: Option<ViewId>,
429    /// Frame indicator, by id (`None` = absent).
430    indicator: Option<ViewId>,
431    /// Last search string. Stored per-instance (each editor remembers its own).
432    find_str: String,
433    /// Last replacement string (per-instance; see [`find_str`]).
434    replace_str: String,
435    /// The `EF_*` search options (per-instance; see [`find_str`]).
436    editor_flags: u16,
437    /// Absolute screen position of view-local `(0, 0)`, cached by `draw` so the
438    /// mouse-tracking capture can localize absolute mouse coords (the same
439    /// `abs_origin` pattern buttons use).
440    abs_origin: Point,
441    /// Size of the whole screen, cached by `draw` (`DrawCtx::screen_size`)
442    /// so the right-click popup is placed against the screen, not the owner.
443    screen: Point,
444    /// Per-hold mouse-track state — `Some` while a hold is in flight (see
445    /// [`EditorTrack`]). Guards the tracked `MouseMove`/`MouseAuto`/wheel/
446    /// `MouseUp` arms against stray events.
447    track: Option<EditorTrack>,
448    /// Cached answer from the "Replace this occurrence?" prompt
449    /// ([`Context::request_message_box`] with `yes_no_cancel`). Set via
450    /// [`View::set_modal_answer`]; consumed by [`do_search_replace`] on the
451    /// next search-again dispatch to act on the user's choice before searching
452    /// for the next match.
453    pending_replace_answer: Option<crate::command::Command>,
454}
455
456impl Editor {
457    /// Build an editor over a `buf_size`-byte buffer, wired to the given scroll
458    /// bars and frame indicator (each optional, by id).
459    ///
460    /// The view grows with its parent on the right/bottom, is selectable, shows a
461    /// cursor, and starts with an empty buffer. No redraw is performed here (a
462    /// [`View`] has no [`Context`] at construction); the initial state is
463    /// consistent for the first `draw`, and scroll-bar params publish on the
464    /// first flush.
465    pub fn new(
466        bounds: Rect,
467        h_scroll_bar: Option<ViewId>,
468        v_scroll_bar: Option<ViewId>,
469        indicator: Option<ViewId>,
470        buf_size: usize,
471    ) -> Self {
472        let mut state = ViewState::new(bounds);
473        state.grow_mode = GrowMode {
474            hi_x: true,
475            hi_y: true,
476            ..Default::default()
477        };
478        state.options = Options {
479            selectable: true,
480            ..Default::default()
481        };
482        state.show_cursor();
483        // Allocate the buffer at full physical size up front; gap bytes are stale.
484        let buffer = vec![0u8; buf_size];
485        let mut ed = Editor {
486            state,
487            buffer,
488            buf_size,
489            buf_len: 0,
490            gap_len: buf_size,
491            sel_start: 0,
492            sel_end: 0,
493            cur_ptr: 0,
494            cur_pos: Point::new(0, 0),
495            delta: Point::new(0, 0),
496            limit: Point::new(MAX_LINE_LENGTH, 1),
497            draw_line: 0,
498            draw_ptr: 0,
499            del_count: 0,
500            ins_count: 0,
501            is_valid: buf_size != 0,
502            can_undo: true,
503            file_editor: false,
504            is_clipboard: false,
505            modified: false,
506            selecting: false,
507            overwrite: false,
508            auto_indent: true,
509            lock_count: 0,
510            update_flags: 0,
511            pending: None,
512            line_ending: DEFAULT_LINE_ENDING,
513            encoding: Encoding::Default,
514            h_scroll_bar,
515            v_scroll_bar,
516            indicator,
517            find_str: String::new(),
518            replace_str: String::new(),
519            editor_flags: 0,
520            abs_origin: Point::new(0, 0),
521            screen: Point::new(0, 0),
522            track: None,
523            pending_replace_answer: None,
524        };
525        // Initialize logical length to 0 — flag-set only (no flush; no Context).
526        ed.set_buf_len(0);
527        ed
528    }
529
530    /// Construct an `Editor` in file-editor mode (growable buffer, save commands).
531    /// The buffer starts empty and `set_buf_size` grows it on load. A growable
532    /// empty buffer is valid (unlike a fixed 0-size buffer, which would be
533    /// `is_valid == false`).
534    pub(crate) fn new_file_editor(
535        bounds: Rect,
536        h_scroll_bar: Option<ViewId>,
537        v_scroll_bar: Option<ViewId>,
538        indicator: Option<ViewId>,
539    ) -> Self {
540        let mut ed = Editor::new(bounds, h_scroll_bar, v_scroll_bar, indicator, 0);
541        ed.file_editor = true;
542        ed.is_valid = true; // a growable (file) editor with an empty buffer is valid
543        ed
544    }
545
546    // -- test/inspection accessors ------------------------------------------
547
548    /// Number of logical text bytes currently in the buffer (not counting the gap).
549    ///
550    /// Use this to check whether the editor is empty (`buf_len() == 0`) or to
551    /// drive a progress indicator. For the raw text itself, call [`text`](Editor::text).
552    pub fn buf_len(&self) -> usize {
553        self.buf_len
554    }
555
556    /// Byte offset of the cursor in the logical (gap-elided) text.
557    ///
558    /// Use this to record the cursor position before a programmatic edit, or to
559    /// verify cursor placement in tests. Offsets are byte-granular; grapheme
560    /// boundaries are respected by the navigation methods but not enforced here.
561    pub fn cur_ptr(&self) -> usize {
562        self.cur_ptr
563    }
564
565    /// Content extent: `x` = maximum line length (fixed at 256), `y` = number of lines.
566    ///
567    /// Use this to size or configure scroll bars programmatically: `limit().y` is
568    /// the total line count, which equals the vertical scroll range. `limit().x` is
569    /// always 256 (the fixed maximum line length used to set horizontal scroll range).
570    pub fn limit(&self) -> Point {
571        self.limit
572    }
573
574    /// Viewport top-left: `x` = first visible column, `y` = first visible row.
575    ///
576    /// Use this to read the current scroll position, for instance to restore it
577    /// after a programmatic buffer reload. The editor updates `delta` automatically
578    /// when the cursor moves off-screen; set it via [`apply_scroll_delta`](Editor::apply_scroll_delta).
579    pub fn delta(&self) -> Point {
580        self.delta
581    }
582
583    /// Cursor position in display coordinates: `x` = column, `y` = row (both zero-based).
584    ///
585    /// Use this to read the cursor's visual position, for example to assert
586    /// indicator wiring in tests or to display "line N, col M" in a status bar.
587    /// Updated by every navigation and edit operation.
588    pub fn cur_pos(&self) -> Point {
589        self.cur_pos
590    }
591
592    /// Whether the buffer has unsaved changes since the last save or load.
593    ///
594    /// Use this to decide whether to prompt before closing, or to update a dirty
595    /// indicator. Set by any edit; cleared by [`FileEditor`]'s save path. The
596    /// clipboard editor is never marked modified.
597    pub fn modified(&self) -> bool {
598        self.modified
599    }
600
601    /// Reconstruct the logical text (test oracle).
602    pub fn text(&self) -> Vec<u8> {
603        (0..self.buf_len).map(|p| self.buf_char(p)).collect()
604    }
605
606    // -- gap arithmetic -----------------------------------------------------
607
608    /// Physical buffer index of logical offset `p`.
609    fn buf_ptr(&self, p: usize) -> usize {
610        if p < self.cur_ptr {
611            p
612        } else {
613            p + self.gap_len
614        }
615    }
616
617    /// The byte at logical offset `p`.
618    fn buf_char(&self, p: usize) -> u8 {
619        self.buffer[self.buf_ptr(p)]
620    }
621
622    /// Copy up to `dest.len()` logical bytes from `p` into `dest`; returns the
623    /// count copied. Used to materialize a contiguous slice across the gap for
624    /// grapheme decoding.
625    fn get_text(&self, p: usize, dest: &mut [u8]) -> usize {
626        if p < self.buf_len {
627            let count = dest.len().min(self.buf_len - p);
628            for (i, slot) in dest.iter_mut().enumerate().take(count) {
629                *slot = self.buf_char(p + i);
630            }
631            count
632        } else {
633            0
634        }
635    }
636
637    /// Read up to `n` logical bytes starting at `p` into a `Vec` (the contiguous
638    /// materialization used by the grapheme helpers).
639    fn read_chunk(&self, p: usize, n: usize) -> Vec<u8> {
640        let mut buf = vec![0u8; n];
641        let count = self.get_text(p, &mut buf);
642        buf.truncate(count);
643        buf
644    }
645
646    // -- character navigation -----------------------------------------------
647
648    /// Advance one grapheme from `p` (or a `\r\n` pair, or one byte under
649    /// single-byte encoding).
650    fn next_char(&self, p: usize) -> usize {
651        if p + 1 < self.buf_len {
652            if self.buf_char(p) == b'\r' && self.buf_char(p + 1) == b'\n' {
653                return p + 2;
654            }
655            if self.encoding == Encoding::SingleByte {
656                return p + 1;
657            }
658            // Materialize up to 4 bytes and step one grapheme. Clamp the advance
659            // to bytes actually consumed from `chunk`: an invalid UTF-8 byte makes
660            // `from_utf8_lossy` expand 1 byte → the 3-byte U+FFFD, so without the
661            // clamp the cursor would jump 3 logical bytes and desync from a
662            // grapheme boundary.
663            let chunk = self.read_chunk(p, 4);
664            match next_grapheme_byte_len(&chunk) {
665                Some(len) => p + len,
666                None => self.buf_len,
667            }
668        } else {
669            self.buf_len
670        }
671    }
672
673    /// Retreat one grapheme from `p` (or a `\r\n` pair, or one byte).
674    fn prev_char(&self, p: usize) -> usize {
675        if p > 1 {
676            if self.buf_char(p - 2) == b'\r' && self.buf_char(p - 1) == b'\n' {
677                return p - 2;
678            }
679            if self.encoding == Encoding::SingleByte {
680                return p - 1;
681            }
682            let count = 4.min(p);
683            let chunk = self.read_chunk(p - count, count);
684            // Step back over the last grapheme in `chunk`, clamped to its real
685            // byte length: a trailing invalid byte must retreat exactly 1 logical
686            // byte (not the 3 of an expanded U+FFFD).
687            let back = prev_grapheme_byte_len(&chunk);
688            p - back
689        } else {
690            // p == 0 or p == 1 → 0.
691            0
692        }
693    }
694
695    /// Advance `p` over one char and `pos` over its display width (tabs round up
696    /// to the next multiple of 8). Returns false at end of buffer.
697    fn next_char_and_pos(&self, p: &mut usize, pos: &mut i32) -> bool {
698        if *p < self.buf_len {
699            if self.encoding == Encoding::SingleByte {
700                *p += 1;
701                *pos += 1;
702            } else {
703                let chunk = self.read_chunk(*p, 4);
704                if chunk.first() == Some(&b'\t') {
705                    *p += 1;
706                    *pos = (*pos | 7) + 1;
707                } else {
708                    // Width-aware step, with the advance clamped to bytes actually
709                    // consumed from `chunk` (an invalid byte advances exactly 1; see
710                    // `next_char`).
711                    match next_grapheme_with_width(&chunk) {
712                        Some((len, w)) => {
713                            *p += len;
714                            *pos += w as i32;
715                        }
716                        None => {
717                            *p += 1;
718                        }
719                    }
720                }
721            }
722            true
723        } else {
724            false
725        }
726    }
727
728    /// Display column of `target`, scanning from `p`.
729    fn char_pos(&self, mut p: usize, target: usize) -> i32 {
730        let mut pos = 0;
731        while p < target {
732            if !self.next_char_and_pos(&mut p, &mut pos) {
733                break;
734            }
735        }
736        pos
737    }
738
739    /// Logical offset at display column `target` on the line starting at `p`
740    /// (stops at a line break).
741    fn char_ptr(&self, mut p: usize, target: i32) -> usize {
742        let mut pos = 0;
743        let mut prev_p = p;
744        while p < self.buf_len && pos < target {
745            let c = self.buf_char(p);
746            if c == b'\r' || c == b'\n' {
747                break;
748            }
749            prev_p = p;
750            if !self.next_char_and_pos(&mut p, &mut pos) {
751                break;
752            }
753        }
754        if pos > target {
755            p = prev_p;
756        }
757        p
758    }
759
760    /// Offset of the first line break at or after `p` (or `buf_len`).
761    fn line_end(&self, p: usize) -> usize {
762        let mut i = p;
763        while i < self.buf_len {
764            let c = self.buf_char(i);
765            if c == b'\r' || c == b'\n' {
766                return i;
767            }
768            i += 1;
769        }
770        self.buf_len
771    }
772
773    /// Offset of the start of the line containing `p`.
774    fn line_start(&self, p: usize) -> usize {
775        let mut i = p;
776        while i > 0 {
777            i -= 1;
778            let c = self.buf_char(i);
779            if c == b'\r' {
780                if i + 1 != self.cur_ptr && i + 1 != self.buf_len && self.buf_char(i + 1) == b'\n' {
781                    return i + 2;
782                }
783                return i + 1;
784            } else if c == b'\n' {
785                return i + 1;
786            }
787        }
788        0
789    }
790
791    /// Start of the line after `p`.
792    fn next_line(&self, p: usize) -> usize {
793        self.next_char(self.line_end(p))
794    }
795
796    /// Start of the line before `p`.
797    fn prev_line(&self, p: usize) -> usize {
798        self.line_start(self.prev_char(p))
799    }
800
801    /// Start of the next word.
802    fn next_word(&self, mut p: usize) -> usize {
803        if p < self.buf_len {
804            let mut a = self.buf_char(p);
805            loop {
806                let b = a;
807                p = self.next_char(p);
808                if p >= self.buf_len {
809                    break;
810                }
811                a = self.buf_char(p);
812                if is_word_boundary(a, b) {
813                    break;
814                }
815            }
816        }
817        p
818    }
819
820    /// Start of the previous word.
821    fn prev_word(&self, mut p: usize) -> usize {
822        if p > 0 {
823            p = self.prev_char(p);
824            if p > 0 {
825                let mut a = self.buf_char(p);
826                let mut b;
827                loop {
828                    b = a;
829                    p = self.prev_char(p);
830                    a = self.buf_char(p);
831                    if p == 0 || is_word_boundary(a, b) {
832                        break;
833                    }
834                }
835                if is_word_boundary(a, b) {
836                    p = self.next_char(p);
837                }
838            }
839        }
840        p
841    }
842
843    /// First non-whitespace offset on `p`'s line (or the line start if that
844    /// equals `p`).
845    fn indented_line_start(&self, p: usize) -> usize {
846        let start_ptr = self.line_start(p);
847        let mut dest_ptr = start_ptr;
848        while dest_ptr < self.buf_len {
849            let c = self.buf_char(dest_ptr);
850            if c == b' ' || c == b'\t' {
851                dest_ptr += 1;
852            } else {
853                break;
854            }
855        }
856        if dest_ptr == p { start_ptr } else { dest_ptr }
857    }
858
859    /// Move `count` display lines from `p`, preserving the column.
860    fn line_move(&self, mut p: usize, mut count: i32) -> usize {
861        let i0 = p;
862        p = self.line_start(p);
863        let pos = self.char_pos(p, i0);
864        let mut i = p;
865        while count != 0 {
866            i = p;
867            if count < 0 {
868                p = self.prev_line(p);
869                count += 1;
870            } else {
871                p = self.next_line(p);
872                count -= 1;
873            }
874        }
875        if p != i {
876            p = self.char_ptr(p, pos);
877        }
878        p
879    }
880
881    /// Logical offset under the view-local mouse point.
882    fn get_mouse_ptr(&self, mouse_local: Point) -> usize {
883        let mx = mouse_local.x.max(0).min(self.state.size.x - 1);
884        let my = mouse_local.y.max(0).min(self.state.size.y - 1);
885        self.char_ptr(
886            self.line_move(self.draw_ptr, my + self.delta.y - self.draw_line),
887            mx + self.delta.x,
888        )
889    }
890
891    // -- selection / cursor -------------------------------------------------
892
893    /// Whether a non-empty selection exists.
894    pub(crate) fn has_selection(&self) -> bool {
895        self.sel_start != self.sel_end
896    }
897
898    /// Infer the line ending from the first break in the buffer.
899    fn detect_line_ending_type(&self) -> LineEnding {
900        for p in 0..self.buf_len {
901            match self.buf_char(p) {
902                b'\r' => {
903                    if p + 1 < self.buf_len && self.buf_char(p + 1) == b'\n' {
904                        return LineEnding::CrLf;
905                    }
906                    return LineEnding::Cr;
907                }
908                b'\n' => return LineEnding::Lf,
909                _ => {}
910            }
911        }
912        DEFAULT_LINE_ENDING
913    }
914
915    /// Length of `p` after rewriting all of its line breaks to
916    /// [`line_ending`](Editor::line_ending).
917    fn length_with_converted_line_endings(&self, p: &[u8]) -> usize {
918        let le = self.line_ending.bytes().len();
919        let mut new_len = 0;
920        let mut i = 0;
921        while i < p.len() {
922            if p[i] == b'\n' || p[i] == b'\r' {
923                new_len += le;
924                if p[i] == b'\r' && i + 1 < p.len() && p[i + 1] == b'\n' {
925                    i += 1;
926                }
927            } else {
928                new_len += 1;
929            }
930            i += 1;
931        }
932        new_len
933    }
934
935    /// Write `src` into the buffer at `dest_off` with its line breaks converted.
936    /// Writes exactly `length_with_converted_line_endings(src)` bytes.
937    fn copy_and_convert_line_endings(&mut self, dest_off: usize, src: &[u8]) {
938        let le = self.line_ending.bytes();
939        let mut d = dest_off;
940        let mut i = 0;
941        while i < src.len() {
942            let c = src[i];
943            if c == b'\n' || c == b'\r' {
944                self.buffer[d] = le[0];
945                d += 1;
946                if le.len() > 1 {
947                    self.buffer[d] = le[1];
948                    d += 1;
949                }
950                if c == b'\r' && i + 1 < src.len() && src[i + 1] == b'\n' {
951                    i += 1;
952                }
953            } else {
954                self.buffer[d] = c;
955                d += 1;
956            }
957            i += 1;
958        }
959    }
960
961    /// Reset the buffer to `length` logical bytes (the gap is everything after),
962    /// zero cursor/selection/scroll, and recompute the line count.
963    fn set_buf_len(&mut self, length: usize) {
964        self.buf_len = length;
965        self.gap_len = self.buf_size - length;
966        self.sel_start = 0;
967        self.sel_end = 0;
968        self.cur_ptr = 0;
969        self.delta = Point::new(0, 0);
970        self.cur_pos = self.delta;
971        self.limit.x = MAX_LINE_LENGTH;
972        // countLines(&buffer[gapLen], bufLen): the logical bytes live after the
973        // gap when curPtr == 0.
974        let lines = count_lines(&self.buffer[self.gap_len..self.gap_len + self.buf_len]);
975        self.limit.y = lines + 1;
976        self.draw_line = 0;
977        self.draw_ptr = 0;
978        self.del_count = 0;
979        self.ins_count = 0;
980        self.modified = false;
981        self.line_ending = self.detect_line_ending_type();
982        self.update(UF_VIEW);
983    }
984
985    /// Ensure the buffer can hold `new_size` bytes. The plain editor never grows
986    /// (returns whether `new_size` already fits). In **file-editor mode** it grows
987    /// the buffer: round `new_size` up to a 0x1000 boundary, resize the `Vec`, and
988    /// move the post-gap tail to the new end so the gap widens in place.
989    fn set_buf_size(&mut self, new_size: usize) -> bool {
990        if new_size <= self.buf_size {
991            // A shrink path (reclaiming memory when new_size < buf_size) is not
992            // modeled — memory is not reclaimed, but the logical text and all
993            // invariants are unaffected.
994            return true;
995        }
996        if !self.file_editor {
997            return false; // plain editor / memo: fixed buffer, cannot grow.
998        }
999        // Grow path. `Vec` growth is infallible, so there is no
1000        // out-of-memory return.
1001        let rounded = (new_size + 0x0FFF) & !0x0FFF; // round up to 0x1000
1002        let old_size = self.buf_size;
1003        let n = self.buf_len - self.cur_ptr + self.del_count; // bytes after the gap
1004        self.buffer.resize(rounded, 0);
1005        // Move the tail [old_size - n .. old_size] to [rounded - n .. rounded]
1006        // (copy_within is overlap-safe).
1007        self.buffer.copy_within(old_size - n..old_size, rounded - n);
1008        self.buf_size = rounded;
1009        self.gap_len = self.buf_size - self.buf_len;
1010        true
1011    }
1012
1013    /// Replace the whole buffer with `text` (used by [`Memo::set_value`]).
1014    /// All-or-nothing: if `text` does not fit the buffer and it cannot grow
1015    /// (plain editor / memo have a fixed buffer; file-editor mode grows instead),
1016    /// it is a no-op. The replaced text is left unselected.
1017    pub fn set_text(&mut self, text: &[u8]) {
1018        if self.set_buf_size(text.len()) {
1019            let start = self.buf_size - text.len();
1020            self.buffer[start..].copy_from_slice(text);
1021            self.set_buf_len(text.len());
1022        }
1023    }
1024
1025    /// Set the selection to `[new_start, new_end)` and place the cursor at the
1026    /// start endpoint when `cur_start`, else the end. Moving the gap to the chosen
1027    /// endpoint is the load-bearing operation.
1028    ///
1029    /// Context-free (no flush); the public, flushing wrapper is
1030    /// [`set_select`](Self::set_select).
1031    fn set_select_core(&mut self, new_start: usize, new_end: usize, cur_start: bool) {
1032        let p = if cur_start { new_start } else { new_end };
1033
1034        let mut flags = UF_UPDATE;
1035        if (new_start != self.sel_start || new_end != self.sel_end)
1036            && (new_start != new_end || self.sel_start != self.sel_end)
1037        {
1038            flags = UF_VIEW;
1039        }
1040
1041        if p != self.cur_ptr {
1042            if p > self.cur_ptr {
1043                // Move text from after the gap to before it.
1044                let l = p - self.cur_ptr;
1045                let src = self.cur_ptr + self.gap_len;
1046                self.buffer.copy_within(src..src + l, self.cur_ptr);
1047                let lines = count_lines(&self.buffer[self.cur_ptr..self.cur_ptr + l]);
1048                self.cur_pos.y += lines;
1049                self.cur_ptr = p;
1050            } else {
1051                let l = self.cur_ptr - p;
1052                self.cur_ptr = p;
1053                let lines = count_lines(&self.buffer[self.cur_ptr..self.cur_ptr + l]);
1054                self.cur_pos.y -= lines;
1055                // Move text from before the gap to after it.
1056                let dst = self.cur_ptr + self.gap_len;
1057                self.buffer.copy_within(self.cur_ptr..self.cur_ptr + l, dst);
1058            }
1059            self.del_count = 0;
1060            self.ins_count = 0;
1061            // A shrink-to-fit here is a no-op (the buffer never shrinks; see
1062            // set_buf_size).
1063        }
1064        self.draw_line = self.cur_pos.y;
1065        self.draw_ptr = self.line_start(p);
1066        self.cur_pos.x = self.char_pos(self.draw_ptr, p);
1067        self.sel_start = new_start;
1068        self.sel_end = new_end;
1069        self.update(flags);
1070    }
1071
1072    /// Move the cursor to `p`, optionally extending the selection (and snapping to
1073    /// word/line granularity per `select_mode`).
1074    ///
1075    /// Context-free (no flush); the public, flushing wrapper is
1076    /// [`set_cur_ptr`](Self::set_cur_ptr).
1077    fn set_cur_ptr_core(&mut self, mut p: usize, select_mode: u8) {
1078        let mut anchor = if (select_mode & SM_EXTEND) == 0 {
1079            p
1080        } else if self.cur_ptr == self.sel_start {
1081            self.sel_end
1082        } else {
1083            self.sel_start
1084        };
1085
1086        if p < anchor {
1087            if (select_mode & SM_DOUBLE) != 0 {
1088                p = self.prev_word(self.next_word(p));
1089                anchor = self.next_word(self.prev_word(anchor));
1090            } else if (select_mode & SM_TRIPLE) != 0 {
1091                p = self.prev_line(self.next_line(p));
1092                anchor = self.next_line(self.prev_line(anchor));
1093            }
1094            self.set_select_core(p, anchor, true);
1095        } else {
1096            if (select_mode & SM_DOUBLE) != 0 {
1097                p = self.next_word(p);
1098                anchor = self.prev_word(self.next_word(anchor));
1099            } else if (select_mode & SM_TRIPLE) != 0 {
1100                p = self.next_line(p);
1101                anchor = self.prev_line(self.next_line(anchor));
1102            }
1103            self.set_select_core(anchor, p, false);
1104        }
1105    }
1106
1107    /// Begin a persistent selection.
1108    fn start_select(&mut self) {
1109        self.hide_select();
1110        self.selecting = true;
1111    }
1112
1113    /// Collapse the selection to the cursor.
1114    fn hide_select(&mut self) {
1115        self.selecting = false;
1116        self.set_select_core(self.cur_ptr, self.cur_ptr, false);
1117    }
1118
1119    /// Flip overwrite mode and the block-cursor flag.
1120    fn toggle_ins_mode(&mut self) {
1121        self.overwrite = !self.overwrite;
1122        let ins = self.state.state.cursor_ins;
1123        self.state.state.cursor_ins = !ins;
1124    }
1125
1126    /// Flip between multibyte and single-byte encoding.
1127    fn toggle_encoding(&mut self) {
1128        self.encoding = if self.encoding == Encoding::Default {
1129            Encoding::SingleByte
1130        } else {
1131            Encoding::Default
1132        };
1133        self.update_flags |= UF_VIEW;
1134        let cur_start = self.cur_ptr < self.sel_end;
1135        self.set_select_core(self.sel_start, self.sel_end, cur_start);
1136    }
1137
1138    // -- insertion / deletion -----------------------------------------------
1139
1140    /// THE core edit: replace a range with bytes from `p`, with optional undo and
1141    /// optional selection of the inserted text.
1142    ///
1143    /// `p` must **not** alias `self.buffer` — callers snapshot first.
1144    fn insert_buffer(
1145        &mut self,
1146        p: &[u8],
1147        offset: usize,
1148        length: usize,
1149        allow_undo: bool,
1150        select_text: bool,
1151    ) -> bool {
1152        self.selecting = false;
1153        let sel_len = self.sel_end - self.sel_start;
1154        if sel_len == 0 && length == 0 {
1155            return true;
1156        }
1157
1158        let mut del_len = 0;
1159        if allow_undo {
1160            if self.cur_ptr == self.sel_start {
1161                del_len = sel_len;
1162            } else if sel_len > self.ins_count {
1163                del_len = sel_len - self.ins_count;
1164            }
1165        }
1166
1167        let ins_len = self.length_with_converted_line_endings(&p[offset..offset + length]);
1168        let new_size = self.buf_len + self.del_count - sel_len + del_len + ins_len;
1169
1170        if new_size > self.buf_len + self.del_count && !self.set_buf_size(new_size) {
1171            // edOutOfMemory — collapse the selection and bail.
1172            self.sel_end = self.sel_start;
1173            return false;
1174        }
1175
1176        let sel_lines = count_lines(&self.buffer[self.buf_ptr(self.sel_start)..][..sel_len]);
1177        if self.cur_ptr == self.sel_end {
1178            if allow_undo {
1179                if del_len > 0 {
1180                    // memmove(&buffer[curPtr+gapLen-delCount-delLen],
1181                    //         &buffer[selStart], delLen)
1182                    let dst = self.cur_ptr + self.gap_len - self.del_count - del_len;
1183                    let src = self.sel_start;
1184                    self.buffer.copy_within(src..src + del_len, dst);
1185                }
1186                self.ins_count -= sel_len - del_len;
1187            }
1188            self.cur_ptr = self.sel_start;
1189            self.cur_pos.y -= sel_lines;
1190        }
1191        if self.delta.y > self.cur_pos.y {
1192            self.delta.y -= sel_lines;
1193            if self.delta.y < self.cur_pos.y {
1194                self.delta.y = self.cur_pos.y;
1195            }
1196        }
1197
1198        if length > 0 {
1199            self.copy_and_convert_line_endings(self.cur_ptr, &p[offset..offset + length]);
1200        }
1201
1202        let lines = count_lines(&self.buffer[self.cur_ptr..self.cur_ptr + ins_len]);
1203        self.cur_ptr += ins_len;
1204        // bufLen += insLen - selLen; gapLen -= insLen - selLen. The delta is signed
1205        // (negative on a net deletion), so do it with isize to avoid usize wrap.
1206        let delta_len = ins_len as isize - sel_len as isize;
1207        self.buf_len = (self.buf_len as isize + delta_len) as usize;
1208        self.gap_len = (self.gap_len as isize - delta_len) as usize;
1209        self.cur_pos.y += lines;
1210        self.draw_line = self.cur_pos.y;
1211        self.draw_ptr = self.line_start(self.cur_ptr);
1212        self.cur_pos.x = self.char_pos(self.draw_ptr, self.cur_ptr);
1213        if !select_text {
1214            self.sel_start = self.cur_ptr;
1215        }
1216        self.sel_end = self.cur_ptr;
1217        if allow_undo {
1218            self.del_count += del_len;
1219            self.ins_count += ins_len;
1220        }
1221        self.limit.y += lines - sel_lines;
1222        self.delta.y = 0.max(self.delta.y.min(self.limit.y - self.state.size.y));
1223        // C++: `if (isClipboard() == False) modified = True;`
1224        // The clipboard editor itself stays unmodified (it is not a "file" —
1225        // modified tracking is for the save guard).
1226        if !self.is_clipboard {
1227            self.modified = true;
1228        }
1229        // setBufSize(bufLen + delCount) — no-op for the base.
1230        if sel_lines == 0 && lines == 0 {
1231            self.update(UF_LINE);
1232        } else {
1233            self.update(UF_VIEW);
1234        }
1235        true
1236    }
1237
1238    /// Insert `text` at the cursor (the ctx-free insert core), optionally
1239    /// selecting the inserted bytes.
1240    fn insert_text_core(&mut self, text: &[u8], select_text: bool) -> bool {
1241        self.insert_buffer(text, 0, text.len(), self.can_undo, select_text)
1242    }
1243
1244    /// Delete the current selection.
1245    fn delete_select(&mut self) {
1246        self.insert_buffer(&[], 0, 0, self.can_undo, false);
1247    }
1248
1249    /// Insert `data` (another editor's selection bytes) into this editor. The
1250    /// inserted text is selected only when this is the clipboard editor; a normal
1251    /// destination editor leaves it unselected.
1252    ///
1253    /// Called by the pump's clipboard brokers: the cut/copy path (destination =
1254    /// clipboard editor, selects the content) and the paste path (destination =
1255    /// normal editor, no selection). After the insert the caller must call
1256    /// `flush_if_unlocked` to publish updated scroll-bar params.
1257    pub(crate) fn insert_from(&mut self, data: &[u8], ctx: &mut Context) -> bool {
1258        let res = self.insert_buffer(data, 0, data.len(), self.can_undo, self.is_clipboard);
1259        self.flush_if_unlocked(ctx);
1260        res
1261    }
1262
1263    /// Extract the current selection as a byte vec (for the clipboard broker).
1264    /// The selection bytes are always physically contiguous in the gap buffer (the
1265    /// cursor sits at one selection endpoint, so the gap never lies inside the
1266    /// selection).
1267    pub(crate) fn selection_bytes(&self) -> Vec<u8> {
1268        let len = self.sel_end - self.sel_start;
1269        let start = self.buf_ptr(self.sel_start);
1270        self.buffer[start..start + len].to_vec()
1271    }
1272
1273    /// Delete the range `[start_ptr, end_ptr)`, honoring an existing selection
1274    /// when `del_select`.
1275    fn delete_range(&mut self, start_ptr: usize, end_ptr: usize, del_select: bool) {
1276        if self.has_selection() && del_select {
1277            self.delete_select();
1278        } else {
1279            self.set_select_core(self.cur_ptr, end_ptr, true);
1280            self.delete_select();
1281            self.set_select_core(start_ptr, self.cur_ptr, false);
1282            self.delete_select();
1283        }
1284    }
1285
1286    /// Insert a line break, replicating the current line's leading indent when
1287    /// auto-indent is on.
1288    fn new_line(&mut self) {
1289        let p = self.line_start(self.cur_ptr);
1290        let mut i = p;
1291        while i < self.cur_ptr {
1292            let c = self.buffer[self.buf_ptr(i)];
1293            if c == b' ' || c == b'\t' {
1294                i += 1;
1295            } else {
1296                break;
1297            }
1298        }
1299        self.insert_text_core(b"\n", false);
1300        if self.auto_indent {
1301            // Snapshot the indent run BEFORE inserting (source must not alias
1302            // self.buffer). The run is physically contiguous (it precedes the
1303            // cursor, and after the "\n" insert the gap sits past the cursor).
1304            let indent: Vec<u8> = (p..p + (i - p)).map(|q| self.buf_char(q)).collect();
1305            self.insert_text_core(&indent, false);
1306        }
1307    }
1308
1309    /// Single-level undo: restore the most recently deleted text and drop the most
1310    /// recently inserted.
1311    fn undo(&mut self) {
1312        if self.del_count != 0 || self.ins_count != 0 {
1313            self.sel_start = self.cur_ptr - self.ins_count;
1314            self.sel_end = self.cur_ptr;
1315            let length = self.del_count;
1316            self.del_count = 0;
1317            self.ins_count = 0;
1318            // Source = the deleted text, which lives in the gap just before its
1319            // end. Snapshot first (no alias).
1320            let start = self.cur_ptr + self.gap_len - length;
1321            let snapshot: Vec<u8> = self.buffer[start..start + length].to_vec();
1322            self.insert_buffer(&snapshot, 0, length, false, true);
1323        }
1324    }
1325
1326    // -- search -------------------------------------------------------------
1327
1328    /// Find `needle` from the cursor; on a hit, select it and track the cursor.
1329    /// This is the low-level search primitive; the interactive Find / Replace
1330    /// dialogs drive it through `do_search_replace`.
1331    ///
1332    /// Context-free: instead of flushing inline, this only records the scroll
1333    /// target; the actual flush happens on the next `handle_event` boundary.
1334    pub fn search(&mut self, needle: &str, opts: u16) -> bool {
1335        let needle = needle.as_bytes();
1336        let mut pos = self.cur_ptr;
1337        loop {
1338            // bufLen - pos logical bytes are reachable from `pos`; they are NOT
1339            // contiguous across the gap, so materialize them.
1340            let block = self.read_chunk(pos, self.buf_len - pos);
1341            let i = if (opts & EF_CASE_SENSITIVE) != 0 {
1342                scan(&block, needle)
1343            } else {
1344                i_scan(&block, needle)
1345            };
1346            if i == SEARCH_FAILED {
1347                return false;
1348            }
1349            let hit = i + pos;
1350            let nlen = needle.len();
1351            let whole_ok = (opts & EF_WHOLE_WORDS_ONLY) == 0
1352                || !((hit != 0 && is_word_char(self.buf_char(hit - 1)))
1353                    || (hit + nlen != self.buf_len && is_word_char(self.buf_char(hit + nlen))));
1354            if whole_ok {
1355                self.set_select_core(hit, hit + nlen, false);
1356                let center = !self.cursor_visible();
1357                self.track_cursor_core(center);
1358                return true;
1359            } else {
1360                pos = hit + 1;
1361            }
1362        }
1363    }
1364
1365    // -- viewport -----------------------------------------------------------
1366
1367    /// Whether the cursor row is within the visible viewport.
1368    fn cursor_visible(&self) -> bool {
1369        self.cur_pos.y >= self.delta.y && self.cur_pos.y < self.delta.y + self.state.size.y
1370    }
1371
1372    /// Set the scroll offset (clamped to the content extent) and flag a redraw.
1373    ///
1374    /// Context-free (no flush); the public, flushing wrapper is
1375    /// [`scroll_to`](Self::scroll_to).
1376    fn scroll_to_core(&mut self, x: i32, y: i32) {
1377        let x = 0.max(x.min(self.limit.x - self.state.size.x));
1378        let y = 0.max(y.min(self.limit.y - self.state.size.y));
1379        if x != self.delta.x || y != self.delta.y {
1380            self.delta.x = x;
1381            self.delta.y = y;
1382            self.update(UF_VIEW);
1383        }
1384    }
1385
1386    /// One tick of the middle-button pan: scroll by `last - mouse` (the movement
1387    /// since the previous tick) and remember the new position, never touching the
1388    /// cursor or selection. The pan does not take an update lock, so the scroll's
1389    /// view-repaint flushes immediately, which `flush_if_unlocked` mirrors.
1390    fn pan_tick(&mut self, last: Point, moved: bool, mouse: Point, ctx: &mut Context) {
1391        let d = Point::new(
1392            self.delta.x + last.x - mouse.x,
1393            self.delta.y + last.y - mouse.y,
1394        );
1395        self.scroll_to_core(d.x, d.y);
1396        // An auto-repeat at the held position has `mouse == last` — a no-op
1397        // scroll, and NOT movement: holding the button still then releasing is
1398        // still a paste, not a zero-distance pan.
1399        self.track = Some(EditorTrack::Pan {
1400            last: mouse,
1401            moved: moved || mouse != last,
1402        });
1403        self.flush_if_unlocked(ctx);
1404    }
1405
1406    /// Publish the current selection as the X11/Wayland PRIMARY selection, so
1407    /// another client can middle-click-paste it. The twin of
1408    /// [`InputLine::publish_primary`](crate::widgets::InputLine); called only
1409    /// when a **mouse** selection completes.
1410    fn publish_primary(&self, ctx: &mut Context) {
1411        if self.has_selection()
1412            && let Ok(text) = String::from_utf8(self.selection_bytes())
1413        {
1414            ctx.set_primary(text);
1415        }
1416    }
1417
1418    /// Scroll so the cursor is visible (centering it when `center`).
1419    ///
1420    /// Context-free (no flush); the public, flushing wrapper is
1421    /// [`track_cursor`](Self::track_cursor).
1422    fn track_cursor_core(&mut self, center: bool) {
1423        if center {
1424            self.scroll_to_core(
1425                self.cur_pos.x - self.state.size.x + 1,
1426                self.cur_pos.y - self.state.size.y / 2,
1427            );
1428        } else {
1429            self.scroll_to_core(
1430                (self.cur_pos.x - self.state.size.x + 1).max(self.delta.x.min(self.cur_pos.x)),
1431                (self.cur_pos.y - self.state.size.y + 1).max(self.delta.y.min(self.cur_pos.y)),
1432            );
1433        }
1434    }
1435
1436    // -- public caret/selection/scroll API (C++-public) ----------------------
1437
1438    /// Set the selection to `[start, end)` and place the cursor at the `start`
1439    /// endpoint when `cur_start`, else the `end` endpoint, then publish the
1440    /// new cursor/selection state.
1441    ///
1442    /// # Turbo Vision heritage
1443    ///
1444    /// Ports `TEditor::setSelect`, which C++ exposes publicly. The `ctx`
1445    /// parameter is the tvision-rs deviation already established by
1446    /// [`insert_text`](Self::insert_text)/[`apply_scroll_delta`](Self::apply_scroll_delta):
1447    /// publishing the cursor and scroll-bar params needs a `Context` to reach
1448    /// the pump's broker. For a context-free call (no flush) use the internal
1449    /// `set_select_core`.
1450    pub fn set_select(&mut self, start: usize, end: usize, cur_start: bool, ctx: &mut Context) {
1451        self.set_select_core(start, end, cur_start);
1452        self.flush_if_unlocked(ctx);
1453    }
1454
1455    /// Move the cursor to byte offset `p`, optionally extending the selection
1456    /// (and snapping to word/line granularity per `select_mode`), then
1457    /// publish.
1458    ///
1459    /// This does **not** scroll the cursor into view on its own — call
1460    /// [`track_cursor`](Self::track_cursor) afterward if the new position
1461    /// might be offscreen, exactly as the C++ call sites do.
1462    ///
1463    /// # Turbo Vision heritage
1464    ///
1465    /// Ports `TEditor::setCurPtr`, which C++ exposes publicly. See
1466    /// [`set_select`](Self::set_select) for why this takes a `ctx`. For a
1467    /// context-free call (no flush) use the internal `set_cur_ptr_core`.
1468    pub fn set_cur_ptr(&mut self, p: usize, select_mode: u8, ctx: &mut Context) {
1469        self.set_cur_ptr_core(p, select_mode);
1470        self.flush_if_unlocked(ctx);
1471    }
1472
1473    /// Set the scroll offset to `(x, y)`, clamped to the content extent, and
1474    /// publish the new scroll-bar params.
1475    ///
1476    /// # Turbo Vision heritage
1477    ///
1478    /// Ports `TEditor::scrollTo`, which C++ exposes publicly. See
1479    /// [`set_select`](Self::set_select) for why this takes a `ctx`. For a
1480    /// context-free call (no flush) use the internal `scroll_to_core`.
1481    pub fn scroll_to(&mut self, x: i32, y: i32, ctx: &mut Context) {
1482        self.scroll_to_core(x, y);
1483        self.flush_if_unlocked(ctx);
1484    }
1485
1486    /// Scroll so the cursor is visible, centering it when `center`, and
1487    /// publish the new scroll-bar params.
1488    ///
1489    /// # Turbo Vision heritage
1490    ///
1491    /// Ports `TEditor::trackCursor`, which C++ exposes publicly. See
1492    /// [`set_select`](Self::set_select) for why this takes a `ctx`. For a
1493    /// context-free call (no flush) use the internal `track_cursor_core`.
1494    pub fn track_cursor(&mut self, center: bool, ctx: &mut Context) {
1495        self.track_cursor_core(center);
1496        self.flush_if_unlocked(ctx);
1497    }
1498
1499    // -- scroll-bar broker apply hook (tvision-rs seam, not a C++ port) ------
1500
1501    /// Adopt new scroll offsets read from the scroll bars (applied by the pump).
1502    ///
1503    /// Public ctx-taking entry: the pump reads each scroll bar's value, then calls
1504    /// this with `dx`/`dy` (`None` = no bar). For each present bar, if its value
1505    /// differs from the current offset, adopt it and flag a full redraw; then
1506    /// flush.
1507    pub fn apply_scroll_delta(&mut self, dx: Option<i32>, dy: Option<i32>, ctx: &mut Context) {
1508        if let Some(x) = dx
1509            && x != self.delta.x
1510        {
1511            self.delta.x = x;
1512            self.update(UF_VIEW);
1513        }
1514        if let Some(y) = dy
1515            && y != self.delta.y
1516        {
1517            self.delta.y = y;
1518            self.update(UF_VIEW);
1519        }
1520        self.flush_if_unlocked(ctx);
1521    }
1522
1523    // -- external text insertion (C++-public: TEditor::insertText) ----------
1524
1525    /// Insert `text` at the cursor, optionally leaving the inserted bytes selected.
1526    ///
1527    /// Use this to inject text from the outside (clipboard paste, template fill,
1528    /// programmatic population). `select_text = true` leaves the new text selected
1529    /// (useful for a paste that should be immediately replaceable). Flushes after
1530    /// the insert so scroll-bar params and the indicator are updated on the next pump.
1531    /// For a context-free insert (no flush) use the internal `insert_text_core`.
1532    pub fn insert_text(&mut self, text: &[u8], select_text: bool, ctx: &mut Context) {
1533        self.lock();
1534        self.insert_text_core(text, select_text);
1535        let center = !self.cursor_visible();
1536        self.track_cursor_core(center);
1537        self.unlock(ctx);
1538    }
1539
1540    // -- update / lock / flush ----------------------------------------------
1541
1542    /// Record pending redraw flags; no inline flush (see the context-threading
1543    /// split in the [`Editor`] docs).
1544    fn update(&mut self, flags: u8) {
1545        self.update_flags |= flags;
1546    }
1547
1548    /// Take an update lock (deferring flushes until it is released).
1549    fn lock(&mut self) {
1550        self.lock_count += 1;
1551    }
1552
1553    /// Release an update lock; flush when the count returns to 0.
1554    fn unlock(&mut self, ctx: &mut Context) {
1555        if self.lock_count > 0 {
1556            self.lock_count -= 1;
1557            if self.lock_count == 0 {
1558                self.do_update(ctx);
1559            }
1560        }
1561    }
1562
1563    /// Flush if not inside a lock — the trailing flush for `handle_event`'s
1564    /// unlocked arms.
1565    fn flush_if_unlocked(&mut self, ctx: &mut Context) {
1566        if self.lock_count == 0 {
1567            self.do_update(ctx);
1568        }
1569    }
1570
1571    /// Publish cursor, scrollbar params, and the indicator value if any update is
1572    /// pending. The whole-tree redraw handles the repaint.
1573    fn do_update(&mut self, ctx: &mut Context) {
1574        if self.update_flags == 0 {
1575            return;
1576        }
1577        // Cursor in view-local coords = content position minus the scroll offset.
1578        self.state
1579            .set_cursor(self.cur_pos.x - self.delta.x, self.cur_pos.y - self.delta.y);
1580        // No explicit text repaint here: the whole tree is redrawn and diffed.
1581        let size = self.state.size;
1582        if let Some(h) = self.h_scroll_bar {
1583            ctx.request_scroll_bar_params(
1584                h,
1585                Some(self.delta.x),
1586                Some(0),
1587                Some(self.limit.x - size.x),
1588                Some(size.x / 2),
1589                Some(1),
1590            );
1591        }
1592        if let Some(v) = self.v_scroll_bar {
1593            ctx.request_scroll_bar_params(
1594                v,
1595                Some(self.delta.y),
1596                Some(0),
1597                Some(self.limit.y - size.y),
1598                Some(size.y - 1),
1599                Some(1),
1600            );
1601        }
1602        if let Some(ind) = self.indicator {
1603            ctx.set_indicator_value(ind, self.cur_pos, self.modified);
1604        }
1605        if self.state.state.active {
1606            self.update_commands(ctx);
1607        }
1608        self.update_flags = 0;
1609    }
1610
1611    /// Enable `command` iff `enable` and this editor is active, else disable it.
1612    fn set_cmd_state(&self, command: crate::command::Command, enable: bool, ctx: &mut Context) {
1613        if enable && self.state.state.active {
1614            ctx.enable_command(command);
1615        } else {
1616            ctx.disable_command(command);
1617        }
1618    }
1619
1620    /// Gray/ungray the editing commands according to the current state.
1621    fn update_commands(&self, ctx: &mut Context) {
1622        use crate::command::Command;
1623        let has_undo = self.del_count != 0 || self.ins_count != 0;
1624        self.set_cmd_state(Command::UNDO, has_undo, ctx);
1625        // The clipboard editor does not update cut/copy/paste (it is not a
1626        // user-editable file editor).
1627        if !self.is_clipboard {
1628            let has_sel = self.has_selection();
1629            self.set_cmd_state(Command::CUT, has_sel, ctx);
1630            self.set_cmd_state(Command::COPY, has_sel, ctx);
1631            // Paste is allowed when there is no clipboard editor, or it has a
1632            // selection to paste.
1633            let paste_ok = ctx.clipboard_editor_id().is_none() || ctx.clipboard_has_selection();
1634            self.set_cmd_state(Command::PASTE, paste_ok, ctx);
1635        }
1636        self.set_cmd_state(Command::CLEAR, self.has_selection(), ctx);
1637        self.set_cmd_state(Command::FIND, true, ctx);
1638        self.set_cmd_state(Command::REPLACE, true, ctx);
1639        self.set_cmd_state(Command::SEARCH_AGAIN, true, ctx);
1640        if self.file_editor {
1641            // File editor: Save / Save As are always enabled while active.
1642            self.set_cmd_state(Command::SAVE, true, ctx);
1643            self.set_cmd_state(Command::SAVE_AS, true, ctx);
1644        }
1645    }
1646
1647    /// Clear the dirty flag and request an indicator/cursor redraw (the tail of a
1648    /// successful save).
1649    fn clear_modified(&mut self) {
1650        self.modified = false;
1651        self.update(UF_UPDATE);
1652    }
1653
1654    // -- clipboard ------------------------------------------------------------
1655
1656    /// Copy the selection to the internal or system clipboard.
1657    fn clip_copy(&mut self, ctx: &mut Context) -> bool {
1658        // The clipboard editor cannot copy from itself.
1659        if ctx.clipboard_editor_id() == self.state.id() && self.state.id().is_some() {
1660            return false;
1661        }
1662        if let Some(clipboard_id) = ctx.clipboard_editor_id() {
1663            // Internal clipboard: snapshot the selection bytes and hand them to
1664            // the clipboard editor.
1665            let data = self.selection_bytes();
1666            ctx.clipboard_editor_receive(clipboard_id, data);
1667            self.selecting = false;
1668            self.update(UF_UPDATE);
1669            true
1670        } else {
1671            // System clipboard path.
1672            let len = self.sel_end - self.sel_start;
1673            let start = self.buf_ptr(self.sel_start);
1674            // The selection is always physically contiguous (curPtr is always at
1675            // selStart or selEnd, so the gap never sits inside the selection).
1676            let text = String::from_utf8_lossy(&self.buffer[start..start + len]).into_owned();
1677            ctx.set_clipboard(text);
1678            self.selecting = false;
1679            self.update(UF_UPDATE);
1680            true
1681        }
1682    }
1683
1684    /// Cut: copy the selection, then delete it.
1685    fn clip_cut(&mut self, ctx: &mut Context) {
1686        if self.clip_copy(ctx) {
1687            self.delete_select();
1688        }
1689    }
1690
1691    /// Paste from the internal or system clipboard.
1692    fn clip_paste(&mut self, ctx: &mut Context) {
1693        if let Some(clipboard_id) = ctx.clipboard_editor_id() {
1694            // Internal clipboard: ClipboardEditorPaste broker reads clipboard's
1695            // selection and inserts into self. C++: `insertFrom(clipboard)`.
1696            if let Some(id) = self.state.id() {
1697                ctx.clipboard_editor_paste(id, clipboard_id);
1698            }
1699        } else {
1700            // System clipboard path.
1701            if let Some(id) = self.state.id() {
1702                ctx.editor_paste(id);
1703            }
1704        }
1705    }
1706
1707    // -- find/replace accessor methods ----------------------------------------
1708
1709    /// Read the find string — for the drain-handler pre-fill.
1710    pub(crate) fn find_str(&self) -> &str {
1711        &self.find_str
1712    }
1713
1714    /// Read the replace string — for the drain-handler pre-fill.
1715    pub(crate) fn replace_str(&self) -> &str {
1716        &self.replace_str
1717    }
1718
1719    /// Read `editor_flags` — for the drain-handler pre-fill.
1720    pub(crate) fn editor_flags(&self) -> u16 {
1721        self.editor_flags
1722    }
1723
1724    /// Set `editor_flags` — used in tests and internal construction.
1725    #[cfg_attr(not(test), allow(dead_code))]
1726    pub(crate) fn set_editor_flags(&mut self, f: u16) {
1727        self.editor_flags = f;
1728    }
1729
1730    // -- find/replace dialogs -----------------------------------------------
1731
1732    /// One pass of the search/replace loop.
1733    ///
1734    /// The "Replace this occurrence?" prompt is asynchronous: it goes through the
1735    /// `request_message_box` seam rather than a blocking dialog call, and
1736    /// `pending_replace_answer` carries the user's choice between pump iterations.
1737    fn do_search_replace(&mut self, ctx: &mut Context) {
1738        use crate::command::Command;
1739        use crate::dialog::{MessageBoxButtons, MessageBoxKind};
1740
1741        let opts = self.editor_flags;
1742        let do_replace = (opts & EF_DO_REPLACE) != 0;
1743        let replace_all = (opts & EF_REPLACE_ALL) != 0;
1744        let prompt = (opts & EF_PROMPT_ON_REPLACE) != 0;
1745
1746        // `search`/`insert_text` need `&mut self`, so the find/replace strings
1747        // can't be borrowed across those calls — clone once up front rather than
1748        // per loop iteration.
1749        let find = self.find_str.clone();
1750        let replacement = self.replace_str.clone();
1751
1752        // If there is a pending answer from a previous replace-prompt dialog,
1753        // act on it before searching for the next occurrence.
1754        if let Some(answer) = self.pending_replace_answer.take() {
1755            match answer {
1756                Command::YES => {
1757                    // Replace the current selection (still set from the last search).
1758                    self.insert_text(replacement.as_bytes(), false, ctx);
1759                    if !replace_all {
1760                        return;
1761                    }
1762                    // Fall through to search for the next occurrence.
1763                }
1764                Command::CANCEL => {
1765                    return; // user cancelled the replace loop
1766                }
1767                _ => {
1768                    // cmNo: C++ loop condition is `while (i != cmCancel && efReplaceAll)`,
1769                    // so when efReplaceAll is NOT set the loop exits on cmNo too.
1770                    if !replace_all {
1771                        return;
1772                    }
1773                    // efReplaceAll: fall through to search next (curPtr is at selEnd).
1774                }
1775            }
1776        }
1777
1778        // Main search/replace loop (runs at least once; loops only on replace_all
1779        // without a prompt since the prompt path returns above).
1780        loop {
1781            if !self.search(&find, opts) {
1782                // Search string not found. C++ only shows the dialog when NOT
1783                // (replace_all && do_replace).
1784                if !(replace_all && do_replace) {
1785                    ctx.request_message_box(
1786                        "Search string not found.".into(),
1787                        MessageBoxKind::Error,
1788                        MessageBoxButtons::ok(),
1789                        None,
1790                        None,
1791                    );
1792                }
1793                return;
1794            }
1795
1796            if do_replace {
1797                if prompt {
1798                    // Ask user — deferred async message box; answer routes back
1799                    // via set_modal_answer + SEARCH_AGAIN re-inject.
1800                    if let Some(id) = self.state.id() {
1801                        ctx.request_message_box(
1802                            "Replace this occurrence?".into(),
1803                            MessageBoxKind::Information,
1804                            MessageBoxButtons::yes_no_cancel(),
1805                            Some(id),                    // answer_to = this editor
1806                            Some(Command::SEARCH_AGAIN), // re-run after answer
1807                        );
1808                    }
1809                    return; // wait for answer
1810                } else {
1811                    // No prompt: replace immediately.
1812                    self.insert_text(replacement.as_bytes(), false, ctx);
1813                    if !replace_all {
1814                        return;
1815                    }
1816                    // Continue loop for replace_all (no prompt).
1817                }
1818            } else {
1819                return; // found, no replace
1820            }
1821        }
1822    }
1823
1824    // -- line formatting / draw ---------------------------------------------
1825
1826    /// The color role at offset `p`: the selected role inside the selection, else
1827    /// the normal role.
1828    fn color_at(&self, p: usize) -> Role {
1829        if self.sel_start <= p && p < self.sel_end {
1830            Role::ScrollerSelected
1831        } else {
1832            Role::ScrollerNormal
1833        }
1834    }
1835
1836    /// Render one display row (the line starting at `line_ptr`) into the row at
1837    /// view-local `y`, honoring the horizontal scroll and width.
1838    fn format_line(&self, ctx: &mut DrawCtx, y: i32, line_ptr: usize, h_scroll: i32, width: i32) {
1839        let h_scroll = h_scroll.max(0);
1840        let width = width.max(0);
1841
1842        let mut p = line_ptr;
1843        let mut pos = 0i32;
1844        let mut x = 0i32;
1845        while p < self.buf_len {
1846            let mut next_p = p;
1847            let mut next_pos = pos;
1848            self.next_char_and_pos(&mut next_p, &mut next_pos);
1849
1850            if x > width || (x == width && pos < next_pos) {
1851                break;
1852            }
1853
1854            let char_len = next_p - p;
1855            let chunk = self.read_chunk(p, char_len);
1856            if chunk.first() == Some(&b'\r') || chunk.first() == Some(&b'\n') {
1857                break;
1858            }
1859
1860            if next_pos > h_scroll {
1861                let role = self.color_at(p);
1862                let style = ctx.style(role);
1863                let char_width = next_pos - pos.max(h_scroll);
1864                if chunk.first() == Some(&b'\t') || pos < h_scroll {
1865                    for k in 0..char_width {
1866                        ctx.put_char(x + k, y, ' ', style);
1867                    }
1868                } else {
1869                    let s = String::from_utf8_lossy(&chunk);
1870                    ctx.put_str(x, y, &s, style);
1871                }
1872                x += char_width;
1873            }
1874
1875            p = next_p;
1876            pos = next_pos;
1877        }
1878
1879        if x < width {
1880            let role = self.color_at(p);
1881            let style = ctx.style(role);
1882            for k in 0..(width - x) {
1883                ctx.put_char(x + k, y, ' ', style);
1884            }
1885        }
1886    }
1887
1888    /// Render `count` rows starting at view-local `y`, from the line at
1889    /// `line_ptr`.
1890    fn draw_lines(&self, ctx: &mut DrawCtx, y: i32, count: i32, mut line_ptr: usize) {
1891        for yy in y..y + count {
1892            self.format_line(ctx, yy, line_ptr, self.delta.x, self.state.size.x);
1893            line_ptr = self.next_line(line_ptr);
1894        }
1895    }
1896}
1897
1898// ---------------------------------------------------------------------------
1899// View impl
1900// ---------------------------------------------------------------------------
1901
1902impl View for Editor {
1903    fn state(&self) -> &ViewState {
1904        &self.state
1905    }
1906
1907    fn state_mut(&mut self) -> &mut ViewState {
1908        &mut self.state
1909    }
1910
1911    /// Recompute `draw_ptr` for the current vertical scroll, then render the
1912    /// viewport rows. `draw_ptr`/`draw_line` are display caches, so mutating them
1913    /// during drawing is intentional.
1914    fn draw(&mut self, ctx: &mut DrawCtx) {
1915        // Cache the absolute origin for the mouse-tracking capture, which uses it
1916        // to localize absolute mouse coords (the same `abs_origin` pattern
1917        // buttons use).
1918        self.abs_origin = ctx.origin();
1919        self.screen = ctx.screen_size();
1920        if self.draw_line != self.delta.y {
1921            self.draw_ptr = self.line_move(self.draw_ptr, self.delta.y - self.draw_line);
1922            self.draw_line = self.delta.y;
1923        }
1924        let count = self.state.size.y;
1925        let draw_ptr = self.draw_ptr;
1926        self.draw_lines(ctx, 0, count, draw_ptr);
1927    }
1928
1929    /// Handle keyboard editing, command dispatch, single-click mouse positioning,
1930    /// and scroll-bar change notifications.
1931    fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut Context) {
1932        use crate::command::Command;
1933        use crate::event::Event;
1934
1935        let center_cursor = !self.cursor_visible();
1936
1937        // Extend the selection if a persistent selection is active or shift is held.
1938        let mut select_mode: u8 = 0;
1939        let shift_held = match ev {
1940            Event::KeyDown(k) => k.modifiers.shift,
1941            Event::MouseDown(m) | Event::MouseUp(m) | Event::MouseMove(m) | Event::MouseAuto(m) => {
1942                m.modifiers.shift
1943            }
1944            _ => false,
1945        };
1946        if self.selecting || shift_held {
1947            select_mode = SM_EXTEND;
1948        }
1949
1950        // Resolve the keymap and the Ctrl-K/Ctrl-Q two-key prefix, turning a
1951        // KeyDown into a command in place (or clearing it for a prefix key).
1952        self.convert_event(ev);
1953
1954        match ev {
1955            // -- mouse wheel --------------------------------------------------
1956            // During a hold the capture forwards the wheel under the loop's mask.
1957            // Outside a hold the editor's event mask excludes the wheel, so an
1958            // untracked wheel falls through unconsumed.
1959            Event::MouseWheel(m) => {
1960                let m = *m;
1961                match self.track {
1962                    // The wheel iteration of the drag-select loop: forward the
1963                    // wheel to both scroll bars, then run the unconditional body.
1964                    // The bars are siblings, so the wheel is delivered through the
1965                    // mouse-track deferred effect (resolve the bar, hand it the
1966                    // event). The bar's resulting change notification would be
1967                    // swallowed by the modal capture, so the editor self-posts a
1968                    // delta-sync instead. Both land on the next pump, so this
1969                    // iteration's cursor move still sees the pre-scroll `delta`;
1970                    // the next tick corrects it.
1971                    Some(EditorTrack::Select { select_mode: sm }) => {
1972                        self.lock();
1973                        if let Some(v) = self.v_scroll_bar {
1974                            ctx.request_mouse_track(v, Event::MouseWheel(m));
1975                        }
1976                        if let Some(h) = self.h_scroll_bar {
1977                            ctx.request_mouse_track(h, Event::MouseWheel(m));
1978                        }
1979                        if let Some(id) = self.state.id() {
1980                            ctx.request_scroll_sync(id, self.h_scroll_bar, self.v_scroll_bar);
1981                        }
1982                        // :580-581 — setCurPtr(getMousePtr(where),
1983                        // selectMode); selectMode |= smExtend.
1984                        let ptr = self.get_mouse_ptr(m.position);
1985                        self.set_cur_ptr_core(ptr, sm);
1986                        self.track = Some(EditorTrack::Select {
1987                            select_mode: sm | SM_EXTEND,
1988                        });
1989                        self.unlock(ctx);
1990                    }
1991                    // The pan loop's mask is evMouse (teditor1.cpp:542),
1992                    // which includes evMouseWheel: a wheel tick runs the
1993                    // same scroll-by-mouse-delta body (:543-548).
1994                    Some(EditorTrack::Pan { last, moved }) => {
1995                        self.pan_tick(last, moved, m.position, ctx);
1996                    }
1997                    None => return, // untracked wheel — fall through
1998                }
1999                ev.clear();
2000                return;
2001            }
2002            Event::MouseDown(m) => {
2003                let m = *m;
2004                if m.buttons.right {
2005                    use crate::event::{Key, KeyEvent, KeyModifiers};
2006                    use crate::menu::{Menu, popup_menu};
2007                    let global = m.position + self.abs_origin;
2008                    let menu = Menu::builder()
2009                        .command_key(
2010                            "Cu~t~",
2011                            Command::CUT,
2012                            KeyEvent::new(
2013                                Key::Delete,
2014                                KeyModifiers {
2015                                    shift: true,
2016                                    ..Default::default()
2017                                },
2018                            ),
2019                            "Shift-Del",
2020                        )
2021                        .command_key(
2022                            "~C~opy",
2023                            Command::COPY,
2024                            KeyEvent::new(
2025                                Key::Insert,
2026                                KeyModifiers {
2027                                    ctrl: true,
2028                                    ..Default::default()
2029                                },
2030                            ),
2031                            "Ctrl-Ins",
2032                        )
2033                        .command_key(
2034                            "~P~aste",
2035                            Command::PASTE,
2036                            KeyEvent::new(
2037                                Key::Insert,
2038                                KeyModifiers {
2039                                    shift: true,
2040                                    ..Default::default()
2041                                },
2042                            ),
2043                            "Shift-Ins",
2044                        )
2045                        .command_key(
2046                            "~U~ndo",
2047                            Command::UNDO,
2048                            KeyEvent::new(
2049                                Key::Char('u'),
2050                                KeyModifiers {
2051                                    ctrl: true,
2052                                    ..Default::default()
2053                                },
2054                            ),
2055                            "Ctrl-U",
2056                        )
2057                        .build();
2058                    // `global` is in screen coordinates, so the popup is
2059                    // placed against the screen. Before the first draw the
2060                    // screen size is unknown; the owner's size is the best
2061                    // bound there is.
2062                    let screen = if self.screen.x > 0 && self.screen.y > 0 {
2063                        self.screen
2064                    } else {
2065                        ctx.owner_size()
2066                    };
2067                    popup_menu(global, menu, screen, ctx);
2068                    ev.clear();
2069                    return;
2070                }
2071                if m.buttons.middle {
2072                    // Middle-button pan (teditor1.cpp:540-551): `lastMouse =
2073                    // makeLocal(event.mouse.where); while (mouseEvent(event,
2074                    // evMouse)) { … }` — a WHILE loop, so the press itself runs
2075                    // no body: record `lastMouse` and arm the capture with the
2076                    // evMouse mask (move + auto + wheel). Without an id
2077                    // (uninserted) there is nothing to track — the press is a
2078                    // no-op, like the C++ loop with no further events.
2079                    if let Some(id) = self.state.id() {
2080                        self.track = Some(EditorTrack::Pan {
2081                            last: m.position,
2082                            moved: false,
2083                        });
2084                        ctx.start_mouse_track(
2085                            id,
2086                            self.abs_origin,
2087                            crate::capture::TrackMask {
2088                                mouse_move: true,
2089                                mouse_auto: true,
2090                                wheel: true,
2091                            },
2092                        );
2093                    }
2094                    ev.clear();
2095                    return;
2096                }
2097                if m.flags.double_click {
2098                    select_mode |= SM_DOUBLE;
2099                } else if m.flags.triple_click {
2100                    select_mode |= SM_TRIPLE;
2101                }
2102                // The first iteration of the drag-select do{}while
2103                // (teditor1.cpp:557-583 — the body runs once for the press):
2104                // lock; setCurPtr(getMousePtr(where), selectMode); selectMode
2105                // |= smExtend; unlock. Position is already view-local
2106                // (Group::deliver makeLocal'd it). Then enter the loop: arm the
2107                // capture with the loop mask evMouseMove + evMouseAuto +
2108                // evMouseWheel (:583), carrying the live selectMode in the
2109                // track state (the C++ loop-local survives across iterations).
2110                // Without an id (uninserted) the press stays single-shot.
2111                self.lock();
2112                let ptr = self.get_mouse_ptr(m.position);
2113                self.set_cur_ptr_core(ptr, select_mode);
2114                self.unlock(ctx);
2115                if let Some(id) = self.state.id() {
2116                    self.track = Some(EditorTrack::Select {
2117                        select_mode: select_mode | SM_EXTEND,
2118                    });
2119                    ctx.start_mouse_track(
2120                        id,
2121                        self.abs_origin,
2122                        crate::capture::TrackMask {
2123                            mouse_move: true,
2124                            mouse_auto: true,
2125                            wheel: true,
2126                        },
2127                    );
2128                }
2129            }
2130            // -- evMouseMove (tracked) — a loop-body tick. Guarded by `track`:
2131            // a stray move falls through unconsumed.
2132            Event::MouseMove(m) if self.track.is_some() => {
2133                let m = *m;
2134                match self.track {
2135                    // Drag-select body (teditor1.cpp:558,580-582): lock;
2136                    // setCurPtr(getMousePtr(where), selectMode); selectMode |=
2137                    // smExtend; unlock. (Neither the auto nor the wheel branch
2138                    // applies to a plain move.)
2139                    Some(EditorTrack::Select { select_mode: sm }) => {
2140                        self.lock();
2141                        let ptr = self.get_mouse_ptr(m.position);
2142                        self.set_cur_ptr_core(ptr, sm);
2143                        self.track = Some(EditorTrack::Select {
2144                            select_mode: sm | SM_EXTEND,
2145                        });
2146                        self.unlock(ctx);
2147                    }
2148                    // Pan body (teditor1.cpp:543-548).
2149                    Some(EditorTrack::Pan { last, moved }) => {
2150                        self.pan_tick(last, moved, m.position, ctx)
2151                    }
2152                    None => unreachable!("guarded by track.is_some()"),
2153                }
2154            }
2155            // -- auto-repeat (tracked) — a loop-body tick with the edge-scroll
2156            // prelude. Guarded by `track`.
2157            Event::MouseAuto(m) if self.track.is_some() => {
2158                let m = *m;
2159                match self.track {
2160                    // Drag-select auto body: per-axis out-of-bounds check against
2161                    // the view size, edge-scroll by one, THEN move the cursor.
2162                    // Order matters — the cursor read sees the post-scroll delta.
2163                    Some(EditorTrack::Select { select_mode: sm }) => {
2164                        self.lock();
2165                        let mouse = m.position;
2166                        let mut d = self.delta;
2167                        if mouse.x < 0 {
2168                            d.x -= 1;
2169                        }
2170                        if mouse.x >= self.state.size.x {
2171                            d.x += 1;
2172                        }
2173                        if mouse.y < 0 {
2174                            d.y -= 1;
2175                        }
2176                        if mouse.y >= self.state.size.y {
2177                            d.y += 1;
2178                        }
2179                        self.scroll_to_core(d.x, d.y);
2180                        let ptr = self.get_mouse_ptr(mouse);
2181                        self.set_cur_ptr_core(ptr, sm);
2182                        self.track = Some(EditorTrack::Select {
2183                            select_mode: sm | SM_EXTEND,
2184                        });
2185                        self.unlock(ctx);
2186                    }
2187                    // Pan body (teditor1.cpp:543-548): an auto at the held
2188                    // position has lastMouse == mouse — a no-op scroll,
2189                    // faithful to the C++ evMouse-masked loop.
2190                    Some(EditorTrack::Pan { last, moved }) => {
2191                        self.pan_tick(last, moved, m.position, ctx)
2192                    }
2193                    None => unreachable!("guarded by track.is_some()"),
2194                }
2195            }
2196            // -- evMouseUp (tracked) — both loops simply exit (`mouseEvent`
2197            // returns False on evMouseUp, tview.cpp:642; no post-loop code at
2198            // teditor1.cpp:551/:583-584). Guarded by `track`: MouseUp is not
2199            // mask-gated in Group::wants, so a stray, untracked up must fall
2200            // through unconsumed.
2201            Event::MouseUp(_) if self.track.is_some() => {
2202                match self.track {
2203                    // A middle press that never moved is the X11 paste gesture,
2204                    // not a zero-distance pan.
2205                    Some(EditorTrack::Pan { moved: false, .. }) => {
2206                        if let Some(id) = self.state.id() {
2207                            ctx.request_editor_paste_primary(id);
2208                        }
2209                    }
2210                    // A completed sweep publishes what it swept.
2211                    Some(EditorTrack::Select { .. }) => self.publish_primary(ctx),
2212                    _ => {}
2213                }
2214                self.track = None;
2215            }
2216            Event::KeyDown(k) => {
2217                let k = *k;
2218                // Insertable character? (printable, or tab). Faithful to the C++
2219                // charCode 9 / [32,255) gate, decomposed to our Key model.
2220                let insertable = match k.key {
2221                    crate::event::Key::Char(_) if !k.modifiers.ctrl && !k.modifiers.alt => true,
2222                    // Shift+Tab (kbShiftTab, charCode 0) is NOT insertable — it bubbles
2223                    // to dialog back-tab nav; only plain Tab (kbTab, charCode 9) inserts.
2224                    crate::event::Key::Tab
2225                        if !k.modifiers.shift && !k.modifiers.ctrl && !k.modifiers.alt =>
2226                    {
2227                        true
2228                    }
2229                    _ => false,
2230                };
2231                if insertable {
2232                    self.lock();
2233                    if self.overwrite
2234                        && !self.has_selection()
2235                        && self.cur_ptr != self.line_end(self.cur_ptr)
2236                    {
2237                        self.sel_end = self.next_char(self.cur_ptr);
2238                    }
2239                    let bytes: Vec<u8> = match k.key {
2240                        crate::event::Key::Char(c) => {
2241                            let mut b = [0u8; 4];
2242                            c.encode_utf8(&mut b).as_bytes().to_vec()
2243                        }
2244                        crate::event::Key::Tab => b"\t".to_vec(),
2245                        _ => unreachable!(),
2246                    };
2247                    self.insert_text_core(&bytes, false);
2248                    self.track_cursor_core(center_cursor);
2249                    self.unlock(ctx);
2250                } else {
2251                    return;
2252                }
2253            }
2254            Event::Paste(text) => {
2255                let text = std::mem::take(text);
2256                ev.clear();
2257                self.insert_text(text.as_bytes(), false, ctx);
2258            }
2259            Event::Command(cmd) => {
2260                let cmd = *cmd;
2261                match cmd {
2262                    Command::FIND => {
2263                        if let Some(id) = self.state.id() {
2264                            ctx.open_find_dialog(id);
2265                        }
2266                    }
2267                    Command::REPLACE => {
2268                        if let Some(id) = self.state.id() {
2269                            ctx.open_replace_dialog(id);
2270                        }
2271                    }
2272                    Command::SEARCH_AGAIN => {
2273                        self.do_search_replace(ctx);
2274                        self.flush_if_unlocked(ctx);
2275                    }
2276                    Command::ENCODING => {
2277                        self.toggle_encoding();
2278                        self.flush_if_unlocked(ctx);
2279                    }
2280                    _ => {
2281                        self.lock();
2282                        let handled = self.handle_edit_command(cmd, select_mode, ctx);
2283                        if !handled {
2284                            self.unlock(ctx);
2285                            return;
2286                        }
2287                        self.track_cursor_core(center_cursor);
2288                        self.unlock(ctx);
2289                    }
2290                }
2291            }
2292            Event::Broadcast { command, source }
2293                if *command == Command::SCROLL_BAR_CHANGED
2294                    && source.is_some()
2295                    && (*source == self.h_scroll_bar || *source == self.v_scroll_bar) =>
2296            {
2297                if let Some(id) = self.state.id() {
2298                    ctx.request_scroll_sync(id, self.h_scroll_bar, self.v_scroll_bar);
2299                }
2300                // Do NOT consume the scroll-bar-changed broadcast: by codebase
2301                // convention broadcasts are left live for sibling views (the
2302                // scroller behaves the same way). Functionally inert here, since
2303                // the broadcast only concerns this editor's own bar.
2304                return;
2305            }
2306            _ => return,
2307        }
2308        ev.clear();
2309    }
2310
2311    /// Set or clear a view state flag and react to the change.
2312    ///
2313    /// On `Active`: shows or hides the paired scroll bars and indicator and
2314    /// re-grays the editing commands (Cut/Copy/Paste/Undo etc.). On `Focused`:
2315    /// broadcasts `RECEIVED_FOCUS` or `RELEASED_FOCUS` so other views (such as
2316    /// the indicator) can update. Override `update_commands` rather than this
2317    /// method to customize command gating.
2318    fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
2319        self.state.set_flag(flag, enable);
2320        if flag == StateFlag::Focused {
2321            let source = self.state.id();
2322            ctx.broadcast(
2323                if enable {
2324                    crate::command::Command::RECEIVED_FOCUS
2325                } else {
2326                    crate::command::Command::RELEASED_FOCUS
2327                },
2328                source,
2329            );
2330        }
2331        if flag == StateFlag::Active {
2332            if let Some(h) = self.h_scroll_bar {
2333                ctx.request_set_visible(h, enable);
2334            }
2335            if let Some(v) = self.v_scroll_bar {
2336                ctx.request_set_visible(v, enable);
2337            }
2338            if let Some(i) = self.indicator {
2339                ctx.request_set_visible(i, enable);
2340            }
2341            // Re-gray commands whenever activity changes; flag a redraw so the
2342            // first flush publishes the scroll-bar params/indicator too.
2343            self.update(UF_VIEW);
2344            self.update_commands(ctx);
2345            self.flush_if_unlocked(ctx);
2346        }
2347        // There is no "exposed" flag here; the initial flush instead happens on
2348        // the first active/event boundary.
2349    }
2350
2351    /// Resize and reposition the editor to `bounds`, clamping the scroll offset so
2352    /// the current content stays in view.
2353    ///
2354    /// Called by the parent group when the window is resized. Scroll-bar params are
2355    /// republished on the next flush rather than inline (the same pattern as
2356    /// [`Scroller`](crate::widgets::Scroller)).
2357    fn change_bounds(&mut self, bounds: Rect) {
2358        self.state.set_bounds(bounds);
2359        self.delta.x = 0.max(self.delta.x.min(self.limit.x - self.state.size.x));
2360        self.delta.y = 0.max(self.delta.y.min(self.limit.y - self.state.size.y));
2361        self.update(UF_VIEW);
2362    }
2363
2364    /// Returns `true` when the editor's buffer allocated successfully; `false` if
2365    /// allocation failed (a zero-size fixed buffer).
2366    ///
2367    /// Called by the framework before a close or dialog-accept to decide whether to
2368    /// proceed. The base editor only checks the allocation flag; `FileEditor`
2369    /// overrides this to run the modified-save Yes/No/Cancel prompt instead.
2370    fn valid(&mut self, _cmd: crate::command::Command, _ctx: &mut Context) -> bool {
2371        self.is_valid
2372    }
2373
2374    /// Concrete-reach hatch: the pump downcasts to `&mut Editor` for the
2375    /// `EditorPaste` broker, and for the `FindPick` /
2376    /// `ReplacePick` completion to set search state.
2377    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
2378        Some(self)
2379    }
2380
2381    /// Read both scroll bars' values and apply the delta via [`apply_scroll_delta`].
2382    ///
2383    /// Unlike the scroller/outline, the editor **preserves `None`** — a missing
2384    /// bar skips that axis rather than scrolling to 0. `apply_scroll_delta` is
2385    /// the editor's `TEditor::checkScrollBar` body; `ctx` is live so the editor
2386    /// may queue scrollbar param write-backs for the next pump.
2387    ///
2388    /// [`apply_scroll_delta`]: Editor::apply_scroll_delta
2389    fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, ctx: &mut Context) {
2390        self.apply_scroll_delta(h, v, ctx);
2391    }
2392
2393    /// Cache the user's answer to the "Replace this occurrence?" prompt, routed
2394    /// back from the message box. Consumed by `do_search_replace` on the next
2395    /// search-again dispatch.
2396    fn set_modal_answer(&mut self, cmd: crate::command::Command) {
2397        self.pending_replace_answer = Some(cmd);
2398    }
2399
2400    /// Load a finished Find/Replace dialog's search record (the pump packs the
2401    /// dialog fields, read via [`View::value`], into an ordered
2402    /// [`FieldValue::List`](crate::data::FieldValue::List)). A 2-element
2403    /// `[Text(find), Bits(flags)]` is the Find shape (leaves `replace_str`
2404    /// untouched); a 3-element `[Text(find), Text(replace), Bits(flags)]` is the
2405    /// Replace shape. `flags` is pre-masked by the completion (and already carries
2406    /// or clears `EF_DO_REPLACE`); stored as the low 16 bits. Other shapes are
2407    /// ignored (typed-model drop, like [`set_value`](View::set_value)).
2408    ///
2409    /// **Shape collision:** the match is on record shape only. A view that
2410    /// embeds or delegates to `Editor` and opens its own form via
2411    /// [`Context::request_exec_view`](crate::view::Context::request_exec_view)
2412    /// would, if that form gathers to `[Text, Bits]` (an `InputLine` plus
2413    /// `CheckBoxes`) or `[Text, Text, Bits]`, have it overwrite `find_str`,
2414    /// `replace_str` and the editor flags. Such a wrapper overrides
2415    /// `set_modal_data` itself and forwards to the editor only the Find/Replace
2416    /// records.
2417    fn set_modal_data(&mut self, data: crate::data::FieldValue) {
2418        use crate::data::FieldValue;
2419        if let FieldValue::List(items) = data {
2420            match items.as_slice() {
2421                [FieldValue::Text(find), FieldValue::Bits(flags)] => {
2422                    self.find_str = find.clone();
2423                    self.editor_flags = *flags as u16;
2424                }
2425                [
2426                    FieldValue::Text(find),
2427                    FieldValue::Text(replace),
2428                    FieldValue::Bits(flags),
2429                ] => {
2430                    self.find_str = find.clone();
2431                    self.replace_str = replace.clone();
2432                    self.editor_flags = *flags as u16;
2433                }
2434                _ => {}
2435            }
2436        }
2437    }
2438}
2439
2440impl Editor {
2441    /// Translate a `KeyDown` into a `Command` (or a cleared prefix), routing
2442    /// through the process-global keymap.
2443    fn convert_event(&mut self, ev: &mut crate::event::Event) {
2444        use crate::event::Event;
2445        if let Event::KeyDown(k) = ev {
2446            let stroke = KeyStroke::from_event(*k);
2447            let pending = self.pending.take();
2448            match keymap::resolve_global(pending, stroke) {
2449                Resolve::Prefix => {
2450                    self.pending = Some(stroke);
2451                    ev.clear();
2452                }
2453                Resolve::Command(c) => {
2454                    *ev = Event::Command(c);
2455                }
2456                Resolve::None => {
2457                    // Insertable char or unhandled — leave the event unchanged.
2458                }
2459            }
2460        }
2461    }
2462
2463    /// Dispatch an editing command. Returns false for an unhandled command, so
2464    /// the caller can fall through.
2465    fn handle_edit_command(
2466        &mut self,
2467        cmd: crate::command::Command,
2468        select_mode: u8,
2469        ctx: &mut Context,
2470    ) -> bool {
2471        use crate::command::Command;
2472        match cmd {
2473            Command::CUT => self.clip_cut(ctx),
2474            Command::COPY => {
2475                self.clip_copy(ctx);
2476            }
2477            Command::PASTE => self.clip_paste(ctx),
2478            Command::UNDO => self.undo(),
2479            Command::CLEAR => self.delete_select(),
2480            Command::CHAR_LEFT => self.set_cur_ptr_core(self.prev_char(self.cur_ptr), select_mode),
2481            Command::CHAR_RIGHT => self.set_cur_ptr_core(self.next_char(self.cur_ptr), select_mode),
2482            Command::WORD_LEFT => self.set_cur_ptr_core(self.prev_word(self.cur_ptr), select_mode),
2483            Command::WORD_RIGHT => self.set_cur_ptr_core(self.next_word(self.cur_ptr), select_mode),
2484            Command::LINE_START => {
2485                let p = if self.auto_indent {
2486                    self.indented_line_start(self.cur_ptr)
2487                } else {
2488                    self.line_start(self.cur_ptr)
2489                };
2490                self.set_cur_ptr_core(p, select_mode);
2491            }
2492            Command::LINE_END => self.set_cur_ptr_core(self.line_end(self.cur_ptr), select_mode),
2493            Command::LINE_UP => {
2494                self.set_cur_ptr_core(self.line_move(self.cur_ptr, -1), select_mode)
2495            }
2496            Command::LINE_DOWN => {
2497                self.set_cur_ptr_core(self.line_move(self.cur_ptr, 1), select_mode)
2498            }
2499            Command::PAGE_UP => self.set_cur_ptr_core(
2500                self.line_move(self.cur_ptr, -(self.state.size.y - 1)),
2501                select_mode,
2502            ),
2503            Command::PAGE_DOWN => self.set_cur_ptr_core(
2504                self.line_move(self.cur_ptr, self.state.size.y - 1),
2505                select_mode,
2506            ),
2507            Command::TEXT_START => self.set_cur_ptr_core(0, select_mode),
2508            Command::TEXT_END => self.set_cur_ptr_core(self.buf_len, select_mode),
2509            Command::NEW_LINE => self.new_line(),
2510            Command::BACK_SPACE => {
2511                self.delete_range(self.prev_char(self.cur_ptr), self.cur_ptr, true)
2512            }
2513            Command::DEL_CHAR => {
2514                self.delete_range(self.cur_ptr, self.next_char(self.cur_ptr), true)
2515            }
2516            Command::DEL_WORD => {
2517                self.delete_range(self.cur_ptr, self.next_word(self.cur_ptr), false)
2518            }
2519            Command::DEL_WORD_LEFT => {
2520                self.delete_range(self.prev_word(self.cur_ptr), self.cur_ptr, false)
2521            }
2522            Command::DEL_START => {
2523                self.delete_range(self.line_start(self.cur_ptr), self.cur_ptr, false)
2524            }
2525            Command::DEL_END => self.delete_range(self.cur_ptr, self.line_end(self.cur_ptr), false),
2526            Command::DEL_LINE => self.delete_range(
2527                self.line_start(self.cur_ptr),
2528                self.next_line(self.cur_ptr),
2529                false,
2530            ),
2531            Command::INS_MODE => self.toggle_ins_mode(),
2532            Command::START_SELECT => self.start_select(),
2533            Command::HIDE_SELECT => self.hide_select(),
2534            Command::INDENT_MODE => self.auto_indent = !self.auto_indent,
2535            Command::SELECT_ALL => {
2536                self.set_cur_ptr_core(0, select_mode);
2537                self.set_cur_ptr_core(self.buf_len, select_mode | SM_EXTEND);
2538            }
2539            _ => return false,
2540        }
2541        true
2542    }
2543}
2544
2545// ---------------------------------------------------------------------------
2546// Memo — a thin embed-delegate wrapper over Editor.
2547// ---------------------------------------------------------------------------
2548
2549/// A single-field multi-line editor for use inside a dialog. An
2550/// embed-and-delegate wrapper over [`Editor`]; the only behavioural differences
2551/// from the base editor are: it swallows a plain `Tab` keypress (so Tab navigates
2552/// the dialog rather than inserting), and it exposes its text as a typed
2553/// [`FieldValue`](crate::data::FieldValue) for dialog gather/scatter.
2554///
2555/// A memo reuses the editor's drawing and so its scroller colors; it carries no
2556/// separate palette of its own.
2557///
2558/// # Turbo Vision heritage
2559///
2560/// Ports `TMemo` (`tmemo.cpp`). Data exchange becomes the typed value protocol
2561/// (deviation D10) and the palette is folded into the editor's colors.
2562pub struct Memo {
2563    /// The shared editor engine (buffer, nav, edit, undo, draw, brokers).
2564    pub editor: Editor,
2565}
2566
2567impl Memo {
2568    /// Create a fixed-size multi-line text field for use inside a dialog.
2569    ///
2570    /// `buf_size` is the maximum number of bytes the memo can hold; size it to the
2571    /// largest text you expect (the buffer does not grow). Pass the [`ViewId`]s of
2572    /// the sibling scroll bars and an optional frame indicator; `None` is fine when
2573    /// those controls are absent.
2574    ///
2575    /// Embed the returned `Memo` into your dialog group with
2576    /// [`Group::insert`](crate::view::Group::insert), then wire it to
2577    /// any [`Label`](crate::widgets::Label) via [`View::set_value`] /
2578    /// [`View::value`] during scatter/gather.
2579    pub fn new(
2580        bounds: Rect,
2581        h_scroll_bar: Option<ViewId>,
2582        v_scroll_bar: Option<ViewId>,
2583        indicator: Option<ViewId>,
2584        buf_size: usize,
2585    ) -> Self {
2586        Memo {
2587            editor: Editor::new(bounds, h_scroll_bar, v_scroll_bar, indicator, buf_size),
2588        }
2589    }
2590}
2591
2592#[crate::delegate(to = editor)]
2593impl View for Memo {
2594    /// Swallow a plain `Tab` KeyDown (so it bubbles to the dialog's focus
2595    /// navigation) and forward everything else to the editor.
2596    fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut Context) {
2597        use crate::event::{Event, Key};
2598        // Shift/Ctrl/Alt+Tab ARE forwarded; only the unmodified Tab is swallowed.
2599        if let Event::KeyDown(k) = ev
2600            && k.key == Key::Tab
2601            && !k.modifiers.shift
2602            && !k.modifiers.ctrl
2603            && !k.modifiers.alt
2604        {
2605            // Swallow WITHOUT clearing — let it propagate to dialog focus-nav.
2606            return;
2607        }
2608        self.editor.handle_event(ev, ctx);
2609    }
2610
2611    /// Return the memo's entire text as a [`FieldValue::Text`](crate::data::FieldValue).
2612    ///
2613    /// Called automatically by the owning dialog's scatter pass — prefer
2614    /// [`Dialog::gather`](crate::dialog::Dialog) over calling this directly.
2615    fn value(&self) -> Option<crate::data::FieldValue> {
2616        Some(crate::data::FieldValue::Text(
2617            String::from_utf8_lossy(&self.editor.text()).into_owned(),
2618        ))
2619    }
2620
2621    /// Replace the memo's text with the contents of a [`FieldValue::Text`](crate::data::FieldValue).
2622    ///
2623    /// Non-`Text` variants are silently ignored (a type mismatch the typed value
2624    /// protocol drops for all controls). Called automatically by the owning
2625    /// dialog's gather pass — prefer
2626    /// [`Dialog::scatter`](crate::dialog::Dialog) over calling this directly.
2627    fn set_value(&mut self, v: crate::data::FieldValue) {
2628        if let crate::data::FieldValue::Text(s) = v {
2629            self.editor.set_text(s.as_bytes());
2630        }
2631    }
2632}
2633
2634// ---------------------------------------------------------------------------
2635// FileEditor — a file-editor-mode Editor.
2636// ---------------------------------------------------------------------------
2637
2638/// An [`Editor`] backed by a file on disk. An embed-and-delegate wrapper; the
2639/// editor runs in file-editor mode (growable buffer plus save commands).
2640///
2641/// It loads and saves over real `std::fs`, grows the buffer to fit a file, and
2642/// handles the save commands. Validation runs the full modified-save
2643/// Yes/No/Cancel prompt and a write-error popup, both through the
2644/// async-modal-from-a-view mechanism: `valid` requests a message box, caches the
2645/// answer in [`set_modal_answer`](View::set_modal_answer), then re-validates.
2646///
2647/// Save-as (an explicit Save-As command, or saving an untitled buffer) opens a
2648/// file dialog through [`Context::request_save_as_dialog`]: the loop builds and
2649/// runs the dialog, the completion sets `file_name` plus `pending_title_update`
2650/// and re-injects a Save command, which writes the file and broadcasts a
2651/// title-update (refreshing the hosting [`EditWindow`]'s frame title).
2652///
2653/// A read error is reported through a message box on the first event (the
2654/// constructor has no [`Context`], so the error is cached at load time).
2655/// Optional backup files (off by default) append `~` to the filename
2656/// (`foo.txt` → `foo.txt~`), following the Unix convention.
2657///
2658/// A couple of details collapse on a modern host: `std::fs::write` does not
2659/// distinguish create-vs-write failure, so both report one "Error writing file …"
2660/// box, and buffer growth is infallible, so there is no out-of-memory path.
2661///
2662/// # Turbo Vision heritage
2663///
2664/// Ports `TFileEditor` (`tfiledtr.cpp`). Data exchange uses the typed value
2665/// protocol (deviation D10); serialization is dropped.
2666pub struct FileEditor {
2667    /// The editor engine, in file-editor mode.
2668    pub editor: Editor,
2669    /// The backing file path, or `None` for an untitled (unsaved) buffer.
2670    ///
2671    /// Set at construction time if a path was provided, then updated by the
2672    /// save-as dialog completion. Read this to determine the current title or
2673    /// whether a buffer has ever been saved. Do not mutate it directly; let
2674    /// `save` / the save-as dialog completion update it.
2675    pub file_name: Option<std::path::PathBuf>,
2676    /// The user's answer to the modified-save prompt, cached by
2677    /// [`View::set_modal_answer`] between the `valid()` that requested the box and
2678    /// the re-validate that consumes it (the async-modal-from-a-view round-trip).
2679    /// `None` until an answer is routed back; consumed (taken) on the next `valid`.
2680    pending_save_answer: Option<crate::command::Command>,
2681    /// Set by the save-as dialog completion (after the user picks a filename) so
2682    /// the next successful save broadcasts a title-update to refresh the hosting
2683    /// [`EditWindow`]'s frame title. The broadcast is deferred to the re-injected
2684    /// save so it fires from a full [`Context`].
2685    pub pending_title_update: bool,
2686    /// Error message from `load_file` to display on the first `handle_event` call.
2687    /// Set when a real I/O error (not NotFound) occurs during `load_file`, which is
2688    /// called from the constructor and has no [`Context`]. Shown via
2689    /// `request_message_box` on the first `handle_event` (the established pattern
2690    /// for work deferred out of a constructor).
2691    pending_load_error: Option<String>,
2692}
2693
2694impl FileEditor {
2695    /// Create a file-backed editor wired to the given scroll bars and frame indicator.
2696    ///
2697    /// Pass a `file_name` to open an existing file: the path is expanded to
2698    /// absolute and the file is read immediately. `None` starts an untitled buffer
2699    /// you can save later via [`FileEditor::save`]. A missing file is treated as an
2700    /// empty buffer (not an error); a real I/O error is reported the first time
2701    /// `handle_event` runs (the constructor has no [`Context`] for modal dialogs).
2702    ///
2703    /// This constructor is called by [`EditWindow::new`] — prefer that for the
2704    /// typical "open a file in a window" use case.
2705    pub fn new(
2706        bounds: Rect,
2707        h_scroll_bar: Option<ViewId>,
2708        v_scroll_bar: Option<ViewId>,
2709        indicator: Option<ViewId>,
2710        file_name: Option<std::path::PathBuf>,
2711    ) -> Self {
2712        let mut fe = FileEditor {
2713            editor: Editor::new_file_editor(bounds, h_scroll_bar, v_scroll_bar, indicator),
2714            file_name: None,
2715            pending_save_answer: None,
2716            pending_title_update: false,
2717            pending_load_error: None,
2718        };
2719        if let Some(path) = file_name {
2720            // Make the path absolute relative to the CWD, resolving . and .., but
2721            // do NOT require it to exist. std::path::absolute matches this
2722            // contract (stable since Rust 1.79); fall back to the original path if
2723            // the CWD cannot be determined (the only failure mode).
2724            let path = std::path::absolute(&path).unwrap_or(path);
2725            fe.file_name = Some(path);
2726            if fe.editor.is_valid {
2727                fe.editor.is_valid = fe.load_file();
2728            }
2729        }
2730        fe
2731    }
2732
2733    /// Read `file_name` into the buffer, growing it to fit.
2734    ///
2735    /// A missing or unopenable file is treated as an empty buffer (returns `true`,
2736    /// matching the C++ behavior). A real read error stores a message in
2737    /// `pending_load_error` and returns `false`; the message is shown via a modal
2738    /// dialog on the first `handle_event` call (the constructor has no `Context`).
2739    ///
2740    /// Call this after changing `file_name` to reload from the new path. The buffer
2741    /// is grown infallibly to fit the file — there is no out-of-memory failure path.
2742    pub fn load_file(&mut self) -> bool {
2743        let Some(path) = self.file_name.clone() else {
2744            self.editor.set_buf_len(0);
2745            return true;
2746        };
2747        match std::fs::read(&path) {
2748            Ok(bytes) => {
2749                // set_text grows the buffer to fit and places the bytes at the end.
2750                self.editor.set_text(&bytes);
2751                true
2752            }
2753            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2754                self.editor.set_buf_len(0); // can't open ⇒ empty, valid (C++ True)
2755                true
2756            }
2757            Err(e) => {
2758                // Store the read error for display on first handle_event (the
2759                // constructor has no ctx). OS detail is omitted because the dialog
2760                // sizer doesn't handle embedded newlines.
2761                let _ = e;
2762                let msg = format!("Error reading file {}.", path.display());
2763                self.pending_load_error = Some(msg);
2764                false
2765            }
2766        }
2767    }
2768
2769    /// Write the buffer's logical text to `file_name` and clear the dirty flag.
2770    ///
2771    /// Returns `false` and pops an error dialog on failure. If the
2772    /// `EF_BACKUP_FILES` flag is set in the editor's `editor_flags`, the existing
2773    /// file is renamed to `<name>~` before writing.
2774    ///
2775    /// Call [`save`](FileEditor::save) rather than this directly — `save` handles
2776    /// the untitled case by opening a save-as dialog first.
2777    pub fn save_file(&mut self, ctx: &mut Context) -> bool {
2778        let Some(path) = self.file_name.clone() else {
2779            return false;
2780        };
2781        // Backup-files option: rename the existing file to <name>~ before writing
2782        // the new content, appending "~" to the full filename (Unix convention).
2783        // No filename component: silently skip.
2784        if (self.editor.editor_flags() & EF_BACKUP_FILES) != 0
2785            && let Some(name) = path.file_name()
2786        {
2787            let mut bname = name.to_os_string();
2788            bname.push("~");
2789            let backup = path.with_file_name(bname);
2790            let _ = std::fs::remove_file(&backup); // Windows: rename fails if dest exists
2791            let _ = std::fs::rename(&path, &backup); // ignore — original may not exist (first save)
2792        }
2793        // The logical text skips the gap; the editor's text() helper does that.
2794        let bytes = self.editor.text();
2795        match std::fs::write(&path, &bytes) {
2796            Ok(()) => {
2797                self.editor.clear_modified();
2798                true
2799            }
2800            Err(_) => {
2801                // A failed write reports one "Error writing file …" box. `std::fs::write`
2802                // opens and writes atomically, so a create failure and a write failure
2803                // cannot be distinguished here.
2804                let msg = format!("Error writing file {}.", path.display());
2805                ctx.request_message_box(
2806                    msg,
2807                    crate::dialog::MessageBoxKind::Error,
2808                    crate::dialog::MessageBoxButtons::ok(),
2809                    None,
2810                    None,
2811                );
2812                false
2813            }
2814        }
2815    }
2816
2817    /// Save the buffer to disk, opening a file-picker dialog if the buffer is untitled.
2818    ///
2819    /// If `file_name` is set, delegates immediately to [`save_file`](FileEditor::save_file).
2820    /// If the buffer is untitled, requests an async save-as dialog (a leaf view cannot
2821    /// run a blocking dialog inline): the dialog runs on the next event-loop pump,
2822    /// sets `file_name`, and re-injects a `Save` command that triggers a second call
2823    /// to `save`, this time with `file_name` set.
2824    ///
2825    /// Returns `false` when the save is deferred (untitled path) or when writing
2826    /// fails; `true` on a successful write. Normally invoked via the `Save` command
2827    /// in `handle_event` — callers rarely need to call this directly.
2828    pub fn save(&mut self, ctx: &mut Context) -> bool {
2829        if self.file_name.is_some() {
2830            self.save_file(ctx)
2831        } else {
2832            if let Some(id) = View::state(self).id() {
2833                ctx.request_save_as_dialog(id);
2834            }
2835            false
2836        }
2837    }
2838}
2839
2840#[crate::delegate(to = editor)]
2841impl View for FileEditor {
2842    /// Concrete-reach hatch: the pump's save-as brokers and
2843    /// `EditWindow::handle_event` downcast a group child back to `&mut FileEditor`
2844    /// to set `file_name` / read `pending_title_update`. WITHOUT this override the
2845    /// `#[delegate(to = editor)]` macro would forward `as_any_mut` to the inner
2846    /// [`Editor`], so the downcast would silently miss (returning the inner
2847    /// editor's `Any`).
2848    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
2849        Some(self)
2850    }
2851
2852    /// Handle events for the file editor: delegates to the inner [`Editor`], then
2853    /// processes `Save` and `Save-As` commands and deferred load errors.
2854    ///
2855    /// **Load-error popup:** if `load_file` stored an error at construction time it
2856    /// is popped as a modal dialog on the first event (the constructor has no
2857    /// [`Context`] for dialogs).
2858    ///
2859    /// **Save-As:** opens a file-picker dialog asynchronously; the completion sets
2860    /// `file_name`, sets `pending_title_update`, and re-injects a `Save` command.
2861    ///
2862    /// **Save:** calls [`save`](FileEditor::save), flushes the update flags, and —
2863    /// when `pending_title_update` is set — broadcasts `cmUpdateTitle` to refresh
2864    /// every open [`EditWindow`]'s frame title.
2865    fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut Context) {
2866        use crate::command::Command;
2867        use crate::event::Event;
2868        if let Some(msg) = self.pending_load_error.take() {
2869            ctx.request_message_box(
2870                msg,
2871                crate::dialog::MessageBoxKind::Error,
2872                crate::dialog::MessageBoxButtons::ok(),
2873                None,
2874                None,
2875            );
2876        }
2877        self.editor.handle_event(ev, ctx);
2878        // Save-As: always open the file dialog to pick a (possibly new) name,
2879        // regardless of whether the buffer is titled. The completion sets the
2880        // picked name and re-injects a Save.
2881        if let Event::Command(cmd) = ev
2882            && *cmd == Command::SAVE_AS
2883        {
2884            if let Some(id) = View::state(self).id() {
2885                ctx.request_save_as_dialog(id);
2886            }
2887            ev.clear();
2888            return; // do NOT fall through to the cmSave arm below.
2889        }
2890        if let Event::Command(cmd) = ev
2891            && *cmd == Command::SAVE
2892        {
2893            let ok = self.save(ctx);
2894            // Publish modified=false to the indicator and re-gray the save commands
2895            // now (the inner editor already flushed with modified still true, since
2896            // a Save is not itself an edit).
2897            self.editor.flush_if_unlocked(ctx);
2898            // After a successful save-as (the completion set the flag and re-injected
2899            // this Save), broadcast a title-update so the hosting EditWindow
2900            // refreshes its frame title.
2901            if ok && self.pending_title_update {
2902                self.pending_title_update = false;
2903                ctx.broadcast(Command::UPDATE_TITLE, View::state(self).id());
2904            }
2905            ev.clear();
2906        }
2907    }
2908
2909    /// Validity check. For the plain validity command this reflects buffer
2910    /// validity; for any other command, a **modified** buffer first prompts a
2911    /// Yes/No/Cancel save dialog, and the answer decides the result: Yes → save,
2912    /// No → clear the dirty flag and allow, Cancel → veto.
2913    ///
2914    /// The prompt is asynchronous: the first call requests the box
2915    /// ([`Context::request_message_box`], routing the answer back to this view and
2916    /// re-posting the close command) and returns `false` (veto for now). When the
2917    /// user picks, the pump routes the answer back through
2918    /// [`View::set_modal_answer`] (caching it in `pending_save_answer`) and
2919    /// re-posts the close, which re-runs this check; this time the cached choice is
2920    /// applied.
2921    fn valid(&mut self, cmd: crate::command::Command, ctx: &mut Context) -> bool {
2922        use crate::command::Command;
2923        if cmd == Command::VALID {
2924            return self.editor.valid(cmd, ctx);
2925        }
2926        // Re-validate pass: consume the cached answer from the async box.
2927        if let Some(answer) = self.pending_save_answer.take() {
2928            return match answer {
2929                Command::YES => self.save(ctx),
2930                Command::NO => {
2931                    self.editor.clear_modified();
2932                    true
2933                }
2934                // Cancel (or anything else, e.g. an OK-only box) → veto the close.
2935                _ => false,
2936            };
2937        }
2938        // First pass: a modified buffer needs the save prompt.
2939        if self.editor.modified() {
2940            // self id = self.state().id() (the state delegates to the inner editor,
2941            // so this is the id the owning group stored for the FileEditor box). The
2942            // close path always runs against an inserted tree; if somehow absent,
2943            // fall back to allow-close (cannot route an answer with no id).
2944            let Some(my_id) = View::state(self).id() else {
2945                return true;
2946            };
2947            // edSaveUntitled / edSaveModify (msgbox uses Information per editorDialog).
2948            let msg = match &self.file_name {
2949                None => "Save untitled file?".to_string(),
2950                Some(p) => format!("{} has been modified. Save?", p.display()),
2951            };
2952            ctx.request_message_box(
2953                msg,
2954                crate::dialog::MessageBoxKind::Information,
2955                crate::dialog::MessageBoxButtons::yes_no_cancel(),
2956                Some(my_id),
2957                Some(Command::CLOSE),
2958            );
2959            return false; // veto until the answer comes back and re-validates.
2960        }
2961        true
2962    }
2963
2964    /// Cache the user's Yes/No/Cancel choice from the modified-save box for the
2965    /// re-validate pass (the async-modal-from-a-view round-trip).
2966    fn set_modal_answer(&mut self, cmd: crate::command::Command) {
2967        self.pending_save_answer = Some(cmd);
2968    }
2969}
2970
2971/// Reach the inner [`Editor`] engine of a group child that may be a plain
2972/// [`Editor`], a [`Memo`], or a [`FileEditor`].
2973///
2974/// `FileEditor::as_any_mut` returns the `FileEditor` itself (so the save-as
2975/// brokers can downcast to it), NOT the inner `Editor`. The `EditorPaste` broker
2976/// targets the inserted view's id — which, in an `EditWindow`, IS a `FileEditor` —
2977/// yet it needs the inner `Editor`. This helper bridges that: it tries the
2978/// `FileEditor` downcast first (peeling to its `.editor`), and otherwise falls back
2979/// to a direct `Editor` downcast (covering a plain `Editor` and a `Memo`, both of
2980/// whose `as_any_mut` forward to the inner `Editor`). The `is::<>()`-first form
2981/// avoids the NLL conditional-borrow error.
2982pub(crate) fn editor_mut(v: &mut dyn View) -> Option<&mut Editor> {
2983    let any = v.as_any_mut()?;
2984    if any.is::<FileEditor>() {
2985        return any.downcast_mut::<FileEditor>().map(|fe| &mut fe.editor);
2986    }
2987    any.downcast_mut::<Editor>()
2988}
2989
2990// ---------------------------------------------------------------------------
2991// EditWindow
2992// ---------------------------------------------------------------------------
2993
2994/// The `EditWindow` interactive-resize floor: frame + indicator + scroll bars
2995/// + a few text columns. Ports `minEditWinSize` (`teditwnd.cpp:29`).
2996pub(crate) const MIN_EDIT_WIN_SIZE: Point = Point::new(24, 6);
2997
2998/// A [`Window`](crate::window::Window) hosting a [`FileEditor`] with two scroll bars and an
2999/// [`Indicator`]. An embed-and-delegate wrapper over [`Window`](crate::window::Window); the constructor
3000/// wires the editor to the (initially hidden) scroll bars and indicator by id.
3001///
3002/// The 24×6 minimum (`minEditWinSize`, `MIN_EDIT_WIN_SIZE`) is pushed into the
3003/// embedded window via `set_min_size` at construction (D16), so every clamp
3004/// path — including the interactive corner drag — honors it through the
3005/// delegated `size_limits`.
3006///
3007/// When a close is requested while this window hosts the internal clipboard
3008/// editor, the window hides instead of closing. The clipboard editor is never
3009/// hosted in an `EditWindow` in practice, so closing is normally the plain window
3010/// close.
3011///
3012/// # Turbo Vision heritage
3013///
3014/// Ports `TEditWindow` (`teditwnd.cpp`).
3015pub struct EditWindow {
3016    /// The embedded window (frame + children).
3017    pub window: crate::window::Window,
3018    /// The id of the hosted [`FileEditor`] child.
3019    ///
3020    /// Use `window.child_mut(editor_id)` to reach the child, then downcast with
3021    /// `as_any_mut()` to `&mut FileEditor` when you need to inspect `file_name`
3022    /// or call file-editor methods directly. Read-only — do not reassign.
3023    pub editor_id: ViewId,
3024    /// The (initially hidden) horizontal scroll bar.
3025    pub h_scroll_bar_id: ViewId,
3026    /// The (initially hidden) vertical scroll bar.
3027    pub v_scroll_bar_id: ViewId,
3028    /// The (initially hidden) indicator.
3029    pub indicator_id: ViewId,
3030}
3031
3032impl EditWindow {
3033    /// Create an edit window that opens `file_name` (or an untitled buffer) inside
3034    /// a tiled, numbered window.
3035    ///
3036    /// `bounds` is the window rectangle in its parent's coordinate space; `number`
3037    /// is the window number shown in the frame title (use `0` for none). The window
3038    /// is tileable (`ofTileable` set) so the desktop can arrange it alongside others.
3039    ///
3040    /// The constructor inserts hidden scroll bars and an indicator first (to
3041    /// capture their [`ViewId`]s), then wires them to a new [`FileEditor`] which is
3042    /// inserted last. The `file_name` path is expanded to absolute and loaded
3043    /// immediately; a missing file starts empty rather than failing.
3044    ///
3045    /// After construction, insert the `EditWindow` into the application desktop
3046    /// with [`Group::insert`](crate::view::Group::insert).
3047    pub fn new(bounds: Rect, file_name: Option<std::path::PathBuf>, number: i16) -> Self {
3048        // Title: filename or "Untitled".
3049        let title = match &file_name {
3050            Some(p) => p.to_string_lossy().into_owned(),
3051            None => "Untitled".to_string(),
3052        };
3053        let mut window = crate::window::Window::new(bounds, Some(title), number);
3054
3055        // The TEditWindow::sizeLimits floor, pushed down into the window
3056        // (D16): every clamp path incl. the interactive drag reads it.
3057        window.set_min_size(MIN_EDIT_WIN_SIZE);
3058
3059        // Edit windows participate in tiling.
3060        View::state_mut(&mut window).options.tileable = true;
3061
3062        let size = View::state(&window).size;
3063
3064        // Horizontal scrollbar — hidden, row-bottom, columns 18..size.x-2.
3065        let mut h = ScrollBar::new(Rect::new(18, size.y - 1, size.x - 2, size.y));
3066        h.state.hide();
3067        let h_scroll_bar_id = window.insert_child(Box::new(h));
3068
3069        // Vertical scrollbar — hidden, right column, rows 1..size.y-1.
3070        let mut v = ScrollBar::new(Rect::new(size.x - 1, 1, size.x, size.y - 1));
3071        v.state.hide();
3072        let v_scroll_bar_id = window.insert_child(Box::new(v));
3073
3074        // Indicator — hidden, row-bottom, columns 2..16.
3075        let mut ind = Indicator::new(Rect::new(2, size.y - 1, 16, size.y));
3076        ind.state.hide();
3077        let indicator_id = window.insert_child(Box::new(ind));
3078
3079        // FileEditor over the inner extent, wired to the three ids.
3080        let mut r = View::state(&window).get_extent();
3081        r.grow(-1, -1);
3082        let editor = FileEditor::new(
3083            r,
3084            Some(h_scroll_bar_id),
3085            Some(v_scroll_bar_id),
3086            Some(indicator_id),
3087            file_name,
3088        );
3089        let editor_id = window.insert_child(Box::new(editor));
3090
3091        EditWindow {
3092            window,
3093            editor_id,
3094            h_scroll_bar_id,
3095            v_scroll_bar_id,
3096            indicator_id,
3097        }
3098    }
3099}
3100
3101#[crate::delegate(
3102    to = window,
3103    skip(
3104        apply_scroll_sync,
3105        as_any_mut,
3106        calc_bounds,
3107        grabs_focus_on_click,
3108        select_window_num,
3109        set_value,
3110        value
3111    )
3112)]
3113impl View for EditWindow {
3114    /// Handle events for this window: delegates to the inner [`Window`](crate::window::Window),
3115    /// then handles two extras — hiding instead of closing when hosting the
3116    /// clipboard editor, and refreshing the frame title on a `cmUpdateTitle` broadcast.
3117    ///
3118    /// **Title refresh:** after a save-as the hosted [`FileEditor`] broadcasts
3119    /// `cmUpdateTitle`; this handler reads the new `file_name`, pushes it as the
3120    /// window title, and leaves the broadcast live so every other open edit window
3121    /// can refresh its own title independently.
3122    ///
3123    /// **Clipboard-editor close guard:** if the hosted `FileEditor` is the internal
3124    /// clipboard editor, a `Close` command hides the window instead of destroying
3125    /// it (the clipboard must persist for the lifetime of the application).
3126    ///
3127    /// # Turbo Vision heritage
3128    ///
3129    /// In C++ `TEditWindow::handleEvent` consumed the `cmUpdateTitle` broadcast and
3130    /// called `frame->drawView()` (pull-title). Rust leaves it live and pushes the
3131    /// new title string into `Window` (push-title), so all windows can act on it
3132    /// without a fixed consumption order.
3133    fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut crate::view::Context) {
3134        use crate::command::Command;
3135        use crate::event::Event;
3136        // Hide instead of close when this window hosts the clipboard editor.
3137        if let Event::Command(ref cmd) = *ev
3138            && *cmd == Command::CLOSE
3139            && ctx.clipboard_editor_id() == Some(self.editor_id)
3140            && let Some(id) = crate::view::View::state(self).id()
3141        {
3142            ctx.request_set_visible(id, false);
3143            ev.clear();
3144            return;
3145        }
3146        self.window.handle_event(ev, ctx);
3147        if let Event::Broadcast { command, .. } = ev
3148            && *command == Command::UPDATE_TITLE
3149        {
3150            let title = self
3151                .window
3152                .child_mut(self.editor_id)
3153                .and_then(|v| v.as_any_mut())
3154                .and_then(|a| a.downcast_mut::<FileEditor>())
3155                .map(|fe| match &fe.file_name {
3156                    Some(p) => p.to_string_lossy().into_owned(),
3157                    None => "Untitled".to_string(),
3158                });
3159            if let Some(t) = title {
3160                self.window.set_title(Some(t));
3161            }
3162        }
3163    }
3164}
3165
3166// ---------------------------------------------------------------------------
3167// Tests — the real oracle is logical buffer state (not just snapshots).
3168// ---------------------------------------------------------------------------
3169#[cfg(test)]
3170mod tests {
3171    use super::*;
3172    use crate::command::Command;
3173    use crate::event::Event;
3174    use crate::view::{Deferred, Group};
3175    use std::collections::VecDeque;
3176
3177    /// Build an editor with an LF default line ending (the host default) and a
3178    /// generous buffer.
3179    fn ed() -> Editor {
3180        Editor::new(Rect::new(0, 0, 40, 10), None, None, None, 1024)
3181    }
3182
3183    /// A throwaway Context for driving the ctx-taking methods in tests.
3184    struct Cx {
3185        out: VecDeque<Event>,
3186        timers: crate::timer::TimerQueue,
3187        deferred: Vec<Deferred>,
3188    }
3189    impl Cx {
3190        fn new() -> Self {
3191            Cx {
3192                out: VecDeque::new(),
3193                timers: crate::timer::TimerQueue::new(),
3194                deferred: vec![],
3195            }
3196        }
3197        fn ctx(&mut self) -> Context<'_> {
3198            Context::new(&mut self.out, &mut self.timers, 0, &mut self.deferred)
3199        }
3200    }
3201
3202    /// Insert `s` at the cursor via the ctx-free core (the common test verb).
3203    fn insert(e: &mut Editor, s: &str) {
3204        e.insert_text_core(s.as_bytes(), false);
3205    }
3206
3207    /// The buffer invariant that must hold after every op.
3208    fn check_invariant(e: &Editor) {
3209        assert_eq!(
3210            e.buf_len + e.gap_len,
3211            e.buf_size,
3212            "buf_len + gap_len == buf_size"
3213        );
3214    }
3215
3216    fn text(e: &Editor) -> String {
3217        String::from_utf8(e.text()).unwrap()
3218    }
3219
3220    // -- ctor ----------------------------------------------------------------
3221
3222    #[test]
3223    fn ctor_defaults() {
3224        let e = ed();
3225        assert!(e.state.options.selectable);
3226        assert!(e.state.grow_mode.hi_x && e.state.grow_mode.hi_y);
3227        assert!(e.state.state.cursor_vis, "showCursor sets cursor_vis");
3228        assert_eq!(e.buf_len, 0);
3229        assert_eq!(e.gap_len, e.buf_size);
3230        assert_eq!(e.limit, Point::new(MAX_LINE_LENGTH, 1));
3231        assert!(e.is_valid);
3232        check_invariant(&e);
3233    }
3234
3235    // -- (a) insert spanning the gap -----------------------------------------
3236
3237    #[test]
3238    fn insert_basic_and_across_gap() {
3239        let mut e = ed();
3240        insert(&mut e, "hello");
3241        assert_eq!(text(&e), "hello");
3242        assert_eq!(e.cur_ptr, 5);
3243        assert_eq!(e.buf_len, 5);
3244        check_invariant(&e);
3245
3246        // Move cursor to start, then insert — exercises the gap memmove on the
3247        // physical buffer (text after the gap).
3248        e.set_cur_ptr_core(0, 0);
3249        assert_eq!(e.cur_ptr, 0);
3250        insert(&mut e, "XY");
3251        assert_eq!(text(&e), "XYhello");
3252        assert_eq!(e.cur_ptr, 2);
3253        check_invariant(&e);
3254    }
3255
3256    // -- (b) insert, move left (setSelect gap move), insert again ------------
3257
3258    #[test]
3259    fn insert_move_left_insert_again() {
3260        let mut e = ed();
3261        insert(&mut e, "abcdef");
3262        e.set_cur_ptr_core(3, 0); // gap moves to between 'c' and 'd'
3263        assert_eq!(e.cur_ptr, 3);
3264        check_invariant(&e);
3265        insert(&mut e, "--");
3266        assert_eq!(text(&e), "abc--def");
3267        assert_eq!(e.cur_ptr, 5);
3268        check_invariant(&e);
3269    }
3270
3271    // -- (c) delete-select ---------------------------------------------------
3272
3273    #[test]
3274    fn delete_select_removes_range() {
3275        let mut e = ed();
3276        insert(&mut e, "hello world");
3277        // Select "hello " (0..6): cursor at 6, anchor at 0.
3278        e.set_select_core(0, 6, false); // cur at selEnd=6
3279        assert!(e.has_selection());
3280        e.delete_select();
3281        assert_eq!(text(&e), "world");
3282        assert!(!e.has_selection());
3283        check_invariant(&e);
3284    }
3285
3286    // -- (d) newLine with autoIndent -----------------------------------------
3287
3288    #[test]
3289    fn new_line_with_auto_indent_replicates_leading_ws() {
3290        let mut e = ed();
3291        insert(&mut e, "    code");
3292        e.new_line();
3293        assert_eq!(text(&e), "    code\n    ");
3294        assert_eq!(e.cur_pos.x, 4, "cursor after the replicated indent");
3295        check_invariant(&e);
3296    }
3297
3298    #[test]
3299    fn new_line_no_auto_indent() {
3300        let mut e = ed();
3301        e.auto_indent = false;
3302        insert(&mut e, "    code");
3303        e.new_line();
3304        assert_eq!(text(&e), "    code\n");
3305        check_invariant(&e);
3306    }
3307
3308    // -- (e) search hit + whole-word reject ----------------------------------
3309
3310    #[test]
3311    fn search_finds_from_cursor() {
3312        let mut e = ed();
3313        insert(&mut e, "the cat sat on the mat");
3314        e.set_cur_ptr_core(0, 0);
3315        assert!(e.search("cat", 0));
3316        assert_eq!(e.sel_start, 4);
3317        assert_eq!(e.sel_end, 7);
3318    }
3319
3320    #[test]
3321    fn search_case_insensitive_default() {
3322        let mut e = ed();
3323        insert(&mut e, "Hello World");
3324        e.set_cur_ptr_core(0, 0);
3325        assert!(e.search("world", 0), "default search is case-insensitive");
3326        assert_eq!(e.sel_start, 6);
3327    }
3328
3329    #[test]
3330    fn search_case_sensitive_rejects_wrong_case() {
3331        let mut e = ed();
3332        insert(&mut e, "Hello World");
3333        e.set_cur_ptr_core(0, 0);
3334        assert!(!e.search("world", EF_CASE_SENSITIVE));
3335    }
3336
3337    #[test]
3338    fn search_whole_word_rejects_substring() {
3339        let mut e = ed();
3340        insert(&mut e, "category cat");
3341        e.set_cur_ptr_core(0, 0);
3342        // Whole-word "cat" must skip "category" and match the standalone "cat".
3343        assert!(e.search("cat", EF_WHOLE_WORDS_ONLY));
3344        assert_eq!(e.sel_start, 9, "matched the standalone 'cat' at 9");
3345    }
3346
3347    #[test]
3348    fn search_whole_word_no_match() {
3349        let mut e = ed();
3350        insert(&mut e, "category");
3351        e.set_cur_ptr_core(0, 0);
3352        assert!(!e.search("cat", EF_WHOLE_WORDS_ONLY));
3353    }
3354
3355    // -- (f) undo after insert restores prior text & cursor ------------------
3356
3357    #[test]
3358    fn undo_after_insert_removes_it() {
3359        let mut e = ed();
3360        insert(&mut e, "abc");
3361        // A real cursor move establishes an undo checkpoint (setSelect's gap move
3362        // zeroes the ins/del counts), so the next insert is the only thing undo
3363        // reverts. (A no-op move does NOT checkpoint — faithful to C++.)
3364        e.set_cur_ptr_core(0, 0);
3365        let before_cur = e.cur_ptr;
3366        e.insert_text_core(b"XYZ", false);
3367        assert_eq!(text(&e), "XYZabc");
3368        e.undo();
3369        assert_eq!(text(&e), "abc", "undo removes only the last insert run");
3370        assert_eq!(e.cur_ptr, before_cur, "cursor restored to before insert");
3371        check_invariant(&e);
3372    }
3373
3374    /// The highest-bug-density path: deleting pre-existing text selected FORWARD
3375    /// (cursor at sel_end, `del_len > 0`) hits the undo memmove + the `dst`
3376    /// underflow arithmetic in insert_buffer. The most ordinary edit there is.
3377    #[test]
3378    fn undo_after_forward_delete_of_existing_text() {
3379        let mut e = ed();
3380        insert(&mut e, "hello world");
3381        e.set_cur_ptr_core(0, 0); // checkpoint: ins_count → 0
3382        e.set_select_core(0, 6, false); // cursor at sel_end=6, selects "hello "
3383        e.delete_select(); // del_len = 6 - 0 = 6 → hits the memmove
3384        assert_eq!(text(&e), "world");
3385        check_invariant(&e);
3386        e.undo();
3387        assert_eq!(
3388            text(&e),
3389            "hello world",
3390            "undo restores the forward-deleted text"
3391        );
3392        check_invariant(&e);
3393    }
3394
3395    #[test]
3396    fn undo_after_delete_restores_text() {
3397        let mut e = ed();
3398        insert(&mut e, "hello");
3399        // Delete "ello" via backspace-like range delete with undo.
3400        e.set_select_core(1, 5, true); // cur at selStart=1
3401        e.delete_select();
3402        assert_eq!(text(&e), "h");
3403        e.undo();
3404        assert_eq!(text(&e), "hello", "undo restores the deleted text");
3405        check_invariant(&e);
3406    }
3407
3408    // -- (g) backspace / delChar / delWord / delLine ranges ------------------
3409
3410    #[test]
3411    fn backspace_deletes_prev_char() {
3412        let mut e = ed();
3413        insert(&mut e, "abc");
3414        e.delete_range(e.prev_char(e.cur_ptr), e.cur_ptr, true);
3415        assert_eq!(text(&e), "ab");
3416        check_invariant(&e);
3417    }
3418
3419    #[test]
3420    fn del_char_deletes_next() {
3421        let mut e = ed();
3422        insert(&mut e, "abc");
3423        e.set_cur_ptr_core(0, 0);
3424        e.delete_range(e.cur_ptr, e.next_char(e.cur_ptr), true);
3425        assert_eq!(text(&e), "bc");
3426        check_invariant(&e);
3427    }
3428
3429    #[test]
3430    fn del_word_deletes_to_next_word() {
3431        let mut e = ed();
3432        insert(&mut e, "foo bar baz");
3433        e.set_cur_ptr_core(0, 0);
3434        // delWord deletes up to the next word boundary (the space after "foo").
3435        e.delete_range(e.cur_ptr, e.next_word(e.cur_ptr), false);
3436        assert_eq!(text(&e), " bar baz");
3437        check_invariant(&e);
3438    }
3439
3440    #[test]
3441    fn del_line_deletes_whole_line() {
3442        let mut e = ed();
3443        insert(&mut e, "line1\nline2\nline3");
3444        // Put the cursor on line2.
3445        e.set_cur_ptr_core(8, 0);
3446        e.delete_range(e.line_start(e.cur_ptr), e.next_line(e.cur_ptr), false);
3447        assert_eq!(text(&e), "line1\nline3");
3448        check_invariant(&e);
3449    }
3450
3451    #[test]
3452    fn del_start_deletes_to_line_start() {
3453        let mut e = ed();
3454        insert(&mut e, "abcdef");
3455        e.set_cur_ptr_core(3, 0);
3456        // cmDelStart: deleteRange(lineStart, curPtr, False).
3457        e.delete_range(e.line_start(e.cur_ptr), e.cur_ptr, false);
3458        assert_eq!(text(&e), "def");
3459        check_invariant(&e);
3460    }
3461
3462    #[test]
3463    fn del_end_deletes_to_line_end() {
3464        let mut e = ed();
3465        insert(&mut e, "abcdef");
3466        e.set_cur_ptr_core(3, 0);
3467        // cmDelEnd: deleteRange(curPtr, lineEnd, False).
3468        e.delete_range(e.cur_ptr, e.line_end(e.cur_ptr), false);
3469        assert_eq!(text(&e), "abc");
3470        check_invariant(&e);
3471    }
3472
3473    // -- line endings --------------------------------------------------------
3474
3475    #[test]
3476    fn insert_converts_line_endings_to_lf() {
3477        let mut e = ed(); // default LF
3478        e.insert_text_core(b"a\r\nb\rc\n", false);
3479        assert_eq!(text(&e), "a\nb\nc\n");
3480        check_invariant(&e);
3481    }
3482
3483    #[test]
3484    fn crlf_editor_converts_to_crlf() {
3485        let mut e = Editor::new(Rect::new(0, 0, 40, 10), None, None, None, 1024);
3486        e.line_ending = LineEnding::CrLf;
3487        e.insert_text_core(b"a\nb", false);
3488        assert_eq!(text(&e), "a\r\nb");
3489        check_invariant(&e);
3490    }
3491
3492    #[test]
3493    fn limit_y_counts_lines() {
3494        let mut e = ed();
3495        insert(&mut e, "one\ntwo\nthree");
3496        assert_eq!(e.limit.y, 3, "3 lines → limit.y = 2 breaks + 1");
3497        check_invariant(&e);
3498    }
3499
3500    // -- navigation ----------------------------------------------------------
3501
3502    #[test]
3503    fn line_move_preserves_column() {
3504        let mut e = ed();
3505        insert(&mut e, "abcdef\nghijkl\nmnopqr");
3506        // Cursor at column 3 of last line.
3507        e.set_cur_ptr_core(0, 0);
3508        e.set_cur_ptr_core(3, 0); // col 3 line 0
3509        assert_eq!(e.cur_pos, Point::new(3, 0));
3510        let p = e.line_move(e.cur_ptr, 1);
3511        e.set_cur_ptr_core(p, 0);
3512        assert_eq!(e.cur_pos.y, 1);
3513        assert_eq!(e.cur_pos.x, 3, "column preserved across line move");
3514    }
3515
3516    #[test]
3517    fn word_navigation() {
3518        let mut e = ed();
3519        insert(&mut e, "foo bar");
3520        e.set_cur_ptr_core(0, 0);
3521        // nextWord stops at the first word boundary — the space after "foo" (3).
3522        assert_eq!(e.next_word(0), 3, "next word boundary is the space at 3");
3523        // prevWord from end → start of "bar" (4).
3524        assert_eq!(e.prev_word(7), 4, "prev word from end → 'bar' start");
3525    }
3526
3527    // -- toggleInsMode / encoding -------------------------------------------
3528
3529    #[test]
3530    fn toggle_ins_mode_flips_overwrite_and_cursor() {
3531        let mut e = ed();
3532        assert!(!e.overwrite);
3533        e.toggle_ins_mode();
3534        assert!(e.overwrite);
3535        assert!(e.state.state.cursor_ins);
3536        // TVCursor::decideCaretSize: overwrite shows the block caret.
3537        assert_eq!(e.caret_size(), crate::backend::CARET_INSERT);
3538        e.toggle_ins_mode();
3539        assert!(!e.overwrite);
3540        assert!(!e.state.state.cursor_ins);
3541        assert_eq!(e.caret_size(), crate::backend::CARET_NORMAL);
3542    }
3543
3544    // -- convertEvent keymap -------------------------------------------------
3545
3546    fn key(k: crate::event::Key) -> crate::event::KeyEvent {
3547        crate::event::KeyEvent::from(k)
3548    }
3549    fn ctrl(c: char) -> crate::event::KeyEvent {
3550        crate::event::KeyEvent::new(
3551            crate::event::Key::Char(c),
3552            crate::event::KeyModifiers {
3553                ctrl: true,
3554                ..Default::default()
3555            },
3556        )
3557    }
3558
3559    #[test]
3560    fn keymap_arrows_and_named() {
3561        use crate::event::Key;
3562        use crate::keymap::{KeyStroke, Keymap, Resolve};
3563        let km = Keymap::word_star();
3564        let r = |k| km.resolve(None, KeyStroke::from_event(key(k)));
3565        assert!(matches!(r(Key::Left),     Resolve::Command(c) if c == Command::CHAR_LEFT));
3566        assert!(matches!(r(Key::Home),     Resolve::Command(c) if c == Command::LINE_START));
3567        assert!(matches!(r(Key::PageDown), Resolve::Command(c) if c == Command::PAGE_DOWN));
3568        assert!(matches!(r(Key::Enter),    Resolve::Command(c) if c == Command::NEW_LINE));
3569        assert!(matches!(r(Key::Delete),   Resolve::Command(c) if c == Command::DEL_CHAR));
3570    }
3571
3572    #[test]
3573    fn keymap_ctrl_letters() {
3574        use crate::keymap::{KeyStroke, Keymap, Resolve};
3575        let km = Keymap::word_star();
3576        let r = |ke| km.resolve(None, KeyStroke::from_event(ke));
3577        assert!(matches!(r(ctrl('s')), Resolve::Command(c) if c == Command::CHAR_LEFT));
3578        assert!(matches!(r(ctrl('y')), Resolve::Command(c) if c == Command::DEL_LINE));
3579        assert!(matches!(r(ctrl('u')), Resolve::Command(c) if c == Command::UNDO));
3580    }
3581
3582    #[test]
3583    fn keymap_two_key_prefixes() {
3584        use crate::event::Key;
3585        use crate::keymap::{KeyStroke, Keymap, Resolve};
3586        let km = Keymap::word_star();
3587        let ks = KeyStroke::from_event;
3588        // Ctrl-Q → prefix.
3589        assert!(matches!(km.resolve(None, ks(ctrl('q'))), Resolve::Prefix));
3590        // Ctrl-K → prefix.
3591        assert!(matches!(km.resolve(None, ks(ctrl('k'))), Resolve::Prefix));
3592        // Ctrl-Q then 'f' → FIND.
3593        let q = ks(ctrl('q'));
3594        assert!(matches!(
3595            km.resolve(Some(q), ks(key(Key::Char('f')))),
3596            Resolve::Command(c) if c == Command::FIND
3597        ));
3598        // Ctrl-K then 'b' → START_SELECT.
3599        let k = ks(ctrl('k'));
3600        assert!(matches!(
3601            km.resolve(Some(k), ks(key(Key::Char('b')))),
3602            Resolve::Command(c) if c == Command::START_SELECT
3603        ));
3604    }
3605
3606    #[test]
3607    fn convert_event_prefix_then_command() {
3608        let _g = crate::keymap::GlobalKeymapGuard::new(crate::keymap::Keymap::word_star());
3609        let mut e = ed();
3610        // Ctrl-K starts a prefix and clears the event.
3611        let mut ev = Event::KeyDown(ctrl('k'));
3612        e.convert_event(&mut ev);
3613        assert!(ev.is_nothing(), "prefix key is cleared");
3614        assert!(e.pending.is_some(), "pending stroke stored");
3615        // The next 'b' resolves to cmStartSelect.
3616        let mut ev2 = Event::KeyDown(key(crate::event::Key::Char('b')));
3617        e.convert_event(&mut ev2);
3618        assert_eq!(ev2, Event::Command(Command::START_SELECT));
3619        assert!(e.pending.is_none(), "prefix consumed");
3620    }
3621
3622    /// Regression: plain Backspace must delete the character to the left.
3623    /// The WordStar default (seeded in Phase 1) binds `backspace → BACK_SPACE`,
3624    /// so this test needs no `set_global`.  Before the Phase 2 refactor,
3625    /// plain Backspace had no binding in the hardcoded match table and was a
3626    /// no-op.
3627    #[test]
3628    fn plain_backspace_deletes_char_left() {
3629        let mut e = ed();
3630        insert(&mut e, "ab");
3631        let mut cx = Cx::new();
3632        let mut ev = Event::KeyDown(crate::event::KeyEvent::from(crate::event::Key::Backspace));
3633        {
3634            let mut ctx = cx.ctx();
3635            e.handle_event(&mut ev, &mut ctx);
3636        }
3637        assert_eq!(
3638            text(&e),
3639            "a",
3640            "plain Backspace must delete the char to the left"
3641        );
3642        check_invariant(&e);
3643    }
3644
3645    // -- handle_event end-to-end (a typed char) ------------------------------
3646
3647    #[test]
3648    fn handle_event_inserts_typed_char() {
3649        let mut e = ed();
3650        let mut cx = Cx::new();
3651        let mut ev = Event::KeyDown(key(crate::event::Key::Char('A')));
3652        {
3653            let mut ctx = cx.ctx();
3654            e.handle_event(&mut ev, &mut ctx);
3655        }
3656        assert_eq!(text(&e), "A");
3657        assert!(ev.is_nothing(), "consumed");
3658    }
3659
3660    /// Regression: Shift+Tab is NOT insertable — it must not write a `\t`. Only a
3661    /// plain Tab inserts; Shift+Tab falls through and bubbles to the dialog for
3662    /// backward focus navigation.
3663    #[test]
3664    fn shift_tab_does_not_insert_tab() {
3665        let mut e = ed();
3666        let mut cx = Cx::new();
3667        let shift_tab = crate::event::KeyEvent::new(
3668            crate::event::Key::Tab,
3669            crate::event::KeyModifiers {
3670                shift: true,
3671                ..Default::default()
3672            },
3673        );
3674        let mut ev = Event::KeyDown(shift_tab);
3675        {
3676            let mut ctx = cx.ctx();
3677            e.handle_event(&mut ev, &mut ctx);
3678        }
3679        assert_eq!(text(&e), "", "Shift+Tab must NOT insert a tab");
3680        assert_eq!(
3681            ev,
3682            Event::KeyDown(shift_tab),
3683            "Shift+Tab must survive uncleared — it bubbles to dialog back-tab nav"
3684        );
3685    }
3686
3687    #[test]
3688    fn handle_event_char_left_command() {
3689        let mut e = ed();
3690        insert(&mut e, "abc");
3691        let mut cx = Cx::new();
3692        let mut ev = Event::Command(Command::CHAR_LEFT);
3693        {
3694            let mut ctx = cx.ctx();
3695            e.handle_event(&mut ev, &mut ctx);
3696        }
3697        assert_eq!(e.cur_ptr, 2, "cursor moved left one char");
3698    }
3699
3700    /// Regression: Ctrl-Del must delete the word to the right, not clear the
3701    /// selection — the WordStar preset binds `ctrl+delete → DEL_WORD` and omits the
3702    /// dead clear binding per the keymap design.
3703    #[test]
3704    fn ctrl_del_deletes_word_to_the_right() {
3705        let _g = crate::keymap::GlobalKeymapGuard::new(crate::keymap::Keymap::word_star());
3706        let mut e = ed();
3707        insert(&mut e, "foo bar");
3708        e.set_cur_ptr_core(0, 0);
3709        let mut cx = Cx::new();
3710        let ctrl_del = crate::event::KeyEvent::new(
3711            crate::event::Key::Delete,
3712            crate::event::KeyModifiers {
3713                ctrl: true,
3714                ..Default::default()
3715            },
3716        );
3717        let mut ev = Event::KeyDown(ctrl_del);
3718        {
3719            let mut ctx = cx.ctx();
3720            e.handle_event(&mut ev, &mut ctx);
3721        }
3722        // delWord = deleteRange(curPtr, nextWord(curPtr), False); nextWord("foo bar")
3723        // from 0 lands on the space after "foo" (3), so "foo" is deleted (the
3724        // standalone trailing-space removal happens on the NEXT delWord).
3725        assert_eq!(text(&e), " bar", "Ctrl-Del deleted the word, not all text");
3726        check_invariant(&e);
3727    }
3728
3729    /// Select-All selects the whole buffer.
3730    #[test]
3731    fn select_all_selects_whole_buffer() {
3732        let mut e = ed();
3733        insert(&mut e, "hello world");
3734        let mut cx = Cx::new();
3735        let mut ev = Event::Command(Command::SELECT_ALL);
3736        {
3737            let mut ctx = cx.ctx();
3738            e.handle_event(&mut ev, &mut ctx);
3739        }
3740        assert_eq!(e.sel_start, 0);
3741        assert_eq!(e.sel_end, e.buf_len);
3742        assert!(e.has_selection());
3743    }
3744
3745    /// Overwrite mode replaces the char under the cursor instead of inserting.
3746    #[test]
3747    fn overwrite_mode_replaces_char() {
3748        let mut e = ed();
3749        insert(&mut e, "abc");
3750        e.set_cur_ptr_core(1, 0); // between 'a' and 'b'
3751        e.toggle_ins_mode(); // overwrite on
3752        assert!(e.overwrite);
3753        let len_before = e.buf_len;
3754        let mut cx = Cx::new();
3755        let mut ev = Event::KeyDown(key(crate::event::Key::Char('X')));
3756        {
3757            let mut ctx = cx.ctx();
3758            e.handle_event(&mut ev, &mut ctx);
3759        }
3760        assert_eq!(text(&e), "aXc", "overwrote 'b'");
3761        assert_eq!(e.buf_len, len_before, "buf_len unchanged in overwrite");
3762        check_invariant(&e);
3763    }
3764
3765    /// Invalid UTF-8 bytes (reachable via the public byte API) advance exactly one
3766    /// logical byte per `next_char`, never desyncing from a grapheme boundary.
3767    #[test]
3768    fn next_char_over_invalid_utf8_advances_one_byte() {
3769        let mut e = ed();
3770        let mut cx = Cx::new();
3771        {
3772            let mut ctx = cx.ctx();
3773            e.insert_text(&[b'a', 0xFF, b'b'], false, &mut ctx);
3774        }
3775        assert_eq!(e.buf_len, 3);
3776        check_invariant(&e);
3777        // Walk: 0 → 1 ('a') → 2 (invalid 0xFF, one byte) → 3 ('b').
3778        let p1 = e.next_char(0);
3779        assert_eq!(p1, 1);
3780        let p2 = e.next_char(p1);
3781        assert_eq!(p2, 2, "invalid byte advances exactly one logical byte");
3782        let p3 = e.next_char(p2);
3783        assert_eq!(p3, 3);
3784        // And prev_char steps back symmetrically.
3785        assert_eq!(e.prev_char(3), 2);
3786        assert_eq!(e.prev_char(2), 1, "step back over the invalid byte by one");
3787        assert_eq!(e.prev_char(1), 0);
3788        check_invariant(&e);
3789    }
3790
3791    // -- public caret/selection/scroll API (core + flush) --------------------
3792
3793    /// The whole point of the ctx+flush shape: after the public `set_cur_ptr`,
3794    /// `state().cursor` already reflects the new position — `do_update` ran as
3795    /// part of the call, so there is no desync window to fall into.
3796    #[test]
3797    fn public_set_cur_ptr_moves_and_publishes_cursor() {
3798        let mut e = ed();
3799        insert(&mut e, "hello world");
3800        let mut cx = Cx::new();
3801        {
3802            let mut ctx = cx.ctx();
3803            e.set_cur_ptr(3, 0, &mut ctx);
3804        }
3805        assert_eq!(e.cur_ptr, 3);
3806        assert_eq!(e.state.cursor, Point::new(3, 0), "do_update ran via flush");
3807    }
3808
3809    /// `cur_start` picks which end of the new selection the cursor lands on.
3810    #[test]
3811    fn public_set_select_places_cursor_at_chosen_end() {
3812        let mut e = ed();
3813        insert(&mut e, "hello world");
3814
3815        let mut cx = Cx::new();
3816        {
3817            let mut ctx = cx.ctx();
3818            e.set_select(0, 6, true, &mut ctx); // cur_start: cursor at the START
3819        }
3820        assert_eq!((e.sel_start, e.sel_end), (0, 6));
3821        assert_eq!(e.cur_ptr, 0);
3822
3823        let mut cx = Cx::new();
3824        {
3825            let mut ctx = cx.ctx();
3826            e.set_select(0, 6, false, &mut ctx); // cursor at the END
3827        }
3828        assert_eq!(e.cur_ptr, 6);
3829    }
3830
3831    /// `scroll_to` adopts the new offset and publishes the cursor relative to it.
3832    #[test]
3833    fn public_scroll_to_updates_delta_and_publishes() {
3834        let mut e = tall_ed();
3835        give_id(&mut e);
3836        e.set_cur_ptr_core(21, 0); // start of "line03" (7 bytes/line × 3)
3837        assert_eq!(e.cur_pos.y, 3);
3838
3839        let mut cx = Cx::new();
3840        {
3841            let mut ctx = cx.ctx();
3842            e.scroll_to(0, 3, &mut ctx);
3843        }
3844        assert_eq!(e.delta.y, 3);
3845        assert_eq!(
3846            e.state.cursor.y, 0,
3847            "cursor republished relative to the new scroll offset (line 3 - delta 3)"
3848        );
3849    }
3850
3851    /// `track_cursor` scrolls an offscreen cursor back into view.
3852    #[test]
3853    fn public_track_cursor_scrolls_offscreen_cursor_into_view() {
3854        let mut e = tall_ed();
3855        give_id(&mut e);
3856        e.set_cur_ptr_core(e.buf_len, 0); // last line, offscreen in a 10-row view
3857        assert!(!e.cursor_visible(), "cursor starts offscreen");
3858
3859        let mut cx = Cx::new();
3860        {
3861            let mut ctx = cx.ctx();
3862            e.track_cursor(false, &mut ctx);
3863        }
3864        assert!(e.cursor_visible(), "track_cursor scrolled it into view");
3865    }
3866
3867    // -- clipboard broker (deferred ops) -------------------------------------
3868
3869    #[test]
3870    fn clip_copy_queues_set_clipboard() {
3871        let mut e = ed();
3872        insert(&mut e, "hello");
3873        e.set_select_core(0, 5, false);
3874        let mut cx = Cx::new();
3875        {
3876            let mut ctx = cx.ctx();
3877            assert!(e.clip_copy(&mut ctx));
3878        }
3879        assert!(
3880            cx.deferred
3881                .iter()
3882                .any(|d| matches!(d, Deferred::SetClipboard(s) if s == "hello")),
3883            "clipCopy queues SetClipboard with the selection"
3884        );
3885    }
3886
3887    #[test]
3888    fn clip_paste_queues_editor_paste() {
3889        // The editor must have an id to be addressable.
3890        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3891        let id = group.insert(Box::new(ed()));
3892        let mut cx = Cx::new();
3893        {
3894            let mut ctx = cx.ctx();
3895            let v = group.find_mut(id).unwrap();
3896            let e = v.as_any_mut().unwrap().downcast_mut::<Editor>().unwrap();
3897            e.clip_paste(&mut ctx);
3898        }
3899        assert!(
3900            cx.deferred
3901                .iter()
3902                .any(|d| matches!(d, Deferred::EditorPaste(eid) if *eid == id))
3903        );
3904    }
3905
3906    // -- scrollbar broker request --------------------------------------------
3907
3908    #[test]
3909    fn broadcast_from_own_bar_requests_sync() {
3910        // Mint scrollbar ids.
3911        let mut bg = Group::new(Rect::new(0, 0, 4, 4));
3912        let h = bg.insert(Box::new(crate::widgets::ScrollBar::new(Rect::new(
3913            0, 0, 1, 4,
3914        ))));
3915        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3916        let id = group.insert(Box::new(Editor::new(
3917            Rect::new(0, 0, 40, 10),
3918            Some(h),
3919            None,
3920            None,
3921            1024,
3922        )));
3923        let mut cx = Cx::new();
3924        {
3925            let mut ctx = cx.ctx();
3926            let mut ev = Event::Broadcast {
3927                command: Command::SCROLL_BAR_CHANGED,
3928                source: Some(h),
3929            };
3930            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
3931        }
3932        assert!(
3933            cx.deferred
3934                .iter()
3935                .any(|d| matches!(d, Deferred::ScrollSync { target, .. } if *target == id))
3936        );
3937    }
3938
3939    // -- snapshot ------------------------------------------------------------
3940
3941    #[test]
3942    fn snapshot_two_lines_with_selection() {
3943        use crate::backend::{HeadlessBackend, Renderer};
3944        use crate::screen::Buffer;
3945        use crate::theme::Theme;
3946
3947        let theme = Theme::classic_blue();
3948        let mut e = Editor::new(Rect::new(0, 0, 12, 4), None, None, None, 1024);
3949        insert(&mut e, "hello\nworld");
3950        // Select "ello" on line 0.
3951        e.set_select_core(1, 5, false);
3952
3953        let (backend, screen) = HeadlessBackend::new(12, 4);
3954        let mut r = Renderer::new(Box::new(backend));
3955        r.render(|buf: &mut Buffer| {
3956            let bounds = e.state.get_bounds();
3957            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
3958            e.draw(&mut dc);
3959        });
3960        insta::assert_snapshot!(screen.snapshot());
3961    }
3962
3963    /// **The right-click popup is placed against the screen**, not against
3964    /// the editor's owner: the click position is in screen coordinates, so
3965    /// clamping it into the (smaller) owner moved the popup away from the
3966    /// click.
3967    #[test]
3968    fn right_click_popup_is_placed_against_the_screen() {
3969        use crate::backend::{HeadlessBackend, Renderer};
3970        use crate::event::{MouseButtons, MouseEvent};
3971        use crate::screen::Buffer;
3972        use crate::theme::Theme;
3973
3974        let theme = Theme::classic_blue();
3975        let mut e = Editor::new(Rect::new(40, 10, 60, 15), None, None, None, 1024);
3976        let (backend, _screen) = HeadlessBackend::new(80, 25);
3977        let mut r = Renderer::new(Box::new(backend));
3978        r.render(|buf: &mut Buffer| {
3979            let bounds = e.state.get_bounds();
3980            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
3981            e.draw(&mut dc);
3982        });
3983        let mut cx = Cx::new();
3984        let mut ev = Event::MouseDown(MouseEvent {
3985            position: Point::new(2, 1),
3986            buttons: MouseButtons {
3987                right: true,
3988                ..Default::default()
3989            },
3990            ..Default::default()
3991        });
3992        {
3993            let mut ctx = cx.ctx();
3994            // The editor's owner (its window interior) is far smaller than
3995            // the screen.
3996            ctx.set_owner_size(Point::new(22, 7));
3997            e.handle_event(&mut ev, &mut ctx);
3998        }
3999        assert!(ev.is_nothing());
4000        let bounds = cx
4001            .deferred
4002            .iter()
4003            .find_map(|d| match d {
4004                Deferred::OpenMenuBox { bounds, .. } => Some(*bounds),
4005                _ => None,
4006            })
4007            .expect("a popup opens");
4008        assert_eq!(
4009            (bounds.a.x, bounds.a.y),
4010            (42, 12),
4011            "the popup opens below-right of the click at (42, 11)"
4012        );
4013    }
4014
4015    // -- Memo ----------------------------------------------------------------
4016
4017    fn memo() -> Memo {
4018        Memo::new(Rect::new(0, 0, 40, 10), None, None, None, 1024)
4019    }
4020
4021    #[test]
4022    fn memo_value_set_value_round_trip() {
4023        let mut m = memo();
4024        m.set_value(crate::data::FieldValue::Text("hello\nworld".into()));
4025        assert_eq!(
4026            m.value(),
4027            Some(crate::data::FieldValue::Text("hello\nworld".into()))
4028        );
4029    }
4030
4031    #[test]
4032    fn memo_set_value_non_text_is_noop() {
4033        let mut m = memo();
4034        m.set_value(crate::data::FieldValue::Text("initial".into()));
4035        m.set_value(crate::data::FieldValue::Int(7));
4036        assert_eq!(
4037            m.value(),
4038            Some(crate::data::FieldValue::Text("initial".into()))
4039        );
4040    }
4041
4042    #[test]
4043    fn memo_tab_swallowed_not_cleared() {
4044        let mut m = memo();
4045        let mut cx = Cx::new();
4046        // Plain Tab: Memo swallows it (returns without clearing) — dialog can use it.
4047        let mut ev = Event::KeyDown(crate::event::KeyEvent::from(crate::event::Key::Tab));
4048        {
4049            let mut ctx = cx.ctx();
4050            m.handle_event(&mut ev, &mut ctx);
4051        }
4052        // The event must still be a Tab KeyDown (not consumed / not cleared).
4053        assert_eq!(
4054            ev,
4055            Event::KeyDown(crate::event::KeyEvent::from(crate::event::Key::Tab)),
4056            "plain Tab must NOT be consumed by Memo"
4057        );
4058        // The buffer must still be empty (Tab was not inserted).
4059        assert_eq!(text(&m.editor), "", "Tab must not insert text");
4060
4061        // A plain printable char IS forwarded and inserts text.
4062        let mut ev2 = Event::KeyDown(key(crate::event::Key::Char('x')));
4063        {
4064            let mut ctx = cx.ctx();
4065            m.handle_event(&mut ev2, &mut ctx);
4066        }
4067        assert!(
4068            ev2.is_nothing(),
4069            "printable char must be consumed by editor"
4070        );
4071        assert_eq!(text(&m.editor), "x", "char 'x' must be inserted");
4072    }
4073
4074    /// Memo only swallows *plain* Tab; Shift+Tab is forwarded to the editor,
4075    /// which (post-fix) treats it as non-insertable — so no `\t` is written and
4076    /// it bubbles to the dialog for backward focus navigation.
4077    #[test]
4078    fn memo_shift_tab_does_not_insert() {
4079        let mut m = memo();
4080        let mut cx = Cx::new();
4081        let shift_tab = crate::event::KeyEvent::new(
4082            crate::event::Key::Tab,
4083            crate::event::KeyModifiers {
4084                shift: true,
4085                ..Default::default()
4086            },
4087        );
4088        let mut ev = Event::KeyDown(shift_tab);
4089        {
4090            let mut ctx = cx.ctx();
4091            m.handle_event(&mut ev, &mut ctx);
4092        }
4093        assert_eq!(text(&m.editor), "", "Shift+Tab must NOT insert text");
4094        assert_eq!(
4095            ev,
4096            Event::KeyDown(shift_tab),
4097            "Shift+Tab must survive uncleared — it bubbles to dialog back-tab nav"
4098        );
4099    }
4100
4101    #[test]
4102    fn memo_snapshot() {
4103        use crate::backend::{HeadlessBackend, Renderer};
4104        use crate::screen::Buffer;
4105        use crate::theme::Theme;
4106
4107        let theme = Theme::classic_blue();
4108        let mut m = Memo::new(Rect::new(0, 0, 20, 4), None, None, None, 1024);
4109        m.set_value(crate::data::FieldValue::Text("line one\nline two".into()));
4110
4111        let (backend, screen) = HeadlessBackend::new(20, 4);
4112        let mut r = Renderer::new(Box::new(backend));
4113        r.render(|buf: &mut Buffer| {
4114            let bounds = m.editor.state.get_bounds();
4115            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
4116            m.draw(&mut dc);
4117        });
4118        insta::assert_snapshot!(screen.snapshot());
4119    }
4120
4121    // -- FileEditor -----------------------------------------------------------
4122
4123    /// A unique temp-file path per test (no `tempfile` dev-dep).
4124    fn tmp_path(name: &str) -> std::path::PathBuf {
4125        std::env::temp_dir().join(format!(
4126            "rstv_fileeditor_{}_{}.txt",
4127            std::process::id(),
4128            name
4129        ))
4130    }
4131
4132    /// An untitled file-editor (growable buffer, no backing file).
4133    fn untitled_fe() -> FileEditor {
4134        FileEditor::new(Rect::new(0, 0, 40, 10), None, None, None, None)
4135    }
4136
4137    /// A base editor / Memo with a fixed buffer REFUSES to grow.
4138    /// `set_buf_size` past capacity returns false,
4139    /// and `set_text` of an over-capacity payload is a no-op (text unchanged).
4140    #[test]
4141    fn base_editor_buffer_does_not_grow() {
4142        // Fixed 8-byte buffer.
4143        let mut e = Editor::new(Rect::new(0, 0, 40, 10), None, None, None, 8);
4144        assert!(!e.file_editor, "base editor is not in file-editor mode");
4145        // BEFORE state: the buffer fits 8 bytes; asking for more must fail.
4146        assert!(e.set_buf_size(8), "exactly-fitting size succeeds");
4147        assert!(
4148            !e.set_buf_size(9),
4149            "over-capacity grow refused (default off)"
4150        );
4151        assert_eq!(e.buf_size, 8, "buf_size unchanged by a refused grow");
4152
4153        // set_text of a 20-byte payload (over capacity) is an all-or-nothing no-op.
4154        e.set_text(b"0123456789abcdefghij");
4155        assert_eq!(e.buf_len, 0, "over-capacity set_text left the buffer empty");
4156        assert!(e.text().is_empty(), "text unchanged after refused grow");
4157        assert_eq!(e.buf_size, 8, "buf_size still fixed at 8");
4158    }
4159
4160    /// Memo (a Memo wraps a base Editor) likewise refuses to grow.
4161    #[test]
4162    fn memo_buffer_does_not_grow() {
4163        let mut m = Memo::new(Rect::new(0, 0, 40, 10), None, None, None, 8);
4164        assert!(!m.editor.file_editor);
4165        m.editor.set_text(b"0123456789abcdefghij");
4166        assert!(
4167            m.editor.text().is_empty(),
4168            "Memo's fixed buffer did not grow"
4169        );
4170        assert_eq!(m.editor.buf_size, 8);
4171    }
4172
4173    /// Growth works when file-editor mode is on: a >0x1000 payload round-trips and
4174    /// `buf_size` grows to a 0x1000 multiple ≥ payload.
4175    #[test]
4176    fn file_editor_buffer_grows() {
4177        let mut fe = untitled_fe();
4178        assert!(fe.editor.file_editor);
4179        assert_eq!(fe.editor.buf_size, 0, "starts empty (TFileEditor model)");
4180
4181        let payload = vec![b'x'; 0x1000 + 37]; // > one 0x1000 page
4182        fe.editor.set_text(&payload);
4183
4184        assert_eq!(fe.editor.text(), payload, "payload round-trips");
4185        assert_eq!(fe.editor.buf_len, payload.len());
4186        assert!(
4187            fe.editor.buf_size >= payload.len(),
4188            "buf_size accommodates the payload"
4189        );
4190        assert_eq!(
4191            fe.editor.buf_size % 0x1000,
4192            0,
4193            "buf_size is a 0x1000 multiple"
4194        );
4195        assert_eq!(fe.editor.buf_size, 0x2000, "rounded up to two pages");
4196        check_invariant(&fe.editor);
4197    }
4198
4199    /// Grow with content present and the cursor mid-buffer — exercises the
4200    /// non-degenerate `n > 0` tail memmove in `set_buf_size` (the other growth
4201    /// tests all start empty, so `n == 0` and the move is a no-op).
4202    #[test]
4203    fn file_editor_buffer_grows_with_content() {
4204        let mut fe = untitled_fe();
4205        fe.editor.set_text(&vec![b'a'; 0x1000]); // one full page; gap_len == 0
4206        assert_eq!(fe.editor.buf_size, 0x1000);
4207        fe.editor.set_cur_ptr_core(0x800, 0); // cursor in the middle (n becomes 0x800)
4208        insert(&mut fe.editor, "Z"); // forces set_buf_size(0x1001) -> grow
4209
4210        let mut expected = vec![b'a'; 0x800];
4211        expected.push(b'Z');
4212        expected.extend(std::iter::repeat_n(b'a', 0x800));
4213        assert_eq!(
4214            fe.editor.text(),
4215            expected,
4216            "text intact across a grow with n > 0"
4217        );
4218        assert_eq!(fe.editor.buf_size, 0x2000, "grew to two pages");
4219        check_invariant(&fe.editor);
4220    }
4221
4222    /// load_file round-trip: a written file loads into the editor and is valid.
4223    #[test]
4224    fn file_editor_load_round_trip() {
4225        let path = tmp_path("load_round_trip");
4226        let content = b"first line\nsecond line\nthird line\n";
4227        std::fs::write(&path, content).unwrap();
4228
4229        let fe = FileEditor::new(
4230            Rect::new(0, 0, 40, 10),
4231            None,
4232            None,
4233            None,
4234            Some(path.clone()),
4235        );
4236        assert!(fe.editor.is_valid, "loaded editor is valid");
4237        assert_eq!(fe.editor.text(), content, "loaded text matches the file");
4238
4239        let _ = std::fs::remove_file(&path);
4240    }
4241
4242    /// A missing file loads as a valid, empty buffer.
4243    #[test]
4244    fn file_editor_load_missing_file() {
4245        let path = tmp_path("missing_does_not_exist");
4246        let _ = std::fs::remove_file(&path); // ensure absent
4247        let fe = FileEditor::new(
4248            Rect::new(0, 0, 40, 10),
4249            None,
4250            None,
4251            None,
4252            Some(path.clone()),
4253        );
4254        assert!(fe.editor.is_valid, "missing file ⇒ valid");
4255        assert!(fe.editor.text().is_empty(), "missing file ⇒ empty buffer");
4256    }
4257
4258    /// Unreadable file (exists, mode 0o000) ⇒ is_valid=false, pending_load_error stored,
4259    /// and `handle_event` queues an `OpenMessageBox` on the first call.
4260    #[cfg(unix)]
4261    #[test]
4262    fn file_editor_load_unreadable_queues_error_box() {
4263        use crate::view::Deferred;
4264        use std::fs::Permissions;
4265        use std::os::unix::fs::PermissionsExt;
4266
4267        // Root bypasses DAC permission checks — mode 0o000 still opens for root.
4268        if unsafe { libc::geteuid() } == 0 {
4269            return;
4270        }
4271
4272        let path = tmp_path("unreadable");
4273        let _ = std::fs::remove_file(&path);
4274        std::fs::File::create(&path).expect("create temp file");
4275        std::fs::set_permissions(&path, Permissions::from_mode(0o000)).expect("set mode 0o000");
4276
4277        let mut fe = FileEditor::new(
4278            Rect::new(0, 0, 40, 10),
4279            None,
4280            None,
4281            None,
4282            Some(path.clone()),
4283        );
4284
4285        // Restore permissions so cleanup can proceed regardless of outcome.
4286        let _ = std::fs::set_permissions(&path, Permissions::from_mode(0o600));
4287        let _ = std::fs::remove_file(&path);
4288
4289        assert!(!fe.editor.is_valid, "unreadable file ⇒ is_valid=false");
4290        assert!(
4291            fe.pending_load_error.is_some(),
4292            "pending_load_error populated after load failure"
4293        );
4294
4295        // First handle_event must flush the error as an OpenMessageBox.
4296        let mut cx = Cx::new();
4297        let mut ev = crate::event::Event::Nothing;
4298        {
4299            let mut ctx = cx.ctx();
4300            fe.handle_event(&mut ev, &mut ctx);
4301        }
4302        assert!(
4303            fe.pending_load_error.is_none(),
4304            "pending_load_error consumed after handle_event"
4305        );
4306        assert!(
4307            cx.deferred.iter().any(|d| matches!(
4308                d,
4309                Deferred::OpenMessageBox { kind, buttons, .. }
4310                    if *kind == crate::dialog::MessageBoxKind::Error
4311                    && *buttons == crate::dialog::MessageBoxButtons::ok()
4312            )),
4313            "handle_event queued an OpenMessageBox(Error) for the read failure"
4314        );
4315    }
4316
4317    /// save_file round-trip: an untitled buffer, given a filename, writes to disk
4318    /// and clears `modified`.
4319    #[test]
4320    fn file_editor_save_round_trip() {
4321        let path = tmp_path("save_round_trip");
4322        let _ = std::fs::remove_file(&path);
4323
4324        let mut fe = untitled_fe();
4325        insert(&mut fe.editor, "saved content\nmore text\n");
4326        assert!(fe.editor.modified(), "insert marks modified");
4327
4328        fe.file_name = Some(path.clone());
4329        let mut cx = Cx::new();
4330        assert!(fe.save(&mut cx.ctx()), "save() to a named file succeeds");
4331
4332        let on_disk = std::fs::read(&path).unwrap();
4333        assert_eq!(on_disk, fe.editor.text(), "disk bytes equal editor text");
4334        assert!(!fe.editor.modified(), "modified cleared after save");
4335
4336        let _ = std::fs::remove_file(&path);
4337    }
4338
4339    /// EF_BACKUP_FILES: when the flag is set, save_file renames the existing file
4340    /// to `<name>~` before writing the new content, using the Unix `~` convention.
4341    #[test]
4342    fn backup_file_created_on_save_with_ef_backup_files() {
4343        let path = tmp_path("backup_test");
4344        let backup = {
4345            let mut s = path.as_os_str().to_os_string();
4346            s.push("~");
4347            std::path::PathBuf::from(s)
4348        };
4349        // Ensure clean state.
4350        let _ = std::fs::remove_file(&path);
4351        let _ = std::fs::remove_file(&backup);
4352
4353        // Write original content so there is something to back up.
4354        let original = b"original content\n";
4355        std::fs::write(&path, original).unwrap();
4356
4357        // Build a FileEditor with EF_BACKUP_FILES enabled.
4358        let mut fe = FileEditor::new(
4359            Rect::new(0, 0, 40, 10),
4360            None,
4361            None,
4362            None,
4363            Some(path.clone()),
4364        );
4365        assert!(fe.editor.is_valid, "loaded editor is valid");
4366        fe.editor.set_editor_flags(EF_BACKUP_FILES);
4367
4368        // Replace content via insert and save.
4369        fe.editor.set_buf_len(0); // clear the buffer
4370        insert(&mut fe.editor, "new content\n");
4371        let mut cx = Cx::new();
4372        assert!(fe.save_file(&mut cx.ctx()), "save_file succeeds");
4373
4374        // The backup must contain the original bytes.
4375        let backed_up = std::fs::read(&backup).expect("backup file must exist");
4376        assert_eq!(backed_up, original, "backup holds the original content");
4377
4378        // The main file must contain the new content.
4379        let on_disk = std::fs::read(&path).unwrap();
4380        assert_eq!(
4381            on_disk,
4382            fe.editor.text(),
4383            "saved file holds the new content"
4384        );
4385
4386        let _ = std::fs::remove_file(&path);
4387        let _ = std::fs::remove_file(&backup);
4388    }
4389
4390    /// Without EF_BACKUP_FILES the backup file must NOT be created.
4391    #[test]
4392    fn no_backup_without_ef_backup_files() {
4393        let path = tmp_path("no_backup_test");
4394        let backup = {
4395            let mut s = path.as_os_str().to_os_string();
4396            s.push("~");
4397            std::path::PathBuf::from(s)
4398        };
4399        let _ = std::fs::remove_file(&path);
4400        let _ = std::fs::remove_file(&backup);
4401
4402        std::fs::write(&path, b"original\n").unwrap();
4403
4404        let mut fe = FileEditor::new(
4405            Rect::new(0, 0, 40, 10),
4406            None,
4407            None,
4408            None,
4409            Some(path.clone()),
4410        );
4411        assert!(fe.editor.is_valid);
4412        // flag NOT set — default editor_flags = 0
4413        let mut cx = Cx::new();
4414        fe.save_file(&mut cx.ctx());
4415
4416        assert!(
4417            !backup.exists(),
4418            "backup must not be created when EF_BACKUP_FILES is off"
4419        );
4420        let _ = std::fs::remove_file(&path);
4421    }
4422
4423    /// A Save command via handle_event writes the file and clears the event.
4424    #[test]
4425    fn file_editor_handle_save_command() {
4426        let path = tmp_path("handle_save_command");
4427        let _ = std::fs::remove_file(&path);
4428
4429        let mut fe = untitled_fe();
4430        insert(&mut fe.editor, "via handle_event\n");
4431        fe.file_name = Some(path.clone());
4432
4433        let mut cx = Cx::new();
4434        let mut ev = Event::Command(Command::SAVE);
4435        fe.handle_event(&mut ev, &mut cx.ctx());
4436
4437        assert!(ev.is_nothing(), "cmSave was cleared by handle_event");
4438        let on_disk = std::fs::read(&path).unwrap();
4439        assert_eq!(on_disk, fe.editor.text(), "file written via cmSave");
4440        assert!(!fe.editor.modified(), "modified cleared");
4441        // clear_modified's UF_UPDATE was flushed inline (not left pending) — the
4442        // indicator/commands publish modified=false on this event, not the next.
4443        assert_eq!(
4444            fe.editor.update_flags, 0,
4445            "no pending update flag after cmSave flush"
4446        );
4447
4448        let _ = std::fs::remove_file(&path);
4449    }
4450
4451    /// Calling `save()` directly on an untitled buffer is a no-op (it has no name
4452    /// to write to; the save-as dialog supplies one) — returns false, no panic.
4453    #[test]
4454    fn file_editor_save_untitled_is_noop() {
4455        let mut fe = untitled_fe();
4456        insert(&mut fe.editor, "unsaved");
4457        let mut cx = Cx::new();
4458        assert!(
4459            !fe.save(&mut cx.ctx()),
4460            "untitled save is a no-op (the save-as dialog supplies a name)"
4461        );
4462        assert!(fe.editor.modified(), "still modified — nothing was saved");
4463    }
4464
4465    /// valid: the plain validity command reflects is_valid; a modified buffer
4466    /// requests the save prompt and vetoes (false) until the answer routes back;
4467    /// an unmodified buffer allows close.
4468    #[test]
4469    fn file_editor_valid() {
4470        let mut fe = untitled_fe();
4471        assert!(fe.editor.is_valid);
4472        let mut cx = Cx::new();
4473        assert!(
4474            fe.valid(Command::VALID, &mut cx.ctx()),
4475            "cmValid reflects a valid buffer"
4476        );
4477        // Unmodified, non-cmValid ⇒ allow close (no prompt).
4478        assert!(
4479            fe.valid(Command::CLOSE, &mut cx.ctx()),
4480            "unmodified buffer allows close"
4481        );
4482    }
4483
4484    // -- save-as: the view-triggered file dialog -------------------------------
4485
4486    /// A Save-As command on a FileEditor requests the save-as file dialog (the
4487    /// deferred push), regardless of whether the buffer is titled, and clears the
4488    /// event.
4489    #[test]
4490    fn save_as_requests_dialog() {
4491        let mut group = Group::new(Rect::new(0, 0, 40, 10));
4492        let id = group.insert(Box::new(untitled_fe()));
4493        let mut cx = Cx::new();
4494        {
4495            let mut ctx = cx.ctx();
4496            let mut ev = Event::Command(Command::SAVE_AS);
4497            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
4498            assert!(ev.is_nothing(), "cmSaveAs is consumed (cleared)");
4499        }
4500        assert!(
4501            cx.deferred
4502                .iter()
4503                .any(|d| matches!(d, Deferred::OpenSaveAsDialog { editor_id } if *editor_id == id)),
4504            "cmSaveAs queues OpenSaveAsDialog for the editor"
4505        );
4506    }
4507
4508    /// Saving an untitled buffer also requests the dialog — it cannot save without
4509    /// a name.
4510    #[test]
4511    fn untitled_save_requests_dialog() {
4512        let mut group = Group::new(Rect::new(0, 0, 40, 10));
4513        let id = group.insert(Box::new(untitled_fe()));
4514        let mut cx = Cx::new();
4515        {
4516            let mut ctx = cx.ctx();
4517            let v = group.find_mut(id).unwrap();
4518            let fe = v
4519                .as_any_mut()
4520                .unwrap()
4521                .downcast_mut::<FileEditor>()
4522                .unwrap();
4523            assert!(
4524                !fe.save(&mut ctx),
4525                "untitled save returns false (async path)"
4526            );
4527        }
4528        assert!(
4529            cx.deferred
4530                .iter()
4531                .any(|d| matches!(d, Deferred::OpenSaveAsDialog { editor_id } if *editor_id == id)),
4532            "untitled save queues OpenSaveAsDialog"
4533        );
4534    }
4535
4536    /// After the save-as dialog completion set `file_name` + `pending_title_update`,
4537    /// the re-injected Save writes the new file AND broadcasts a title-update (the
4538    /// EditWindow title refresh). Drives the editor through a real Save over a temp
4539    /// path.
4540    #[test]
4541    fn save_as_then_save_writes_and_broadcasts_title() {
4542        let dir = std::env::temp_dir();
4543        let path = dir.join(format!("rstv_saveas_test_{}.txt", std::process::id()));
4544        let _ = std::fs::remove_file(&path);
4545
4546        let mut group = Group::new(Rect::new(0, 0, 40, 10));
4547        let id = group.insert(Box::new(untitled_fe()));
4548        // Put some content + the SaveAsPick post-conditions on the editor.
4549        {
4550            let v = group.find_mut(id).unwrap();
4551            let fe = v
4552                .as_any_mut()
4553                .unwrap()
4554                .downcast_mut::<FileEditor>()
4555                .unwrap();
4556            fe.editor.set_text(b"hello saveAs");
4557            fe.file_name = Some(path.clone());
4558            fe.pending_title_update = true;
4559        }
4560        let mut cx = Cx::new();
4561        {
4562            let mut ctx = cx.ctx();
4563            let mut ev = Event::Command(Command::SAVE);
4564            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
4565            assert!(ev.is_nothing(), "cmSave consumed");
4566        }
4567
4568        // The file was written with the buffer contents.
4569        let written = std::fs::read(&path).expect("file written");
4570        assert_eq!(written, b"hello saveAs");
4571        let _ = std::fs::remove_file(&path);
4572
4573        // cmUpdateTitle was broadcast (sourced from the editor) and the flag cleared.
4574        assert!(
4575            cx.out.iter().any(|e| matches!(
4576                e,
4577                Event::Broadcast { command, source } if *command == Command::UPDATE_TITLE && *source == Some(id)
4578            )),
4579            "successful saveAs broadcasts cmUpdateTitle"
4580        );
4581        {
4582            let v = group.find_mut(id).unwrap();
4583            let fe = v
4584                .as_any_mut()
4585                .unwrap()
4586                .downcast_mut::<FileEditor>()
4587                .unwrap();
4588            assert!(!fe.pending_title_update, "title-update flag consumed");
4589        }
4590    }
4591
4592    /// `EditWindow::handle_event` refreshes its frame title on a title-update
4593    /// broadcast, recomputing it from the hosted editor's current `file_name`.
4594    #[test]
4595    fn edit_window_updates_title_on_broadcast() {
4596        let mut ew = EditWindow::new(Rect::new(0, 0, 40, 15), None, 0);
4597        assert_eq!(ew.window.title(), Some("Untitled"));
4598        let editor_id = ew.editor_id;
4599        // Rename the hosted editor (simulating a completed saveAs).
4600        {
4601            let fe = ew
4602                .window
4603                .child_mut(editor_id)
4604                .and_then(|v| v.as_any_mut())
4605                .and_then(|a| a.downcast_mut::<FileEditor>())
4606                .expect("editor child");
4607            fe.file_name = Some(std::path::PathBuf::from("/tmp/renamed.txt"));
4608        }
4609        let mut cx = Cx::new();
4610        {
4611            let mut ctx = cx.ctx();
4612            let mut ev = Event::Broadcast {
4613                command: Command::UPDATE_TITLE,
4614                source: Some(editor_id),
4615            };
4616            View::handle_event(&mut ew, &mut ev, &mut ctx);
4617        }
4618        assert_eq!(
4619            ew.window.title(),
4620            Some("/tmp/renamed.txt"),
4621            "frame title refreshed from the editor's new file_name"
4622        );
4623    }
4624
4625    // -----------------------------------------------------------------------
4626    // EditWindow tests
4627    // -----------------------------------------------------------------------
4628
4629    /// 1a. Title is the filename stem when a path is given.
4630    #[test]
4631    fn edit_window_title_from_path() {
4632        let ew = EditWindow::new(
4633            Rect::new(0, 0, 40, 15),
4634            Some(std::path::PathBuf::from("/tmp/foo.txt")),
4635            1,
4636        );
4637        let t = ew.window.title().unwrap_or("");
4638        assert!(
4639            t.contains("foo.txt"),
4640            "title should contain the filename; got {t:?}"
4641        );
4642    }
4643
4644    /// 1b. Title is "Untitled" when no path is given.
4645    #[test]
4646    fn edit_window_title_untitled() {
4647        let ew = EditWindow::new(Rect::new(0, 0, 40, 15), None, 0);
4648        assert_eq!(
4649            ew.window.title(),
4650            Some("Untitled"),
4651            "untitled edit window title"
4652        );
4653    }
4654
4655    /// 2. size_limits returns (24,6) as the minimum.
4656    #[test]
4657    fn edit_window_size_limits_min() {
4658        let ew = EditWindow::new(Rect::new(0, 0, 40, 15), None, 0);
4659        let (min, _max) = View::size_limits(&ew, Point::new(80, 25));
4660        assert_eq!(min, Point::new(24, 6), "minEditWinSize = {{24, 6}}");
4661    }
4662
4663    /// 3. Construction invariants: editor child is visible+selectable; the
4664    ///    scrollbars/indicator start hidden (load-bearing — `reset_current`
4665    ///    picks the first visible+selectable child, so a stray-visible scrollbar
4666    ///    would steal currency from the editor); the window is tileable.
4667    #[test]
4668    fn edit_window_child_visibility_invariant() {
4669        let mut ew = EditWindow::new(Rect::new(0, 0, 40, 15), None, 0);
4670        let editor_id = ew.editor_id;
4671
4672        // Editor child is visible and selectable.
4673        {
4674            let fe = ew.window.child_mut(editor_id).expect("editor child exists");
4675            let st = fe.state();
4676            assert!(st.state.visible, "editor child is visible");
4677            assert!(
4678                st.options.selectable,
4679                "editor child is selectable (reset_current picks it)"
4680            );
4681        }
4682
4683        // The scrollbars and indicator start hidden.
4684        for id in [ew.h_scroll_bar_id, ew.v_scroll_bar_id, ew.indicator_id] {
4685            let v = ew.window.child_mut(id).expect("aux child exists");
4686            assert!(
4687                !v.state().state.visible,
4688                "aux child {id:?} must start hidden"
4689            );
4690        }
4691
4692        // The tileable flag was set.
4693        assert!(
4694            View::state(&ew).options.tileable,
4695            "ofTileable set on EditWindow"
4696        );
4697    }
4698
4699    /// 4. Snapshot: an untitled EditWindow renders as a framed window.
4700    #[test]
4701    fn edit_window_snapshot() {
4702        use crate::backend::{HeadlessBackend, Renderer};
4703        use crate::screen::Buffer;
4704        use crate::theme::Theme;
4705
4706        let theme = Theme::classic_blue();
4707        let ew = EditWindow::new(Rect::new(0, 0, 30, 8), None, 1);
4708        let mut view: Box<dyn View> = Box::new(ew);
4709        let (backend, screen) = HeadlessBackend::new(30, 8);
4710        let mut r = Renderer::new(Box::new(backend));
4711        r.render(|buf: &mut Buffer| {
4712            let bounds = view.state().get_bounds();
4713            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
4714            view.draw(&mut dc);
4715        });
4716        insta::assert_snapshot!(screen.snapshot());
4717    }
4718
4719    // -- mouse hold-tracking --------------------------------------------------
4720    //
4721    // These tests drive the tracked arms directly with view-local positions, as
4722    // the pump's Deferred::MouseTrack apply does (the capture itself is
4723    // unit-tested in capture::tests; here we verify the editor's loop bodies).
4724
4725    use crate::event::{MouseButtons, MouseEvent, MouseEventFlags, MouseWheel};
4726
4727    fn left_mouse(x: i32, y: i32) -> MouseEvent {
4728        MouseEvent {
4729            position: Point::new(x, y),
4730            buttons: MouseButtons {
4731                left: true,
4732                ..Default::default()
4733            },
4734            ..Default::default()
4735        }
4736    }
4737
4738    fn mouse_down_at(x: i32, y: i32) -> Event {
4739        Event::MouseDown(left_mouse(x, y))
4740    }
4741
4742    fn mouse_move_at(x: i32, y: i32) -> Event {
4743        Event::MouseMove(left_mouse(x, y))
4744    }
4745
4746    fn mouse_auto_at(x: i32, y: i32) -> Event {
4747        Event::MouseAuto(left_mouse(x, y))
4748    }
4749
4750    fn mouse_up_at(x: i32, y: i32) -> Event {
4751        Event::MouseUp(MouseEvent {
4752            position: Point::new(x, y),
4753            ..Default::default()
4754        })
4755    }
4756
4757    fn middle_down_at(x: i32, y: i32) -> Event {
4758        Event::MouseDown(MouseEvent {
4759            position: Point::new(x, y),
4760            buttons: MouseButtons {
4761                middle: true,
4762                ..Default::default()
4763            },
4764            ..Default::default()
4765        })
4766    }
4767
4768    /// A mouse-wheel event (crossterm ScrollUp/Down → `Event::MouseWheel`).
4769    fn wheel_down_at(x: i32, y: i32, wheel: MouseWheel) -> Event {
4770        Event::MouseWheel(MouseEvent {
4771            position: Point::new(x, y),
4772            wheel,
4773            ..Default::default()
4774        })
4775    }
4776
4777    /// Stamp the editor with a fresh ViewId (as Group::insert would do).
4778    fn give_id(e: &mut Editor) -> ViewId {
4779        let id = ViewId::next();
4780        e.state.id = Some(id);
4781        id
4782    }
4783
4784    /// A 40×10 editor holding 15 one-word lines (`line00\n` … `line14\n`,
4785    /// 7 bytes each) — tall enough to vertical-scroll (limit.y = 16 > 10).
4786    fn tall_ed() -> Editor {
4787        let mut e = ed();
4788        let text: String = (0..15).map(|i| format!("line{i:02}\n")).collect();
4789        insert(&mut e, &text);
4790        e.set_cur_ptr_core(0, 0);
4791        e
4792    }
4793
4794    /// A left press on an inserted editor: the first iteration positions the
4795    /// cursor, the track state carries the select mode with `SM_EXTEND` set, and
4796    /// the push-capture deferred names this editor's id.
4797    #[test]
4798    fn track_mouse_down_arms_select_capture() {
4799        let mut e = ed();
4800        insert(&mut e, "hello world");
4801        let id = give_id(&mut e);
4802
4803        let mut cx = Cx::new();
4804        let mut ev = mouse_down_at(2, 0);
4805        {
4806            let mut ctx = cx.ctx();
4807            e.handle_event(&mut ev, &mut ctx);
4808        }
4809        assert!(ev.is_nothing(), "MouseDown consumed");
4810        assert_eq!(e.cur_ptr, 2, "first iteration: setCurPtr(getMousePtr)");
4811        assert_eq!(
4812            e.track,
4813            Some(EditorTrack::Select {
4814                select_mode: SM_EXTEND
4815            }),
4816            "track carries selectMode |= smExtend after the first iteration"
4817        );
4818        let pushes: Vec<_> = cx
4819            .deferred
4820            .iter()
4821            .filter_map(|d| match d {
4822                Deferred::PushCapture(h) => Some(h.view()),
4823                _ => None,
4824            })
4825            .collect();
4826        assert_eq!(pushes, vec![Some(id)], "one PushCapture naming the editor");
4827    }
4828
4829    /// A double-click press seeds word-granular mode into the live track select
4830    /// mode, which persists across drag iterations for a word-granular drag.
4831    #[test]
4832    fn track_double_click_persists_sm_double() {
4833        let mut e = ed();
4834        insert(&mut e, "hello world");
4835        give_id(&mut e);
4836
4837        let mut cx = Cx::new();
4838        let mut ev = Event::MouseDown(MouseEvent {
4839            position: Point::new(1, 0),
4840            buttons: MouseButtons {
4841                left: true,
4842                ..Default::default()
4843            },
4844            flags: MouseEventFlags {
4845                double_click: true,
4846                ..Default::default()
4847            },
4848            ..Default::default()
4849        });
4850        {
4851            let mut ctx = cx.ctx();
4852            e.handle_event(&mut ev, &mut ctx);
4853        }
4854        assert_eq!(
4855            e.track,
4856            Some(EditorTrack::Select {
4857                select_mode: SM_DOUBLE | SM_EXTEND
4858            }),
4859            "smDouble persists in the live selectMode"
4860        );
4861    }
4862
4863    /// A move while drag-tracking extends the selection over the real buffer text
4864    /// and does NOT scroll.
4865    #[test]
4866    fn track_move_extends_selection() {
4867        let mut e = ed();
4868        insert(&mut e, "hello world");
4869        give_id(&mut e);
4870
4871        let mut cx = Cx::new();
4872        let mut ev = mouse_down_at(2, 0);
4873        {
4874            let mut ctx = cx.ctx();
4875            e.handle_event(&mut ev, &mut ctx);
4876        }
4877
4878        let mut ev = mouse_move_at(8, 0);
4879        {
4880            let mut ctx = cx.ctx();
4881            e.handle_event(&mut ev, &mut ctx);
4882        }
4883        assert!(ev.is_nothing(), "tracked move consumed");
4884        assert_eq!((e.sel_start, e.sel_end), (2, 8), "selection 2..8");
4885        assert_eq!(&text(&e)[2..8], "llo wo", "selection covers the real text");
4886        assert_eq!(e.cur_ptr, 8, "cursor at the drag position");
4887        assert_eq!(e.delta, Point::new(0, 0), "a plain move never scrolls");
4888        assert!(e.track.is_some(), "still tracking after the move");
4889    }
4890
4891    /// Auto-repeat below the view edge-scrolls down by one THEN extends the
4892    /// selection to the post-scroll mouse position (the unconditional cursor-move
4893    /// tail).
4894    #[test]
4895    fn track_auto_below_edge_scrolls_then_extends() {
4896        let mut e = tall_ed();
4897        give_id(&mut e);
4898
4899        // Down on row 5 (line05, offset 35).
4900        let mut cx = Cx::new();
4901        let mut ev = mouse_down_at(0, 5);
4902        {
4903            let mut ctx = cx.ctx();
4904            e.handle_event(&mut ev, &mut ctx);
4905        }
4906        assert_eq!(e.cur_ptr, 35);
4907
4908        // Auto at y = 10 (== size.y, out of bounds below): scroll down one,
4909        // then setCurPtr at the clamped row 9 + new delta.y 1 = line 10.
4910        let mut ev = mouse_auto_at(0, 10);
4911        {
4912            let mut ctx = cx.ctx();
4913            e.handle_event(&mut ev, &mut ctx);
4914        }
4915        assert!(ev.is_nothing(), "tracked auto consumed");
4916        assert_eq!(e.delta.y, 1, "scrolled down one row");
4917        assert_eq!(
4918            (e.sel_start, e.sel_end),
4919            (35, 70),
4920            "selection extended to the start of line10 (post-scroll getMousePtr)"
4921        );
4922    }
4923
4924    /// Auto-repeat above the view edge-scrolls up by one then extends the
4925    /// selection backwards.
4926    #[test]
4927    fn track_auto_above_edge_scrolls_then_extends() {
4928        let mut e = tall_ed();
4929        give_id(&mut e);
4930        e.scroll_to_core(0, 3); // viewport starts at line 3
4931
4932        // Down on view row 2 = buffer line 5 (offset 35).
4933        let mut cx = Cx::new();
4934        let mut ev = mouse_down_at(0, 2);
4935        {
4936            let mut ctx = cx.ctx();
4937            e.handle_event(&mut ev, &mut ctx);
4938        }
4939        assert_eq!(e.cur_ptr, 35);
4940
4941        // Auto at y = -1 (out of bounds above): delta.y 3 → 2, then setCurPtr
4942        // at clamped row 0 + delta.y 2 = line 2 (offset 14).
4943        let mut ev = mouse_auto_at(0, -1);
4944        {
4945            let mut ctx = cx.ctx();
4946            e.handle_event(&mut ev, &mut ctx);
4947        }
4948        assert!(ev.is_nothing(), "tracked auto consumed");
4949        assert_eq!(e.delta.y, 2, "scrolled up one row");
4950        assert_eq!(
4951            (e.sel_start, e.sel_end),
4952            (14, 35),
4953            "selection extended backwards to the start of line02"
4954        );
4955    }
4956
4957    /// A mouse wheel during the drag-select hold forwards to BOTH scroll bars (via
4958    /// the mouse-track deferred effect), self-posts a delta-sync (the bar's change
4959    /// notification would otherwise be swallowed by the modal capture), and still
4960    /// runs the unconditional cursor-move tail.
4961    #[test]
4962    fn track_wheel_in_hold_forwards_to_bars_and_syncs() {
4963        let hbar = ViewId::next();
4964        let vbar = ViewId::next();
4965        let mut e = Editor::new(Rect::new(0, 0, 40, 10), Some(hbar), Some(vbar), None, 1024);
4966        insert(&mut e, "hello world");
4967        let id = give_id(&mut e);
4968
4969        let mut cx = Cx::new();
4970        let mut ev = mouse_down_at(2, 0);
4971        {
4972            let mut ctx = cx.ctx();
4973            e.handle_event(&mut ev, &mut ctx);
4974        }
4975
4976        // The wheel arrives view-localized via the capture's wheel mask.
4977        let mut cx = Cx::new();
4978        let mut ev = wheel_down_at(8, 0, MouseWheel::Down);
4979        {
4980            let mut ctx = cx.ctx();
4981            e.handle_event(&mut ev, &mut ctx);
4982        }
4983        assert!(ev.is_nothing(), "wheel-in-hold consumed");
4984        // Forwarded to the v-bar then the h-bar (C++ order), wheel payload intact.
4985        let forwards: Vec<_> = cx
4986            .deferred
4987            .iter()
4988            .filter_map(|d| match d {
4989                Deferred::MouseTrack {
4990                    view,
4991                    event: Event::MouseWheel(m),
4992                } if m.wheel == MouseWheel::Down => Some(*view),
4993                _ => None,
4994            })
4995            .collect();
4996        assert_eq!(forwards, vec![vbar, hbar], "wheel forwarded to both bars");
4997        assert!(
4998            cx.deferred.iter().any(|d| matches!(
4999                d,
5000                Deferred::ScrollSync { target, h, v }
5001                    if *target == id && *h == Some(hbar) && *v == Some(vbar)
5002            )),
5003            "ScrollSync self-posted (the swallowed-broadcast workaround)"
5004        );
5005        // The unconditional body still ran: selection extended to the wheel pos.
5006        assert_eq!((e.sel_start, e.sel_end), (2, 8), "setCurPtr tail ran");
5007    }
5008
5009    /// A mouse wheel with NO hold in flight falls through unconsumed — the
5010    /// editor's event mask excludes the wheel outside a hold.
5011    #[test]
5012    fn track_wheel_outside_hold_falls_through() {
5013        let mut e = ed();
5014        insert(&mut e, "hello world");
5015        give_id(&mut e);
5016        let cur_before = e.cur_ptr;
5017
5018        let mut cx = Cx::new();
5019        let mut ev = wheel_down_at(3, 0, MouseWheel::Up);
5020        {
5021            let mut ctx = cx.ctx();
5022            e.handle_event(&mut ev, &mut ctx);
5023        }
5024        assert!(!ev.is_nothing(), "untracked wheel falls through");
5025        assert_eq!(e.cur_ptr, cur_before, "no cursor positioning from a wheel");
5026        assert!(cx.deferred.is_empty(), "nothing armed, nothing forwarded");
5027    }
5028
5029    /// A middle-button press arms the pan track: the mouse position is recorded
5030    /// and the capture pushed, but nothing scrolls on the press itself — the
5031    /// cursor and selection are untouched.
5032    #[test]
5033    fn track_middle_down_arms_pan() {
5034        let mut e = tall_ed();
5035        let id = give_id(&mut e);
5036        let cur_before = e.cur_ptr;
5037
5038        let mut cx = Cx::new();
5039        let mut ev = middle_down_at(5, 5);
5040        {
5041            let mut ctx = cx.ctx();
5042            e.handle_event(&mut ev, &mut ctx);
5043        }
5044        assert!(ev.is_nothing(), "middle down consumed");
5045        assert_eq!(
5046            e.track,
5047            Some(EditorTrack::Pan {
5048                last: Point::new(5, 5),
5049                moved: false,
5050            }),
5051            "pan track armed with lastMouse"
5052        );
5053        assert_eq!(e.cur_ptr, cur_before, "no cursor change on the press");
5054        assert!(!e.has_selection(), "no selection from a pan press");
5055        let pushes: Vec<_> = cx
5056            .deferred
5057            .iter()
5058            .filter_map(|d| match d {
5059                Deferred::PushCapture(h) => Some(h.view()),
5060                _ => None,
5061            })
5062            .collect();
5063        assert_eq!(pushes, vec![Some(id)], "one PushCapture naming the editor");
5064    }
5065
5066    /// A move while panning scrolls by the mouse delta and never touches the
5067    /// cursor or selection — the track-kind guard in the other direction.
5068    #[test]
5069    fn track_pan_move_scrolls_without_selection() {
5070        let mut e = tall_ed();
5071        give_id(&mut e);
5072        let cur_before = e.cur_ptr;
5073
5074        let mut cx = Cx::new();
5075        let mut ev = middle_down_at(5, 5);
5076        {
5077            let mut ctx = cx.ctx();
5078            e.handle_event(&mut ev, &mut ctx);
5079        }
5080
5081        // Move up-left by (2,1): d = delta(0,0) + last(5,5) − mouse(3,4) = (2,1).
5082        let mut ev = mouse_move_at(3, 4);
5083        {
5084            let mut ctx = cx.ctx();
5085            e.handle_event(&mut ev, &mut ctx);
5086        }
5087        assert!(ev.is_nothing(), "pan move consumed");
5088        assert_eq!(e.delta, Point::new(2, 1), "scrolled by the mouse delta");
5089        assert_eq!(
5090            e.track,
5091            Some(EditorTrack::Pan {
5092                last: Point::new(3, 4),
5093                // A real move: this is a pan, so a release here must not paste.
5094                moved: true,
5095            }),
5096            "lastMouse updated"
5097        );
5098        assert_eq!(e.cur_ptr, cur_before, "pan never moves the cursor");
5099        assert!(!e.has_selection(), "pan never selects");
5100    }
5101
5102    /// A mouse wheel during the pan hold runs the same pan body — no scroll-bar
5103    /// forwarding.
5104    #[test]
5105    fn track_pan_wheel_tick_pans() {
5106        let mut e = tall_ed();
5107        give_id(&mut e);
5108
5109        let mut cx = Cx::new();
5110        let mut ev = middle_down_at(5, 5);
5111        {
5112            let mut ctx = cx.ctx();
5113            e.handle_event(&mut ev, &mut ctx);
5114        }
5115
5116        let mut cx = Cx::new();
5117        let mut ev = wheel_down_at(4, 3, MouseWheel::Up);
5118        {
5119            let mut ctx = cx.ctx();
5120            e.handle_event(&mut ev, &mut ctx);
5121        }
5122        assert!(ev.is_nothing(), "pan wheel tick consumed");
5123        // d = delta(0,0) + last(5,5) − mouse(4,3) = (1,2).
5124        assert_eq!(e.delta, Point::new(1, 2), "wheel tick pans by the delta");
5125        assert!(
5126            !cx.deferred
5127                .iter()
5128                .any(|d| matches!(d, Deferred::MouseTrack { .. })),
5129            "no scrollbar forwarding from the pan body"
5130        );
5131    }
5132
5133    /// A release clears the track (both holds just end; there is no post-hold
5134    /// work).
5135    #[test]
5136    fn track_up_clears_track() {
5137        for arm in [mouse_down_at(2, 0), middle_down_at(2, 0)] {
5138            let mut e = tall_ed();
5139            give_id(&mut e);
5140
5141            let mut cx = Cx::new();
5142            let mut ev = arm;
5143            {
5144                let mut ctx = cx.ctx();
5145                e.handle_event(&mut ev, &mut ctx);
5146            }
5147            assert!(e.track.is_some(), "armed");
5148
5149            let mut ev = mouse_up_at(2, 0);
5150            {
5151                let mut ctx = cx.ctx();
5152                e.handle_event(&mut ev, &mut ctx);
5153            }
5154            assert!(ev.is_nothing(), "tracked up consumed");
5155            assert!(e.track.is_none(), "track cleared on MouseUp");
5156        }
5157    }
5158
5159    /// Stray `MouseUp` / `MouseMove` / `MouseAuto` with no track in flight fall
5160    /// through unconsumed (the tracking guard).
5161    #[test]
5162    fn track_stray_events_fall_through() {
5163        let mut e = tall_ed();
5164        give_id(&mut e);
5165
5166        for mut ev in [mouse_up_at(2, 0), mouse_move_at(2, 0), mouse_auto_at(2, 0)] {
5167            let mut cx = Cx::new();
5168            {
5169                let mut ctx = cx.ctx();
5170                e.handle_event(&mut ev, &mut ctx);
5171            }
5172            assert!(!ev.is_nothing(), "stray {ev:?} falls through unconsumed");
5173            assert!(e.track.is_none(), "no track armed by a stray event");
5174        }
5175    }
5176
5177    /// `MouseDown` on an editor without an id (uninserted): single-shot cursor
5178    /// positioning, no track, no capture — the faithful fallback.
5179    #[test]
5180    fn track_mouse_down_without_id_single_shot() {
5181        let mut e = ed();
5182        insert(&mut e, "hello world");
5183        // No id assigned.
5184        let mut cx = Cx::new();
5185        let mut ev = mouse_down_at(2, 0);
5186        {
5187            let mut ctx = cx.ctx();
5188            e.handle_event(&mut ev, &mut ctx);
5189        }
5190        assert!(ev.is_nothing(), "MouseDown still consumed");
5191        assert_eq!(e.cur_ptr, 2, "cursor positioned single-shot");
5192        assert!(e.track.is_none(), "no track without an id");
5193        assert!(
5194            cx.deferred.is_empty(),
5195            "no capture pushed for id-less editor"
5196        );
5197    }
5198
5199    /// The forwarded track events reach the inner Editor through a FileEditor
5200    /// wrapper (the mouse-track deferred apply calls the wrapper's handle_event,
5201    /// which delegates to the editor — the edit-window hosting path).
5202    ///
5203    /// NOTE: this drives handle_event directly (handler-level), bypassing the
5204    /// pump's Deferred::MouseTrack drain; the deferred-apply path
5205    /// (group.find_mut + handle_event) is covered by the capture tests in
5206    /// capture::tests and the scrollbar pump round-trip in program.rs.
5207    #[test]
5208    fn track_through_file_editor_delegation() {
5209        let mut fe = FileEditor::new(Rect::new(0, 0, 40, 10), None, None, None, None);
5210        fe.editor.insert_text_core(b"hello world", false);
5211        fe.editor.set_cur_ptr_core(0, 0);
5212        let id = ViewId::next();
5213        fe.editor.state.id = Some(id);
5214
5215        let mut cx = Cx::new();
5216        let mut ev = mouse_down_at(2, 0);
5217        {
5218            let mut ctx = cx.ctx();
5219            View::handle_event(&mut fe, &mut ev, &mut ctx);
5220        }
5221        assert!(ev.is_nothing(), "MouseDown consumed through the wrapper");
5222        assert!(fe.editor.track.is_some(), "inner editor armed");
5223        let pushes: Vec<_> = cx
5224            .deferred
5225            .iter()
5226            .filter_map(|d| match d {
5227                Deferred::PushCapture(h) => Some(h.view()),
5228                _ => None,
5229            })
5230            .collect();
5231        assert_eq!(pushes, vec![Some(id)], "capture names the wrapper's id");
5232
5233        let mut ev = mouse_move_at(8, 0);
5234        {
5235            let mut ctx = cx.ctx();
5236            View::handle_event(&mut fe, &mut ev, &mut ctx);
5237        }
5238        assert_eq!(
5239            (fe.editor.sel_start, fe.editor.sel_end),
5240            (2, 8),
5241            "drag-select body ran on the inner editor via delegation"
5242        );
5243    }
5244
5245    // -- find/replace dialog layout snapshots ---------------------------------
5246
5247    /// Render the Find dialog to verify its layout.
5248    #[test]
5249    fn find_dialog_layout() {
5250        use crate::backend::{HeadlessBackend, Renderer};
5251        use crate::data::FieldValue;
5252        use crate::dialog::Dialog;
5253        use crate::screen::Buffer;
5254        use crate::theme::Theme;
5255        use crate::view::{DrawCtx, Rect, View};
5256        use crate::widgets::{
5257            Button, ButtonFlags, CheckBoxes, InputLine, Label, LimitMode, THistory,
5258        };
5259
5260        let mut d = Dialog::new(Rect::new(0, 0, 38, 12), Some("Find".into()));
5261        {
5262            let opts = &mut d.state_mut().options;
5263            opts.center_x = true;
5264            opts.center_y = true;
5265        }
5266
5267        let mut il = InputLine::new(Rect::new(3, 3, 32, 4), 81, None, LimitMode::MaxBytes);
5268        il.set_value(FieldValue::Text("hello".into()));
5269        let find_id = d.insert_child(Box::new(il));
5270        d.insert_child(Box::new(Label::new(
5271            Rect::new(2, 2, 15, 3),
5272            "~T~ext to find",
5273            Some(find_id),
5274        )));
5275        d.insert_child(Box::new(THistory::new(
5276            Rect::new(32, 3, 35, 4),
5277            find_id,
5278            10,
5279        )));
5280
5281        let mut cb = CheckBoxes::new(
5282            Rect::new(3, 5, 35, 7),
5283            vec!["~C~ase sensitive".into(), "~W~hole words only".into()],
5284        );
5285        cb.cluster.value = 0x0001; // case sensitive pre-selected
5286        d.insert_child(Box::new(cb));
5287
5288        d.insert_child(Box::new(Button::new(
5289            Rect::new(14, 9, 24, 11),
5290            "O~K~",
5291            crate::command::Command::OK,
5292            ButtonFlags {
5293                default: true,
5294                ..Default::default()
5295            },
5296        )));
5297        d.insert_child(Box::new(Button::new(
5298            Rect::new(26, 9, 36, 11),
5299            "Cancel",
5300            crate::command::Command::CANCEL,
5301            ButtonFlags::new(),
5302        )));
5303
5304        let theme = Theme::classic_blue();
5305        let (backend, screen) = HeadlessBackend::new(38, 12);
5306        let mut r = Renderer::new(Box::new(backend));
5307        r.render(|buf: &mut Buffer| {
5308            let bounds = d.state().get_bounds();
5309            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
5310            d.draw(&mut dc);
5311        });
5312        insta::assert_snapshot!(screen.snapshot());
5313    }
5314
5315    /// Render the Replace dialog to verify its layout.
5316    #[test]
5317    fn replace_dialog_layout() {
5318        use crate::backend::{HeadlessBackend, Renderer};
5319        use crate::data::FieldValue;
5320        use crate::dialog::Dialog;
5321        use crate::screen::Buffer;
5322        use crate::theme::Theme;
5323        use crate::view::{DrawCtx, Rect, View};
5324        use crate::widgets::{
5325            Button, ButtonFlags, CheckBoxes, InputLine, Label, LimitMode, THistory,
5326        };
5327
5328        let mut d = Dialog::new(Rect::new(0, 0, 40, 16), Some("Replace".into()));
5329        {
5330            let opts = &mut d.state_mut().options;
5331            opts.center_x = true;
5332            opts.center_y = true;
5333        }
5334
5335        let mut il1 = InputLine::new(Rect::new(3, 3, 34, 4), 81, None, LimitMode::MaxBytes);
5336        il1.set_value(FieldValue::Text("foo".into()));
5337        let find_id = d.insert_child(Box::new(il1));
5338        d.insert_child(Box::new(Label::new(
5339            Rect::new(2, 2, 15, 3),
5340            "~T~ext to find",
5341            Some(find_id),
5342        )));
5343        d.insert_child(Box::new(THistory::new(
5344            Rect::new(34, 3, 37, 4),
5345            find_id,
5346            10,
5347        )));
5348
5349        let mut il2 = InputLine::new(Rect::new(3, 6, 34, 7), 81, None, LimitMode::MaxBytes);
5350        il2.set_value(FieldValue::Text("bar".into()));
5351        let replace_id = d.insert_child(Box::new(il2));
5352        d.insert_child(Box::new(Label::new(
5353            Rect::new(2, 5, 12, 6),
5354            "~N~ew text",
5355            Some(replace_id),
5356        )));
5357        d.insert_child(Box::new(THistory::new(
5358            Rect::new(34, 6, 37, 7),
5359            replace_id,
5360            11,
5361        )));
5362
5363        let mut cb = CheckBoxes::new(
5364            Rect::new(3, 8, 37, 12),
5365            vec![
5366                "~C~ase sensitive".into(),
5367                "~W~hole words only".into(),
5368                "~P~rompt on replace".into(),
5369                "~R~eplace all".into(),
5370            ],
5371        );
5372        cb.cluster.value = 0x0005; // case + prompt pre-selected
5373        d.insert_child(Box::new(cb));
5374
5375        d.insert_child(Box::new(Button::new(
5376            Rect::new(17, 13, 27, 15),
5377            "O~K~",
5378            crate::command::Command::OK,
5379            ButtonFlags {
5380                default: true,
5381                ..Default::default()
5382            },
5383        )));
5384        d.insert_child(Box::new(Button::new(
5385            Rect::new(28, 13, 38, 15),
5386            "Cancel",
5387            crate::command::Command::CANCEL,
5388            ButtonFlags::new(),
5389        )));
5390
5391        let theme = Theme::classic_blue();
5392        let (backend, screen) = HeadlessBackend::new(40, 16);
5393        let mut r = Renderer::new(Box::new(backend));
5394        r.render(|buf: &mut Buffer| {
5395            let bounds = d.state().get_bounds();
5396            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
5397            d.draw(&mut dc);
5398        });
5399        insta::assert_snapshot!(screen.snapshot());
5400    }
5401
5402    // -- internal-clipboard tests ---------------------------------------------
5403
5404    /// `insert_from` inserts another editor's bytes into self (non-clipboard dest).
5405    #[test]
5406    fn insert_from_copies_bytes() {
5407        let mut a = ed();
5408        insert(&mut a, "hello");
5409        // Select the "hello" content.
5410        a.set_select_core(0, 5, false);
5411        let data = a.selection_bytes();
5412        assert_eq!(data, b"hello");
5413
5414        let mut b = ed();
5415        let mut cx = Cx::new();
5416        {
5417            let mut ctx = cx.ctx();
5418            let ok = b.insert_from(&data, &mut ctx);
5419            assert!(ok);
5420        }
5421        assert_eq!(text(&b), "hello");
5422    }
5423
5424    /// When `is_clipboard = true`, `insert_from` selects the inserted content.
5425    #[test]
5426    fn clipboard_editor_receive_selects_inserted_text() {
5427        let mut e = ed();
5428        e.is_clipboard = true;
5429        let mut cx = Cx::new();
5430        {
5431            let mut ctx = cx.ctx();
5432            e.insert_from(b"world", &mut ctx);
5433        }
5434        assert!(
5435            e.has_selection(),
5436            "clipboard editor selects after insert_from"
5437        );
5438        assert_eq!(e.selection_bytes(), b"world");
5439    }
5440
5441    /// `clip_copy` with an internal clipboard queues `ClipboardEditorReceive`, not `SetClipboard`.
5442    #[test]
5443    fn clip_copy_internal_routes_to_deferred_receive() {
5444        use crate::view::ViewId;
5445        // Mint a fake clipboard editor id.
5446        let fake_clipboard_id = ViewId::next();
5447        let mut e = ed();
5448        insert(&mut e, "hello");
5449        e.set_select_core(0, 5, false);
5450        let mut cx = Cx::new();
5451        {
5452            let mut ctx = cx.ctx();
5453            ctx.set_clipboard_snapshot(Some(fake_clipboard_id), false);
5454            assert!(e.clip_copy(&mut ctx));
5455        }
5456        assert!(
5457            cx.deferred.iter().any(|d| matches!(
5458                d,
5459                Deferred::ClipboardEditorReceive { clipboard_id, data }
5460                if *clipboard_id == fake_clipboard_id && data == b"hello"
5461            )),
5462            "clip_copy with internal clipboard queues ClipboardEditorReceive"
5463        );
5464        assert!(
5465            !cx.deferred
5466                .iter()
5467                .any(|d| matches!(d, Deferred::SetClipboard(..))),
5468            "clip_copy with internal clipboard must NOT queue SetClipboard"
5469        );
5470    }
5471
5472    /// `clip_paste` with an internal clipboard queues `ClipboardEditorPaste`, not `EditorPaste`.
5473    #[test]
5474    fn clip_paste_internal_routes_to_deferred_paste() {
5475        use crate::view::ViewId;
5476        let fake_clipboard_id = ViewId::next();
5477        // The editor must have an id to be addressable.
5478        let mut group = Group::new(Rect::new(0, 0, 40, 10));
5479        let id = group.insert(Box::new(ed()));
5480        let mut cx = Cx::new();
5481        {
5482            let mut ctx = cx.ctx();
5483            ctx.set_clipboard_snapshot(Some(fake_clipboard_id), true);
5484            let v = group.find_mut(id).unwrap();
5485            let e = v.as_any_mut().unwrap().downcast_mut::<Editor>().unwrap();
5486            e.clip_paste(&mut ctx);
5487        }
5488        assert!(
5489            cx.deferred.iter().any(|d| matches!(
5490                d,
5491                Deferred::ClipboardEditorPaste { dest_id, clipboard_id }
5492                if *dest_id == id && *clipboard_id == fake_clipboard_id
5493            )),
5494            "clip_paste with internal clipboard queues ClipboardEditorPaste"
5495        );
5496        assert!(
5497            !cx.deferred
5498                .iter()
5499                .any(|d| matches!(d, Deferred::EditorPaste(..))),
5500            "clip_paste with internal clipboard must NOT queue EditorPaste"
5501        );
5502    }
5503
5504    /// The clipboard editor skips cut/copy/paste commands in `update_commands`.
5505    #[test]
5506    fn update_commands_clipboard_editor_skips_cut_copy_paste() {
5507        let mut e = ed();
5508        e.is_clipboard = true;
5509        // Give it a selection (so it WOULD enable CUT/COPY/CLEAR if it weren't a clipboard).
5510        e.state.state.active = true;
5511        insert(&mut e, "abc");
5512        e.set_select_core(0, 3, false);
5513        let mut cx = Cx::new();
5514        {
5515            let mut ctx = cx.ctx();
5516            e.update_commands(&mut ctx);
5517        }
5518        // CUT and COPY should NOT appear in deferred (skipped for clipboard editor).
5519        assert!(
5520            !cx.deferred.iter().any(|d| matches!(
5521                d,
5522                Deferred::EnableCommand(c) if *c == Command::CUT || *c == Command::COPY || *c == Command::PASTE
5523            )),
5524            "clipboard editor must not enable CUT, COPY, or PASTE"
5525        );
5526        // CLEAR should still be enabled (has_selection AND active).
5527        assert!(
5528            cx.deferred.iter().any(|d| matches!(
5529                d,
5530                Deferred::EnableCommand(c) if *c == Command::CLEAR
5531            )),
5532            "CLEAR should be enabled for active clipboard editor with selection"
5533        );
5534    }
5535
5536    #[test]
5537    fn set_modal_data_loads_find_shape() {
5538        use crate::data::FieldValue;
5539        let mut e = Editor::new(crate::view::Rect::new(0, 0, 20, 10), None, None, None, 0);
5540        e.replace_str = "keep".to_string();
5541        e.set_modal_data(FieldValue::List(vec![
5542            FieldValue::Text("needle".into()),
5543            FieldValue::Bits(0x0003),
5544        ]));
5545        assert_eq!(e.find_str(), "needle");
5546        assert_eq!(e.editor_flags(), 0x0003);
5547        // Find shape must NOT touch replace_str.
5548        assert_eq!(e.replace_str(), "keep");
5549    }
5550
5551    #[test]
5552    fn set_modal_data_loads_replace_shape() {
5553        use crate::data::FieldValue;
5554        let mut e = Editor::new(crate::view::Rect::new(0, 0, 20, 10), None, None, None, 0);
5555        e.set_modal_data(FieldValue::List(vec![
5556            FieldValue::Text("needle".into()),
5557            FieldValue::Text("thread".into()),
5558            FieldValue::Bits(0x000F | EF_DO_REPLACE as u32),
5559        ]));
5560        assert_eq!(e.find_str(), "needle");
5561        assert_eq!(e.replace_str(), "thread");
5562        assert_eq!(e.editor_flags(), 0x000F | EF_DO_REPLACE);
5563    }
5564
5565    // -- X11 PRIMARY selection: middle-click pastes, middle-drag pans ---------
5566    //
5567    // The middle button is overloaded. The two gestures are told apart by
5568    // MOVEMENT: a press that releases where it started is the X11 paste; a press
5569    // that moves is the Turbo Vision pan (teditor1.cpp:540-551). Pan therefore
5570    // starts one event later than it used to, which no user can perceive.
5571
5572    fn primary_pastes(deferred: &[Deferred]) -> Vec<ViewId> {
5573        deferred
5574            .iter()
5575            .filter_map(|d| match d {
5576                Deferred::EditorPastePrimary(i) => Some(*i),
5577                _ => None,
5578            })
5579            .collect()
5580    }
5581
5582    fn primary_writes(deferred: &[Deferred]) -> Vec<String> {
5583        deferred
5584            .iter()
5585            .filter_map(|d| match d {
5586                Deferred::SetPrimary(t) => Some(t.clone()),
5587                _ => None,
5588            })
5589            .collect()
5590    }
5591
5592    /// Press and release without moving = the paste gesture.
5593    #[test]
5594    fn middle_click_without_movement_pastes_the_primary_selection() {
5595        let mut e = tall_ed();
5596        let id = give_id(&mut e);
5597        let delta_before = e.delta;
5598
5599        let mut cx = Cx::new();
5600        let mut ev = middle_down_at(5, 5);
5601        {
5602            let mut ctx = cx.ctx();
5603            e.handle_event(&mut ev, &mut ctx);
5604        }
5605        let mut ev = mouse_up_at(5, 5);
5606        {
5607            let mut ctx = cx.ctx();
5608            e.handle_event(&mut ev, &mut ctx);
5609        }
5610
5611        assert_eq!(primary_pastes(&cx.deferred), vec![id]);
5612        assert_eq!(e.delta, delta_before, "a paste click must not scroll");
5613        assert_eq!(e.track, None, "track released");
5614    }
5615
5616    /// Press, move, release = the pan gesture, and NO paste.
5617    #[test]
5618    fn middle_drag_pans_and_does_not_paste() {
5619        let mut e = tall_ed();
5620        let _id = give_id(&mut e);
5621
5622        let mut cx = Cx::new();
5623        let mut ev = middle_down_at(5, 5);
5624        {
5625            let mut ctx = cx.ctx();
5626            e.handle_event(&mut ev, &mut ctx);
5627        }
5628        let mut ev = mouse_move_at(5, 3);
5629        {
5630            let mut ctx = cx.ctx();
5631            e.handle_event(&mut ev, &mut ctx);
5632        }
5633        let delta_after_move = e.delta;
5634        let mut ev = mouse_up_at(5, 3);
5635        {
5636            let mut ctx = cx.ctx();
5637            e.handle_event(&mut ev, &mut ctx);
5638        }
5639
5640        assert!(
5641            primary_pastes(&cx.deferred).is_empty(),
5642            "a drag is a pan, not a paste"
5643        );
5644        assert_ne!(delta_after_move, Point::new(0, 0), "the move panned");
5645    }
5646
5647    /// An auto-repeat tick at the HELD position is not movement — the C++ pan
5648    /// loop treats it as a no-op scroll, so a press held still then released is
5649    /// still a paste.
5650    #[test]
5651    fn an_auto_tick_at_the_held_position_is_not_movement() {
5652        let mut e = tall_ed();
5653        let id = give_id(&mut e);
5654
5655        let mut cx = Cx::new();
5656        let mut ev = middle_down_at(5, 5);
5657        {
5658            let mut ctx = cx.ctx();
5659            e.handle_event(&mut ev, &mut ctx);
5660        }
5661        let mut ev = mouse_auto_at(5, 5);
5662        {
5663            let mut ctx = cx.ctx();
5664            e.handle_event(&mut ev, &mut ctx);
5665        }
5666        let mut ev = mouse_up_at(5, 5);
5667        {
5668            let mut ctx = cx.ctx();
5669            e.handle_event(&mut ev, &mut ctx);
5670        }
5671
5672        assert_eq!(primary_pastes(&cx.deferred), vec![id]);
5673    }
5674
5675    /// Finishing a left-button sweep publishes the swept text as PRIMARY.
5676    #[test]
5677    fn finishing_a_drag_select_publishes_the_primary_selection() {
5678        let mut e = tall_ed();
5679        let _id = give_id(&mut e);
5680
5681        let mut cx = Cx::new();
5682        let mut ev = mouse_down_at(0, 0);
5683        {
5684            let mut ctx = cx.ctx();
5685            e.handle_event(&mut ev, &mut ctx);
5686        }
5687        let mut ev = mouse_move_at(3, 0);
5688        {
5689            let mut ctx = cx.ctx();
5690            e.handle_event(&mut ev, &mut ctx);
5691        }
5692        assert!(
5693            e.has_selection(),
5694            "precondition: the sweep selected something"
5695        );
5696        let expected = String::from_utf8(e.selection_bytes()).unwrap();
5697
5698        let mut ev = mouse_up_at(3, 0);
5699        {
5700            let mut ctx = cx.ctx();
5701            e.handle_event(&mut ev, &mut ctx);
5702        }
5703
5704        assert_eq!(primary_writes(&cx.deferred), vec![expected]);
5705    }
5706
5707    /// A click that selects nothing publishes nothing — otherwise every click
5708    /// would clobber the user's selection with "".
5709    #[test]
5710    fn a_click_without_a_sweep_publishes_no_primary_selection() {
5711        let mut e = tall_ed();
5712        let _id = give_id(&mut e);
5713
5714        let mut cx = Cx::new();
5715        let mut ev = mouse_down_at(2, 0);
5716        {
5717            let mut ctx = cx.ctx();
5718            e.handle_event(&mut ev, &mut ctx);
5719        }
5720        let mut ev = mouse_up_at(2, 0);
5721        {
5722            let mut ctx = cx.ctx();
5723            e.handle_event(&mut ev, &mut ctx);
5724        }
5725
5726        assert!(primary_writes(&cx.deferred).is_empty());
5727    }
5728}