tvision_rs/dialog/filedlg.rs
1//! The file-selection dialog family (documented on `FileDialog`).
2
3use core::cmp::Ordering;
4
5// ---------------------------------------------------------------------------
6// DirEntry
7// ---------------------------------------------------------------------------
8
9/// A (display-text, directory-path) pair for the directory tree pane.
10///
11/// Both fields are plain `String`s on the same allocation as the struct.
12///
13/// # Turbo Vision heritage
14/// Ports `TDirEntry` (`filedial.cpp`); its two heap-allocated `char*` fields
15/// become owned `String`s.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct DirEntry {
18 /// The text rendered by [`DirListBox`] for this entry.
19 ///
20 /// Built by `DirListBox::build_tree`: ancestor entries carry tree-glyph
21 /// prefixes (e.g. `" └─┬oetiker"`); the plain display name comes after
22 /// those glyphs. Typically not set by callers directly — construct via
23 /// [`DirEntry::new`] and let `build_tree` produce the decorated text.
24 pub display_text: String,
25 /// The absolute filesystem path this entry navigates to when selected.
26 ///
27 /// Used by the change-directory dialog when the user confirms a selection:
28 /// `ChDirDialog::handle_event` calls
29 /// [`DirListBox::focused_entry`] and reads `dir()` to navigate. Must be a
30 /// valid native path (no trailing separator required — the dialog normalizes
31 /// it); for the root entry use `"/"`.
32 pub directory: String,
33}
34
35impl DirEntry {
36 /// Build a `DirEntry` from any `(display_text, directory)` text pair.
37 ///
38 /// Use this when constructing entries for a custom dir-tree; in normal use
39 /// `DirListBox::new_directory` calls `build_tree` which produces decorated
40 /// entries automatically. `display_text` is what the list draws; `directory`
41 /// is the path navigated on selection.
42 pub fn new(display_text: impl Into<String>, directory: impl Into<String>) -> Self {
43 DirEntry {
44 display_text: display_text.into(),
45 directory: directory.into(),
46 }
47 }
48
49 /// Borrow the rendered display text, including any tree-glyph prefix.
50 ///
51 /// Read by `DirListBox::get_text` on every draw; do not use this to
52 /// extract a bare directory name — strip the glyph prefix or read
53 /// [`dir`](DirEntry::dir) instead.
54 pub fn text(&self) -> &str {
55 &self.display_text
56 }
57
58 /// Borrow the absolute filesystem path this entry represents.
59 ///
60 /// Read by `ChDirDialog::handle_event` (via `DirListBox::focused_entry`)
61 /// when the user confirms a directory change. The path has no trailing `/`.
62 pub fn dir(&self) -> &str {
63 &self.directory
64 }
65}
66
67// ---------------------------------------------------------------------------
68// DirCollection
69// ---------------------------------------------------------------------------
70
71/// An ordered list of [`DirEntry`] items used by [`DirListBox`].
72///
73/// A bare `Vec<DirEntry>` type alias — [`DirListBox`] only needs `push`, index,
74/// and `len`. In normal use you do not need to construct a `DirCollection`
75/// directly: call [`DirListBox::new_directory`] and it builds the list internally
76/// via `build_tree`. Use this alias when you need to pre-populate or inspect the
77/// dir-tree entries without going through `DirListBox`.
78///
79/// # Turbo Vision heritage
80/// Ports `TDirCollection` (`stddlg.h`), a heap pointer collection subclass;
81/// it collapses to a plain `Vec` because the general-purpose collection API
82/// (indexOf, remove, firstThat, …) is unused here.
83pub type DirCollection = Vec<DirEntry>;
84
85// ---------------------------------------------------------------------------
86// SearchRec
87// ---------------------------------------------------------------------------
88
89/// The directory-attribute bit of [`SearchRec::attr`] (`FA_DIREC = 0x10`).
90///
91/// Test `rec.attr & FA_DIREC != 0` to distinguish a directory entry from a
92/// plain file in a listing produced by [`FileList`]. This is the only DOS
93/// attribute bit used by the port; the rest are not set or inspected.
94pub const FA_DIREC: u8 = 0x10;
95
96/// A directory-listing file-metadata record.
97///
98/// `name` is an owned `String` and the struct derives `Clone`.
99///
100/// `attr`, `time`, and `size` are populated by `FileList::raw_from_fs` /
101/// `FileList::build_listing`: `size` is `meta.len()` (saturated to `i32`),
102/// `time` is the `modified()` mtime packed into the DOS `ftime` bitfield by
103/// `pack_dos_time`, and `attr` carries [`FA_DIREC`] for directories.
104///
105/// # Turbo Vision heritage
106/// Ports `TSearchRec` (`filedial.cpp`); its fixed-length `char name[]` (kept
107/// POD-copyable for the collection) becomes an owned `String`.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct SearchRec {
110 /// DOS file-attribute byte; only [`FA_DIREC`] (`0x10`) is examined here.
111 ///
112 /// Set to [`FA_DIREC`] for directories, `0` for plain files. The remaining
113 /// DOS attribute bits (archive, hidden, system, read-only, volume) are
114 /// not populated or tested in this port.
115 pub attr: u8,
116 /// Packed DOS `ftime` timestamp (`pack_dos_time` layout): high 16 bits are
117 /// the date (year-1980/month/day in bits 15–9/8–5/4–0), low 16 bits are
118 /// the time (hour/min/sec÷2 in bits 15–11/10–5/4–0). Times are UTC.
119 ///
120 /// Read by [`FileInfoPane`] to format the size/date line; synthesized by
121 /// `FileList::build_listing` via `pack_dos_time`.
122 pub time: i32,
123 /// File size in bytes, saturated to `i32::MAX` for files larger than 2 GiB.
124 ///
125 /// Displayed on the info pane's size/date line. Directories always carry
126 /// `size = 0`; the `".."` entry also carries `size = 0`.
127 pub size: i32,
128 /// The bare file or directory name — no path component, no trailing `/`.
129 ///
130 /// Use `rec.attr & FA_DIREC != 0` to detect directories. [`FileList`]'s
131 /// `get_text` appends `/` to directory names for display; the raw `name`
132 /// is what `FileList`'s incremental-search and the input-line broker use.
133 pub name: String,
134}
135
136// ---------------------------------------------------------------------------
137// FileCollection
138// ---------------------------------------------------------------------------
139
140/// The sort order for a directory listing: `".."` last, directories after plain
141/// files, then case-sensitive byte-order by name.
142///
143/// The sign of every branch matters — do not "tidy" it.
144///
145/// ```
146/// use tvision_rs::dialog::{SearchRec, search_rec_compare, FA_DIREC};
147/// use core::cmp::Ordering;
148///
149/// let a = SearchRec { attr: 0, time: 0, size: 0, name: "..".into() };
150/// let b = SearchRec { attr: 0, time: 0, size: 0, name: "foo".into() };
151/// assert_eq!(search_rec_compare(&a, &b), Ordering::Greater); // ".." sorts last
152/// ```
153pub fn search_rec_compare(a: &SearchRec, b: &SearchRec) -> Ordering {
154 // Equal names → Equal (mirrors the first strcmp returning 0).
155 if a.name == b.name {
156 return Ordering::Equal;
157 }
158 // key1 == ".." → positive (Greater means *after* in ascending order).
159 if a.name == ".." {
160 return Ordering::Greater;
161 }
162 // key2 == ".." → negative (Less).
163 if b.name == ".." {
164 return Ordering::Less;
165 }
166 let a_dir = a.attr & FA_DIREC != 0;
167 let b_dir = b.attr & FA_DIREC != 0;
168 // a is a directory, b is a plain file → a sorts after b.
169 if a_dir && !b_dir {
170 return Ordering::Greater;
171 }
172 // b is a directory, a is a plain file → a sorts before b.
173 if b_dir && !a_dir {
174 return Ordering::Less;
175 }
176 // Same kind — case-sensitive byte order.
177 a.name.cmp(&b.name)
178}
179
180/// A name-sorted list of [`SearchRec`] items.
181///
182/// The only real behaviour it carries is the sorted insert and its comparator
183/// ([`search_rec_compare`]). The sort order is: plain files alphabetically
184/// (case-sensitive), then directories alphabetically, then `".."` last.
185///
186/// # Turbo Vision heritage
187/// Ports `TFileCollection` (`filedial.cpp`), a sorted heap collection; here only
188/// the sorted insert survives, over a plain `Vec`.
189#[derive(Debug, Clone, Default, PartialEq, Eq)]
190pub struct FileCollection {
191 items: Vec<SearchRec>,
192}
193
194impl FileCollection {
195 /// Create an empty `FileCollection`.
196 pub fn new() -> Self {
197 FileCollection { items: Vec::new() }
198 }
199
200 /// Insert `rec` while keeping the list sorted by [`search_rec_compare`].
201 /// Duplicate names do not occur in a real directory listing.
202 pub fn insert(&mut self, rec: SearchRec) {
203 let pos = self
204 .items
205 .partition_point(|x| search_rec_compare(x, &rec) == Ordering::Less);
206 self.items.insert(pos, rec);
207 }
208
209 /// Borrow the record at `index`, or `None` when out of bounds (never panics).
210 ///
211 /// Used by `FileList` to fetch the entry at a given list position. Prefer
212 /// [`items`](FileCollection::items) and standard slice indexing when you need
213 /// to iterate; use `at` when you already have a positional index from the
214 /// list-viewer (e.g. the focused item).
215 pub fn at(&self, index: usize) -> Option<&SearchRec> {
216 self.items.get(index)
217 }
218
219 /// Number of records currently in the sorted listing.
220 ///
221 /// Mirrors the list-viewer's `range` after a [`FileList::read_directory`]
222 /// call. Use [`is_empty`](FileCollection::is_empty) to gate iteration.
223 pub fn len(&self) -> usize {
224 self.items.len()
225 }
226
227 /// `true` when the collection holds no records.
228 ///
229 /// Returned `true` before the first [`insert`](FileCollection::insert) and
230 /// after a directory with no matching files is read.
231 pub fn is_empty(&self) -> bool {
232 self.items.is_empty()
233 }
234
235 /// Borrow the sorted records as a slice, in [`search_rec_compare`] order.
236 ///
237 /// Use this to iterate all entries or binary-search without consuming the
238 /// collection. `FileList::build_listing` calls this to hand the sorted slice
239 /// off to the list-viewer state.
240 pub fn items(&self) -> &[SearchRec] {
241 &self.items
242 }
243
244 /// Consume the collection and return its sorted records by value.
245 ///
246 /// Avoids a clone when the `FileCollection` is a short-lived temporary.
247 /// `FileList::build_listing` uses this to transfer the sorted `Vec` directly
248 /// into `self.items` without an extra allocation.
249 pub fn into_items(self) -> Vec<SearchRec> {
250 self.items
251 }
252}
253
254// ---------------------------------------------------------------------------
255// DirListBox
256// ---------------------------------------------------------------------------
257
258/// Tree-glyph connector: root entry and each ancestor.
259const PATH_DIR: &str = "└─┬"; // U+2514 U+2500 U+252C
260/// Tree-glyph connector: first subdirectory.
261const FIRST_DIR: &str = "└┬─"; // U+2514 U+252C U+2500
262/// Tree-glyph connector: subsequent subdirectories.
263const MIDDLE_DIR: &str = " ├─"; // SPACE U+251C U+2500
264/// How many extra spaces are added per depth level.
265const INDENT_STEP: usize = 2;
266
267/// A concrete [`ListViewer`] over a [`Vec<DirEntry>`] that renders the current
268/// working directory as a tree-indented listing of its ancestors and immediate
269/// subdirectories.
270///
271/// ## Why it is a parallel `ListViewer`, not a `ListBox`
272///
273/// This is a *second, parallel, direct* [`ListViewer`] impl — exactly like
274/// [`ListBox`](crate::widgets::ListBox) is — over its own `Vec<DirEntry>`
275/// storage. It does **not** embed or delegate through a `ListBox`: if it
276/// delegated [`View::draw`](crate::view::View::draw), draw would run with the
277/// inner `ListBox` as `self` and call its text accessor over `Vec<String>`,
278/// never consulting the `Vec<DirEntry>`.
279///
280/// ## Native paths
281///
282/// The listing is built from native `/`-separated paths; there are no drive
283/// letters or backslashes.
284///
285/// [`ListViewer`]: crate::widgets::list_viewer::ListViewer
286///
287/// # Turbo Vision heritage
288/// Ports `TDirListBox` (`fileopen.cpp`/`dialogs.h`), a list-box subclass; here it
289/// becomes a parallel `ListViewer` impl over its own storage (deviation D2),
290/// native `/`-paths replace the DOS drive model (deviation D14), and persistence
291/// is dropped (deviation D12).
292pub struct DirListBox {
293 lv: crate::widgets::list_viewer::ListViewerState,
294 /// The rendered tree of [`DirEntry`] items; populated by `new_directory`.
295 items: Vec<DirEntry>,
296 /// Index of the current-directory ancestor entry in `items`.
297 ///
298 /// `is_selected(item)` returns `true` iff `item == cur`, so the current
299 /// directory is always highlighted separately from the cursor. Set by
300 /// `build_tree` / `new_directory`; the C++ equivalent was `ushort cur`.
301 cur: usize,
302 /// The path used for the most recent `new_directory` call
303 /// (native `/`-separated, with trailing `/`).
304 ///
305 /// Stored so `new_directory` can refer to it after rebuilding, but the
306 /// directory-change flow reads `focused_entry().dir()` instead — so this
307 /// field is informational only and not otherwise consulted at runtime.
308 dir: String,
309 /// The owning change-directory dialog's change-dir button id, wired by
310 /// [`set_chdir_button`](DirListBox::set_chdir_button) after assembly. On a
311 /// focus change, [`set_state`](DirListBox::set_state) requests the pump make
312 /// this button (un-)default. `None` when there is no such owner (e.g. an
313 /// open/save dialog never wires one).
314 chdir_button: Option<crate::view::ViewId>,
315}
316
317impl DirListBox {
318 /// Construct an empty single-column dir list box, ready to be populated by
319 /// [`new_directory`](DirListBox::new_directory).
320 ///
321 /// Only the vertical scrollbar `v` is used; `h` is accepted for API parity
322 /// with [`ListBox::new`](crate::widgets::ListBox::new) — pass `None` for
323 /// `h`. Wire the Chdir button after construction via
324 /// [`set_chdir_button`](DirListBox::set_chdir_button) (needed by
325 /// `ChDirDialog::new` only; `FileDialog` never wires one).
326 pub fn new(
327 bounds: crate::view::Rect,
328 h: Option<crate::view::ViewId>,
329 v: Option<crate::view::ViewId>,
330 ) -> Self {
331 DirListBox {
332 lv: crate::widgets::list_viewer::ListViewerState::new(bounds, 1, h, v),
333 items: Vec::new(),
334 cur: 0,
335 dir: String::new(),
336 chdir_button: None,
337 }
338 }
339
340 /// Borrow the current directory-tree listing as a slice of [`DirEntry`] items.
341 ///
342 /// Populated by [`new_directory`](DirListBox::new_directory); empty until
343 /// the first call. Use [`focused_entry`](DirListBox::focused_entry) to
344 /// read the cursor's current entry.
345 pub fn list(&self) -> &[DirEntry] {
346 &self.items
347 }
348
349 /// Wire the owning change-directory dialog's change-dir button id (set after
350 /// assembly, once the button's id is known). Read only by
351 /// `set_state` to make that button (un-)default on a
352 /// focus change.
353 pub fn set_chdir_button(&mut self, id: crate::view::ViewId) {
354 self.chdir_button = Some(id);
355 }
356
357 /// The focused [`DirEntry`], or `None` when the list is empty / the focus is
358 /// out of range. Read by the change-directory dialog when it handles a
359 /// change-dir request.
360 pub fn focused_entry(&self) -> Option<&DirEntry> {
361 self.items.get(self.lv.focused as usize)
362 }
363
364 /// Pure tree-builder — the directory-tree layout step of
365 /// [`new_directory`](DirListBox::new_directory).
366 ///
367 /// Given `dir` (a `/`-terminated absolute path, e.g. `"/home/oetiker/"`) and
368 /// an already-sorted list of immediate subdirectory names `subdirs`, returns
369 /// `(entries, cur)` where `cur` is the index of the current-directory entry
370 /// (the deepest ancestor, highlighted by [`ListViewer::is_selected`]).
371 ///
372 /// ## Layout
373 ///
374 /// ```text
375 /// └─┬/ ← root, indent 0 (PATH_DIR)
376 /// └─┬home ← indent 2 (PATH_DIR)
377 /// └─┬oetiker ← indent 4 (PATH_DIR) ← cur
378 /// └┬─projects ← indent 6 (FIRST_DIR, fixed up → └── if last)
379 /// ├─scratch ← indent 6 (MIDDLE_DIR)
380 /// └─tmp ← indent 6 (last; ├ → └)
381 /// ```
382 ///
383 /// For `dir = "/"` (only the root): `cur = 0`, subdirs at indent 2.
384 fn build_tree(dir: &str, subdirs: &[String]) -> (Vec<DirEntry>, usize) {
385 let mut entries: Vec<DirEntry> = Vec::new();
386
387 // --- Step 1: root entry -------------------------------------------
388 entries.push(DirEntry::new(format!("{PATH_DIR}/"), "/".to_string()));
389
390 // --- Step 2: ancestor entries ---------------------------------------
391 // Split `dir` on `/`; the meaningful segments are the non-empty parts.
392 // For `dir = "/home/oetiker/"` → segments ["home", "oetiker"].
393 let segments: Vec<&str> = dir.split('/').filter(|s| !s.is_empty()).collect();
394
395 for (i, &seg) in segments.iter().enumerate() {
396 let indent = (i + 1) * INDENT_STEP;
397 // Build the absolute path through this segment (no trailing slash).
398 let abs_path = format!("/{}", segments[..=i].join("/"));
399 entries.push(DirEntry::new(
400 format!("{}{}{}", " ".repeat(indent), PATH_DIR, seg),
401 abs_path,
402 ));
403 }
404
405 // `cur` is the index of the deepest ancestor = last entry pushed so far.
406 let cur = entries.len() - 1;
407
408 // Indent for subdirs = (depth of cur) + INDENT_STEP.
409 // For root-only (`/`, segments empty, cur = 0): sub_indent = 0 + 2 = 2.
410 // For `/home/oetiker/` (cur at index 2, depth = 2*INDENT_STEP = 4):
411 // sub_indent = 4 + 2 = 6.
412 let sub_indent = cur * INDENT_STEP + INDENT_STEP;
413
414 // --- Step 3: immediate subdirectories --------------------------------
415 for (i, name) in subdirs.iter().enumerate() {
416 let connector = if i == 0 { FIRST_DIR } else { MIDDLE_DIR };
417 // `directory = dir + name` (dir ends with `/`).
418 let directory = format!("{}{}", dir, name);
419 entries.push(DirEntry::new(
420 format!("{}{}{}", " ".repeat(sub_indent), connector, name),
421 directory,
422 ));
423 }
424
425 // --- Step 4: last-entry glyph fix-up --------------------------------
426 // Glyph fix-up applied UNCONDITIONALLY to the last entry (the deepest
427 // visible node has no sibling/child below it, so its connector becomes a
428 // corner):
429 // - has '└' (PATH_DIR "└─┬" or FIRST_DIR "└┬─"): turn the two chars
430 // after '└' into "──" → "└──".
431 // - else has '├' (MIDDLE_DIR " ├─"): turn '├' into '└' → " └─".
432 // When subdirs exist this hits the last subdir; with no subdirs it hits
433 // the deepest ancestor ("└─┬name" → "└──name"). `entries` is never empty
434 // (the root is always present).
435 let last = entries.last_mut().unwrap();
436 let mut c: Vec<char> = last.display_text.chars().collect();
437 if let Some(i) = c.iter().position(|&ch| ch == '└') {
438 if i + 1 < c.len() {
439 c[i + 1] = '─';
440 }
441 if i + 2 < c.len() {
442 c[i + 2] = '─';
443 }
444 last.display_text = c.into_iter().collect();
445 } else if let Some(i) = c.iter().position(|&ch| ch == '├') {
446 c[i] = '└';
447 last.display_text = c.into_iter().collect();
448 }
449
450 (entries, cur)
451 }
452
453 /// Read `dir`'s subdirectories from the filesystem, build the tree via the
454 /// private `build_tree`, then publish the new list to the list-viewer
455 /// machinery and focus the current-directory entry.
456 ///
457 /// The only impure operation (filesystem read) is isolated here; all tree
458 /// construction is in the pure `build_tree`.
459 pub fn new_directory(&mut self, dir: &str, ctx: &mut crate::view::Context) {
460 // Normalize to a trailing `/` (build_tree's precondition). The
461 // callers (`reset_current` / the revert action) pass
462 // `std::env::current_dir()`,
463 // which has NO trailing slash; without this, `build_tree`'s segment
464 // joins and the subdir `dir + name` concatenation would mis-form paths.
465 let dir = if dir.ends_with('/') {
466 dir.to_string()
467 } else {
468 format!("{dir}/")
469 };
470 let dir = dir.as_str();
471 self.dir = dir.to_string();
472
473 // Read immediate subdirectories from the filesystem.
474 let mut subdirs: Vec<String> = match std::fs::read_dir(dir) {
475 Ok(entries) => entries
476 .filter_map(|e| {
477 let e = e.ok()?;
478 // std::fs::metadata follows symlinks (stat semantics).
479 // DirEntry::file_type() is lstat-based and would wrongly
480 // exclude a symlink pointing at a directory — wrong for a
481 // directory navigator. A broken symlink → metadata errs → the
482 // `?` skips it, which is the desired behavior.
483 let meta = std::fs::metadata(e.path()).ok()?;
484 if !meta.is_dir() {
485 return None;
486 }
487 let name = e.file_name().to_string_lossy().into_owned();
488 if name.starts_with('.') {
489 return None;
490 }
491 Some(name)
492 })
493 .collect(),
494 Err(_) => Vec::new(),
495 };
496 // Sort case-insensitively (ordering — identical to `ci_cmp` in
497 // list_box.rs; inlined here to avoid cross-module coupling).
498 subdirs.sort_by(|a, b| {
499 a.chars()
500 .map(|c| c.to_ascii_lowercase())
501 .cmp(b.chars().map(|c| c.to_ascii_lowercase()))
502 });
503
504 let (items, cur) = Self::build_tree(dir, &subdirs);
505 self.items = items;
506 self.cur = cur;
507
508 let len = self.items.len() as i32;
509 crate::widgets::list_viewer::set_range(self, len, ctx);
510 if self.lv.range > 0 {
511 crate::widgets::list_viewer::focus_item(self, self.cur as i32, ctx);
512 }
513 }
514}
515
516impl crate::widgets::list_viewer::ListViewer for DirListBox {
517 fn lv(&self) -> &crate::widgets::list_viewer::ListViewerState {
518 &self.lv
519 }
520
521 fn lv_mut(&mut self) -> &mut crate::widgets::list_viewer::ListViewerState {
522 &mut self.lv
523 }
524
525 /// Return the display string for item `item` — the entry's stored
526 /// [`DirEntry::display_text`], which may carry tree-glyph prefixes.
527 ///
528 /// Called on every redraw by the shared list-viewer draw routine. Returns
529 /// an empty string for out-of-bounds indices (never panics). Callers that
530 /// need the raw path should call [`DirListBox::focused_entry`] instead.
531 fn get_text(&self, item: i32) -> String {
532 self.items
533 .get(item as usize)
534 .map(|e| e.text().to_string())
535 .unwrap_or_default()
536 }
537
538 /// Return `true` when `item` is the current-directory ancestor entry.
539 ///
540 /// Overrides the default (which would highlight only the cursor): the dir
541 /// list keeps the cursor on the ancestor entry (`cur`) even while the user
542 /// browses subdirs, so the current directory is always visually distinct
543 /// from the item under the cursor. Set by `new_directory`; moves only on a
544 /// confirmed directory change.
545 fn is_selected(&self, item: i32) -> bool {
546 item as usize == self.cur
547 }
548
549 /// Selecting an item (double-click / Enter) posts a change-directory command
550 /// ([`Command::CHANGE_DIR`](crate::command::Command::CHANGE_DIR)) to the
551 /// owning dialog.
552 ///
553 /// The command is payload-less: the dialog re-reads the focused entry itself.
554 /// Selection always follows focus (the list focuses an item before selecting
555 /// it), so `focused == item` here and the dialog reads the same entry.
556 fn select_item(&mut self, _item: i32, ctx: &mut crate::view::Context) {
557 ctx.post(crate::command::Command::CHANGE_DIR);
558 }
559}
560
561impl crate::view::View for DirListBox {
562 fn state(&self) -> &crate::view::ViewState {
563 &self.lv.state
564 }
565
566 fn state_mut(&mut self) -> &mut crate::view::ViewState {
567 &mut self.lv.state
568 }
569
570 fn draw(&mut self, ctx: &mut crate::view::DrawCtx) {
571 crate::widgets::list_viewer::draw(self, ctx);
572 }
573
574 /// Dispatch mouse and keyboard events to the shared list-viewer handler.
575 ///
576 /// Handles arrow keys, Page Up/Down, Home/End, and mouse clicks/drags to
577 /// move the cursor through the directory tree. A double-click or Enter fires
578 /// [`select_item`](crate::widgets::list_viewer::ListViewer::select_item),
579 /// which posts `Command::CHANGE_DIR` to the owning dialog. The event loop
580 /// drives this; callers do not call it directly.
581 fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut crate::view::Context) {
582 crate::widgets::list_viewer::handle_event(self, ev, ctx);
583 }
584
585 /// On a focus change the dir list grabs the dialog's default button when it
586 /// gains focus and releases it when it loses focus.
587 ///
588 /// The leaf list cannot poke its sibling button directly, so it requests the
589 /// change through the pump's
590 /// [`MakeButtonDefault`](crate::view::Deferred::MakeButtonDefault) broker via
591 /// [`Context::make_button_default`](crate::view::Context::make_button_default). `chdir_button` is `None` when there is no
592 /// change-directory owner, so this is then a no-op.
593 fn set_state(
594 &mut self,
595 flag: crate::view::StateFlag,
596 enable: bool,
597 ctx: &mut crate::view::Context,
598 ) {
599 crate::widgets::list_viewer::set_state(self, flag, enable, ctx);
600 if flag == crate::view::StateFlag::Focused
601 && let Some(btn) = self.chdir_button
602 {
603 ctx.make_button_default(btn, enable);
604 }
605 }
606
607 /// Republish the scrollbar range on resize.
608 fn on_bounds_changed(&mut self, ctx: &mut crate::view::Context) {
609 crate::widgets::list_viewer::on_bounds_changed(self, ctx);
610 }
611
612 fn cursor_request(&self) -> Option<crate::view::Point> {
613 crate::widgets::list_viewer::focused_cursor(self)
614 }
615
616 fn apply_scroll_sync(
617 &mut self,
618 h: Option<i32>,
619 v: Option<i32>,
620 ctx: &mut crate::view::Context,
621 ) {
622 crate::widgets::list_viewer::apply_scroll(self, h, v, ctx);
623 }
624
625 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
626 Some(self)
627 }
628
629 /// The view's value is its focused item index (same as a plain list box).
630 fn value(&self) -> Option<crate::data::FieldValue> {
631 Some(crate::data::FieldValue::Int(self.lv.focused))
632 }
633}
634
635// ---------------------------------------------------------------------------
636// FileList
637// ---------------------------------------------------------------------------
638
639/// The file-listing pane of the file dialog. A concrete
640/// [`SortedSearch`](crate::widgets::list_viewer::SortedSearch) (hence
641/// [`ListViewer`]) over a name-sorted [`Vec<SearchRec>`] (== a
642/// [`FileCollection`]'s contents), with two columns and incremental
643/// type-to-search.
644///
645/// ## Structural shape
646///
647/// This is a *direct* [`SortedSearch`] impl — the same shape as
648/// [`SortedListBox`](crate::widgets::SortedListBox), NOT
649/// [`DirListBox`](crate::dialog::DirListBox) (which is a plain [`ListViewer`]).
650/// It therefore wires `handle_event`→`sorted_handle_event` and
651/// `cursor_request`→`sorted_cursor`, inherits the default `is_selected`
652/// (the focused item is the selected one), and contributes no dialog data
653/// (`value() == None`).
654///
655/// ## The `search` key
656///
657/// `search` is the one method whose comparator is **non-obvious**: it must
658/// compare via [`search_rec_compare`] over raw [`SearchRec`]s, **not** over
659/// [`get_text`](crate::widgets::ListViewer::get_text) (which appends `/` to dir names and would
660/// mis-order). The key carries an `attr` of [`FA_DIREC`] when the
661/// [`shift_state`](crate::widgets::list_viewer::SortedSearch::shift_state)
662/// holds [`KB_SHIFT`](crate::widgets::list_viewer::KB_SHIFT) or the typed prefix
663/// starts with `.`, routing the search into the directory section of the
664/// collection. That routing exists only in `search_rec_compare`'s file/dir
665/// ordering — hence this is a per-impl `search`, not the shared `get_text` one.
666///
667/// ## Native paths
668///
669/// `get_text` appends `/` to directory names; the listing is case-sensitive (the
670/// DOS-only upper-casing of the search key has no Linux counterpart).
671///
672/// ## Owner broadcasts
673///
674/// On every focus change the list broadcasts a "file focused" command (subject =
675/// the focused entry), and on double-click/Enter it broadcasts a "file
676/// double-clicked" command. Both are wired via the `on_focus_changed` hook
677/// ([`ListViewer::on_focus_changed`](crate::widgets::ListViewer::on_focus_changed)) and the `select_item` override; the focused
678/// record is resolved through the pump's
679/// [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile) broker — the
680/// broadcast itself is payload-less and carries a resolvable source id.
681///
682/// ## Intentional simplifications
683///
684/// - No dialog data (`value() == None`).
685/// - There is no out-of-memory guard on the listing: a Rust `Vec` grows fallibly
686/// only on true allocation failure, which aborts.
687/// - No path canonicalization is needed: the caller passes an absolute `/`-path.
688///
689/// [`ListViewer`]: crate::widgets::list_viewer::ListViewer
690/// [`SortedSearch`]: crate::widgets::list_viewer::SortedSearch
691///
692/// # Turbo Vision heritage
693/// Ports `TFileList` (`fileopen.cpp`/`dialogs.h`), a sorted-list-box subclass;
694/// here it becomes a direct `SortedSearch` impl (deviation D2), persistence is
695/// dropped (deviation D12), and the DOS path model becomes native `/`-paths
696/// (deviation D14).
697pub struct FileList {
698 lv: crate::widgets::list_viewer::ListViewerState,
699 /// Sorted listing in [`search_rec_compare`] order (plain files first, then
700 /// dirs, then `".."`). Updated by `read_directory`/`read_directory_listing`.
701 items: Vec<SearchRec>,
702 /// Position of the last successfully matched char in the focused item's
703 /// display text during an incremental type-to-search. `-1` = no active
704 /// search (next keystroke starts a fresh search). Set by `sorted_handle_event`
705 /// via the `SortedSearch` trait accessor `set_search_pos`.
706 search_pos: i32,
707 /// Shift-key bits captured at the `search_pos` -1→0 transition (i.e. when
708 /// the user starts typing). `sorted_handle_event` stores the live shift
709 /// state here; `search` reads it to route the typed prefix into the
710 /// directory section of the listing when Shift is held.
711 shift_state: u8,
712}
713
714impl FileList {
715 /// Construct an empty two-column file list, ready to be populated by
716 /// [`read_directory`](FileList::read_directory) or
717 /// [`read_directory_listing`](FileList::read_directory_listing).
718 ///
719 /// `num_cols` is fixed at 2 (files in the left column, dirs in the right);
720 /// the text cursor is shown at column 1 for the incremental type-to-search
721 /// indicator. `h` is accepted for API parity with
722 /// [`ListBox::new`](crate::widgets::ListBox::new) but ignored — a file list
723 /// only uses the vertical scrollbar `v`. Pass `None` for `h` and the
724 /// vertical scrollbar's [`ViewId`](crate::view::ViewId) for `v`.
725 pub fn new(
726 bounds: crate::view::Rect,
727 h: Option<crate::view::ViewId>,
728 v: Option<crate::view::ViewId>,
729 ) -> Self {
730 let mut lv = crate::widgets::list_viewer::ListViewerState::new(bounds, 2, h, v);
731 lv.state.show_cursor();
732 lv.state.set_cursor(1, 0);
733 FileList {
734 lv,
735 items: Vec::new(),
736 search_pos: -1,
737 shift_state: 0,
738 }
739 }
740
741 /// Borrow the sorted file/directory listing as a slice.
742 ///
743 /// Populated by [`read_directory`](FileList::read_directory) and
744 /// [`read_directory_listing`](FileList::read_directory_listing); empty until
745 /// the first call. The slice is in [`search_rec_compare`] order: plain files
746 /// first (alphabetically), then directories, then `".."` last. Use
747 /// [`focused_rec`](FileList::focused_rec) to get the cursor's current entry.
748 pub fn list(&self) -> &[SearchRec] {
749 &self.items
750 }
751
752 /// The focused entry, or `None` when the list is empty (or the focus is out
753 /// of range). Read by the pump's
754 /// [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile) broker to
755 /// deliver the focused-file payload to the filename input line / info pane.
756 pub fn focused_rec(&self) -> Option<SearchRec> {
757 self.items.get(self.lv.focused as usize).cloned()
758 }
759
760 /// Match `name` against a `*`/`?` glob (case-sensitive, like the Linux
761 /// build). `*` = any run (including empty); `?` = exactly one char. No
762 /// `[...]` classes or escaping (a Unix `fnmatch` subset). `"*"` matches
763 /// everything. Classic two-pointer scan with `*`-backtracking.
764 fn wildcard_match(pattern: &str, name: &str) -> bool {
765 let p: Vec<char> = pattern.chars().collect();
766 let s: Vec<char> = name.chars().collect();
767 let (mut pi, mut si) = (0usize, 0usize);
768 // Backtrack anchors: the last `*` position in `p` and the `s` position
769 // it was matched against (so a failed match can extend the `*` run).
770 let mut star: Option<usize> = None;
771 let mut star_si = 0usize;
772 while si < s.len() {
773 if pi < p.len() && (p[pi] == '?' || p[pi] == s[si]) {
774 pi += 1;
775 si += 1;
776 } else if pi < p.len() && p[pi] == '*' {
777 star = Some(pi);
778 star_si = si;
779 pi += 1;
780 } else if let Some(sp) = star {
781 // Extend the last `*` to consume one more char of `s`.
782 pi = sp + 1;
783 star_si += 1;
784 si = star_si;
785 } else {
786 return false;
787 }
788 }
789 // Trailing `*`s in the pattern match the empty remainder.
790 while pi < p.len() && p[pi] == '*' {
791 pi += 1;
792 }
793 pi == p.len()
794 }
795
796 /// Build the sorted listing from a directory's raw entries — the pure,
797 /// unit-testable core of [`read_directory`](FileList::read_directory). `dir`
798 /// is a `/`-terminated absolute path; each raw entry is `(name, is_dir,
799 /// size, mtime)` where `mtime` is the entry's modification time (`None` when
800 /// the filesystem could not report one).
801 ///
802 /// Two passes:
803 /// - **Files:** a non-directory is kept iff it matches `wildcard`.
804 /// - **Directories:** a directory is kept iff its name does not start with `.`
805 /// — the wildcard does NOT apply. This drops `.`, `..`, AND hidden dirs.
806 /// - **`".."`:** appended iff `dir != "/"`.
807 ///
808 /// `time` carries the DOS-packed mtime ([`pack_dos_time`]) on every real
809 /// entry — the value the [`FileInfoPane`] unpacks to render the
810 /// size/date line. A real entry with no reportable mtime gets `time = 0`
811 /// (an empty `name` would suppress its date line; a real name would draw a
812 /// blank date, an acceptable degenerate case).
813 ///
814 /// The `".."` row is synthesized *without* statting the parent, so it uses
815 /// [`DOTDOT_TIME`] (`0x210000`) unconditionally — a cosmetic difference in the
816 /// displayed date on the `".."` row only (the real parent's mtime is not
817 /// shown).
818 ///
819 /// Returns the [`search_rec_compare`]-sorted `Vec`, built via
820 /// [`FileCollection::insert`].
821 fn build_listing(
822 dir: &str,
823 wildcard: &str,
824 raw: &[(String, bool, i32, Option<std::time::SystemTime>)],
825 ) -> Vec<SearchRec> {
826 let mut fc = FileCollection::new();
827 for (name, is_dir, size, mtime) in raw {
828 let time = mtime.as_ref().map(pack_dos_time).unwrap_or(0);
829 if *is_dir {
830 if !name.starts_with('.') {
831 fc.insert(SearchRec {
832 attr: FA_DIREC,
833 time,
834 size: 0,
835 name: name.clone(),
836 });
837 }
838 } else if Self::wildcard_match(wildcard, name) {
839 fc.insert(SearchRec {
840 attr: 0,
841 time,
842 size: *size,
843 name: name.clone(),
844 });
845 }
846 }
847 if dir != "/" {
848 fc.insert(SearchRec {
849 attr: FA_DIREC,
850 time: DOTDOT_TIME,
851 size: 0,
852 name: "..".into(),
853 });
854 }
855 fc.into_items()
856 }
857
858 /// Read `dir`'s raw entries from the filesystem — the impure half shared by
859 /// [`read_directory`](FileList::read_directory) and the ctx-free
860 /// [`read_directory_listing`](FileList::read_directory_listing). Each entry is
861 /// `(name, is_dir, size, mtime)`. Uses `std::fs::metadata`, which follows
862 /// symlinks (so a symlink to a directory lists as a directory); a broken
863 /// symlink errs and is skipped. `size` saturates into `i32`.
864 fn raw_from_fs(dir: &str) -> Vec<(String, bool, i32, Option<std::time::SystemTime>)> {
865 match std::fs::read_dir(dir) {
866 Ok(entries) => entries
867 .filter_map(|e| {
868 let e = e.ok()?;
869 let meta = std::fs::metadata(e.path()).ok()?;
870 let name = e.file_name().to_string_lossy().into_owned();
871 let is_dir = meta.is_dir();
872 let size = meta.len().min(i32::MAX as u64) as i32;
873 // `.modified()` is unsupported on some platforms; a None
874 // mtime packs to `time = 0` in build_listing.
875 let mtime = meta.modified().ok();
876 Some((name, is_dir, size, mtime))
877 })
878 .collect(),
879 Err(_) => Vec::new(),
880 }
881 }
882
883 /// Read and publish the listing without a [`Context`](crate::view::Context) —
884 /// a sibling of [`read_directory`](FileList::read_directory) for the dialog
885 /// construction path and deterministic tests. Builds and publishes the listing
886 /// to the list-viewer state (`range`/`focused`/`top_item`) but does **NOT**
887 /// sync the scrollbar or broadcast a focused-file event, because both need a
888 /// `Context`. The ctx-ful [`read_directory`](FileList::read_directory) (driven
889 /// from `reset_current`) is the path that does the scrollbar sync + broadcast.
890 pub fn read_directory_listing(&mut self, dir: &str, wildcard: &str) {
891 let raw = Self::raw_from_fs(dir);
892 self.items = Self::build_listing(dir, wildcard, &raw);
893 self.lv.range = self.items.len() as i32;
894 self.lv.focused = 0;
895 self.lv.top_item = 0;
896 }
897
898 /// Read `dir`'s contents from the filesystem, apply `wildcard` filtering,
899 /// publish the sorted listing to the list-viewer state, and broadcast a
900 /// "file focused" event so the filename input line and info pane update.
901 ///
902 /// The ctx-ful sibling of [`read_directory_listing`](FileList::read_directory_listing):
903 /// use this when a live `Context` is available (i.e. from within an event
904 /// handler or `reset_current`). The context-free variant is for construction
905 /// and deterministic tests where no event loop is running.
906 pub fn read_directory(&mut self, dir: &str, wildcard: &str, ctx: &mut crate::view::Context) {
907 let raw = Self::raw_from_fs(dir);
908
909 self.items = Self::build_listing(dir, wildcard, &raw);
910
911 let len = self.items.len() as i32;
912 crate::widgets::list_viewer::set_range(self, len, ctx);
913 if self.lv.range > 0 {
914 // focus_item → on_focus_changed → FILE_FOCUSED broadcast (item 0).
915 crate::widgets::list_viewer::focus_item(self, 0, ctx);
916 } else if let Some(id) = self.lv.state.id() {
917 // Empty listing — no focusable item, so the `focus_item` path can't
918 // fire. Broadcast FILE_FOCUSED directly: the broker reads
919 // `focused_rec() == None` → a blank field (no current file).
920 ctx.broadcast(crate::command::Command::FILE_FOCUSED, Some(id));
921 }
922 }
923}
924
925impl crate::widgets::list_viewer::ListViewer for FileList {
926 fn lv(&self) -> &crate::widgets::list_viewer::ListViewerState {
927 &self.lv
928 }
929
930 fn lv_mut(&mut self) -> &mut crate::widgets::list_viewer::ListViewerState {
931 &mut self.lv
932 }
933
934 /// Return the display text for item `item`: the bare file name for plain
935 /// files, or the name with a trailing `/` appended for directories.
936 ///
937 /// Called on every redraw by the shared list-viewer draw routine. The
938 /// trailing `/` signals a directory to the user without altering the
939 /// underlying [`SearchRec::name`]. Out-of-bounds indices return an empty
940 /// string and never panic.
941 fn get_text(&self, item: i32) -> String {
942 match self.items.get(item as usize) {
943 Some(rec) => {
944 if rec.attr & FA_DIREC != 0 {
945 format!("{}/", rec.name)
946 } else {
947 rec.name.clone()
948 }
949 }
950 None => String::new(),
951 }
952 }
953
954 // `is_selected` uses the default (the focused item is the selected one). The
955 // file list does NOT override it — do NOT add one here.
956
957 /// Fired on EVERY focus change.
958 ///
959 /// Broadcasts a payload-less "file focused" command with this view as the
960 /// resolvable `source`; the pump's
961 /// [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile) broker
962 /// reads [`focused_rec`](FileList::focused_rec) and delivers it to the
963 /// consumer. The shared focus machinery invokes this hook after it updates the
964 /// focused index, so the new entry is already in place.
965 fn on_focus_changed(&mut self, ctx: &mut crate::view::Context) {
966 if let Some(id) = self.lv.state.id() {
967 ctx.broadcast(crate::command::Command::FILE_FOCUSED, Some(id));
968 }
969 }
970
971 /// On double-click / Enter, broadcast a "file double-clicked" command.
972 ///
973 /// Payload-less: the only consumer ([`FileDialog`]'s event handler) merely
974 /// turns it into an OK, and never reads the record. It does not run the
975 /// default selection behaviour, so it does NOT also emit a generic
976 /// list-item-selected broadcast.
977 fn select_item(&mut self, _item: i32, ctx: &mut crate::view::Context) {
978 if let Some(id) = self.lv.state.id() {
979 ctx.broadcast(crate::command::Command::FILE_DOUBLE_CLICKED, Some(id));
980 }
981 }
982}
983
984impl crate::widgets::list_viewer::SortedSearch for FileList {
985 fn search_pos(&self) -> i32 {
986 self.search_pos
987 }
988
989 fn set_search_pos(&mut self, pos: i32) {
990 self.search_pos = pos;
991 }
992
993 fn shift_state(&self) -> u8 {
994 self.shift_state
995 }
996
997 fn set_shift_state(&mut self, s: u8) {
998 self.shift_state = s;
999 }
1000
1001 /// Map a typed prefix to its insertion point in the sorted listing.
1002 ///
1003 /// The search key's `attr` is [`FA_DIREC`] when Shift is held
1004 /// (`shift_state & KB_SHIFT`) OR the typed prefix starts with `.`, else 0 —
1005 /// this routes the search into the directory or file section of the listing.
1006 /// The name is the typed prefix verbatim (case-sensitive on Linux).
1007 ///
1008 /// Returns the first index `i` in `0..range` where
1009 /// `search_rec_compare(items[i], key) != Less` (the insertion point), or
1010 /// `range` if none. **Compares via [`search_rec_compare`] over raw
1011 /// [`SearchRec`]s** (so `attr` routing applies) — NOT over the display text.
1012 fn search(&self, cur: &[char]) -> i32 {
1013 use crate::widgets::list_viewer::KB_SHIFT;
1014 let attr = if (self.shift_state & KB_SHIFT) != 0 || cur.first() == Some(&'.') {
1015 FA_DIREC
1016 } else {
1017 0
1018 };
1019 let name: String = cur.iter().collect();
1020 let key = SearchRec {
1021 attr,
1022 time: 0,
1023 size: 0,
1024 name,
1025 };
1026 // Insertion point over the sorted items, bounded by `range` (which the
1027 // tests set independently of `items.len()`), via search_rec_compare.
1028 let range = self.lv.range;
1029 let (mut lo, mut hi) = (0i32, range);
1030 while lo < hi {
1031 let mid = lo + (hi - lo) / 2;
1032 if search_rec_compare(&self.items[mid as usize], &key) == Ordering::Less {
1033 lo = mid + 1;
1034 } else {
1035 hi = mid;
1036 }
1037 }
1038 lo
1039 }
1040}
1041
1042impl crate::view::View for FileList {
1043 fn state(&self) -> &crate::view::ViewState {
1044 &self.lv.state
1045 }
1046
1047 fn state_mut(&mut self) -> &mut crate::view::ViewState {
1048 &mut self.lv.state
1049 }
1050
1051 fn draw(&mut self, ctx: &mut crate::view::DrawCtx) {
1052 crate::widgets::list_viewer::draw(self, ctx);
1053 }
1054
1055 /// Dispatch mouse, keyboard, and incremental type-to-search events.
1056 ///
1057 /// Delegates to the shared sorted-list handler (`sorted_handle_event`):
1058 /// printable characters start or extend an incremental search that jumps
1059 /// the cursor to the first matching file name (Shift → searches the
1060 /// directory section); arrow keys, Page Up/Down, and mouse navigate the
1061 /// two-column listing; Enter / double-click fires `select_item` which
1062 /// broadcasts `Command::FILE_DOUBLE_CLICKED`. The event loop drives this;
1063 /// callers do not call it directly.
1064 fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut crate::view::Context) {
1065 crate::widgets::list_viewer::sorted_handle_event(self, ev, ctx);
1066 }
1067
1068 fn cursor_request(&self) -> Option<crate::view::Point> {
1069 crate::widgets::list_viewer::sorted_cursor(self)
1070 }
1071
1072 /// No special state handling — the plain shared behaviour (its only owner
1073 /// notification is in the focus-change hook above).
1074 fn set_state(
1075 &mut self,
1076 flag: crate::view::StateFlag,
1077 enable: bool,
1078 ctx: &mut crate::view::Context,
1079 ) {
1080 crate::widgets::list_viewer::set_state(self, flag, enable, ctx);
1081 }
1082
1083 /// Republish the scrollbar range on resize.
1084 fn on_bounds_changed(&mut self, ctx: &mut crate::view::Context) {
1085 crate::widgets::list_viewer::on_bounds_changed(self, ctx);
1086 }
1087
1088 fn apply_scroll_sync(
1089 &mut self,
1090 h: Option<i32>,
1091 v: Option<i32>,
1092 ctx: &mut crate::view::Context,
1093 ) {
1094 crate::widgets::list_viewer::apply_scroll(self, h, v, ctx);
1095 }
1096
1097 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1098 Some(self)
1099 }
1100
1101 /// `None` — the file list contributes nothing to dialog data transfer.
1102 fn value(&self) -> Option<crate::data::FieldValue> {
1103 None
1104 }
1105}
1106
1107// ---------------------------------------------------------------------------
1108// FileInputLine
1109// ---------------------------------------------------------------------------
1110
1111/// A filename [`InputLine`](crate::widgets::InputLine) that mirrors the
1112/// [`FileList`]'s focused entry.
1113///
1114/// On a "file focused" broadcast (and only while the user is **not** typing in
1115/// it — the not-currently-selected guard) it copies the focused entry's name
1116/// into the field, appending `/<wildcard>` when the entry is a directory.
1117///
1118/// ## Structural shape
1119///
1120/// This **embeds** an [`InputLine`](crate::widgets::InputLine) and forwards the un-overridden
1121/// [`View`](crate::view::View) methods (embed-and-delegate composition) — only
1122/// `handle_event` and `as_any_mut` differ. `value`/`set_value` are NOT
1123/// overridden, so they forward to the inner `InputLine`.
1124///
1125/// ## The payload broker
1126///
1127/// The broadcast carries no payload, so `handle_event` does not read the record
1128/// inline; it requests
1129/// [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile) and the pump
1130/// resolves the producer's [`focused_rec`](FileList::focused_rec), then calls
1131/// [`on_file_focused`](FileInputLine::on_file_focused) on this view.
1132///
1133/// # Turbo Vision heritage
1134/// Ports `TFileInputLine` (`stddlg.cpp`/`stddlg.h`), an input-line subclass; here
1135/// it becomes embed-and-delegate composition (deviation D2), the focused record
1136/// reaches it via a sibling broker since a child cannot read its owner directly
1137/// (deviation D3/D4), and persistence is dropped (deviation D12).
1138pub struct FileInputLine {
1139 /// The embedded input line — the delegation target.
1140 inner: crate::widgets::InputLine,
1141 /// Cached copy of the dialog's wildcard (a child can't read its owner
1142 /// directly). Set at construction; the dialog pushes updates when it re-reads
1143 /// with a new mask. Appended after a `/` when the focused entry is a
1144 /// directory.
1145 wild_card: String,
1146}
1147
1148impl FileInputLine {
1149 /// Build a filename input field for use inside a [`FileDialog`].
1150 ///
1151 /// - `max_len` — byte cap (`LimitMode::MaxBytes`); effective maximum is
1152 /// `max_len - 1`. Pass `MAXPATH` (255) for file dialogs.
1153 /// - `wild_card` — the owning dialog's initial wildcard mask, cached here
1154 /// so `on_file_focused` can append it to directory names without reading
1155 /// the owner directly. Use [`set_wild_card`](FileInputLine::set_wild_card)
1156 /// to push an updated mask when the dialog re-reads with a new one.
1157 ///
1158 /// No event mask is set; the parent group delivers all broadcasts
1159 /// unconditionally, which is required for the `FILE_FOCUSED` handler.
1160 pub fn new(bounds: crate::view::Rect, max_len: i32, wild_card: impl Into<String>) -> Self {
1161 FileInputLine {
1162 inner: crate::widgets::InputLine::new(
1163 bounds,
1164 max_len,
1165 None,
1166 crate::widgets::LimitMode::MaxBytes,
1167 ),
1168 wild_card: wild_card.into(),
1169 }
1170 }
1171
1172 /// Write the focused record into the field — called by the pump's
1173 /// [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile) broker
1174 /// once it has resolved the producer's focused [`SearchRec`].
1175 ///
1176 /// Copies the record's name into the field; when the record is a directory,
1177 /// appends `/` and the cached wildcard; then resets the selection. `None`
1178 /// means no current file (empty name) → a blank field. No explicit redraw is
1179 /// needed (the whole tree is redrawn each frame).
1180 pub fn on_file_focused(&mut self, rec: Option<SearchRec>) {
1181 let text = match rec {
1182 Some(r) if r.attr & FA_DIREC != 0 => format!("{}/{}", r.name, self.wild_card),
1183 Some(r) => r.name,
1184 None => String::new(),
1185 };
1186 // This path does not clamp; assign directly (InputLine exposes no clamping
1187 // text-setter, and `data` is `pub`).
1188 self.inner.data = text;
1189 // Reset the selection (no scroll-to-end suppression).
1190 self.inner.select_all(false, true);
1191 }
1192
1193 /// Push a new wildcard mask into the field's cache.
1194 ///
1195 /// Called by [`FileDialog::valid`](crate::view::View::valid)'s wildcard branch whenever the user
1196 /// navigates with a new mask (e.g. `*.txt`). Without this update, the
1197 /// next directory-focus broadcast would still append the stale mask when
1198 /// formatting a directory entry as `"dirname/<old_mask>"`. Call this before
1199 /// re-reading the directory so the cache is current for subsequent broadcasts.
1200 pub fn set_wild_card(&mut self, w: impl Into<String>) {
1201 self.wild_card = w.into();
1202 }
1203
1204 /// The current text in the filename field.
1205 ///
1206 /// Read by [`FileDialog::get_file_name`] to resolve the typed or
1207 /// broadcast-filled path against the dialog's current directory. The value
1208 /// may be a bare filename, a wildcard mask, a partial path, or an absolute
1209 /// path — `get_file_name` normalizes all of these.
1210 pub fn text(&self) -> &str {
1211 &self.inner.data
1212 }
1213}
1214
1215#[crate::delegate(to = inner)]
1216impl crate::view::View for FileInputLine {
1217 /// Run the embedded input line first, then, on a "file focused" broadcast
1218 /// while NOT selected (so the copy never clobbers the field the user is typing
1219 /// in), request the payload broker.
1220 fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut crate::view::Context) {
1221 // The embedded input line handles the event first.
1222 self.inner.handle_event(ev, ctx);
1223
1224 if let crate::event::Event::Broadcast {
1225 command,
1226 source: Some(src),
1227 } = *ev
1228 && command == crate::command::Command::FILE_FOCUSED
1229 // Do NOT clobber the field while the user is typing in it.
1230 && !self.inner.state().state.selected
1231 && let Some(my_id) = self.inner.state().id()
1232 {
1233 ctx.request_resolve_focused_file(my_id, src);
1234 }
1235 }
1236
1237 /// **Override** (the OPPOSITE of [`Memo`](crate::widgets::Memo), which
1238 /// forwards `as_any_mut` to its editor): the pump's broker downcasts the
1239 /// resolved subscriber to `FileInputLine`, so `as_any_mut` MUST return
1240 /// `self`, NOT the inner `InputLine`.
1241 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1242 Some(self)
1243 }
1244}
1245
1246// ---------------------------------------------------------------------------
1247// FileInfoPane
1248// ---------------------------------------------------------------------------
1249
1250/// Month names indexed by the DOS month field (1–12); index 0 is the empty
1251/// string for a blank / no-file record.
1252const MONTHS: [&str; 13] = [
1253 "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1254];
1255/// The AM-hours suffix on the date line.
1256const AM: &str = "a";
1257/// The PM-hours suffix on the date line.
1258const PM: &str = "p";
1259
1260/// The DOS-packed time the synthesized `".."` record carries (`0x210000`):
1261/// date byte `0x21` → day 1, month 1, year-1980 0 → Jan 01 1980 00:00. Using it
1262/// (rather than a literal `0`, which would unpack to month 0 / day 0 — a blank
1263/// month name + a `00` day) keeps the `".."` row's date well-formed.
1264///
1265/// The `".."` entry is synthesized without statting the parent, so it uses this
1266/// constant unconditionally rather than showing the real parent's mtime; the
1267/// difference is cosmetic (only the `".."` row's displayed date).
1268const DOTDOT_TIME: i32 = 0x0021_0000;
1269
1270/// Pack a [`SystemTime`](std::time::SystemTime) into the DOS `ftime` `u32`
1271/// layout, so the [`FileInfoPane`] draw can unpack and format it.
1272///
1273/// Layout (high 16 bits = date, low 16 bits = time):
1274/// - date: `year-1980` in bits 9–15, `month` (1–12) in bits 5–8, `day` (1–31)
1275/// in bits 0–4.
1276/// - time: `hour` (0–23) in bits 11–15, `min` (0–59) in bits 5–10, `sec/2` in
1277/// bits 0–4.
1278///
1279/// The `std::fs` mtime is packed as civil Y/M/D H:M:S in **UTC** (computed via
1280/// Howard Hinnant's days-from-civil algorithm — no timezone crate dependency), so
1281/// the displayed clock is UTC, not local. Times before the 1980 DOS epoch clamp
1282/// to Jan 01 1980 00:00 (the format cannot represent earlier).
1283fn pack_dos_time(t: &std::time::SystemTime) -> i32 {
1284 let secs = match t.duration_since(std::time::UNIX_EPOCH) {
1285 Ok(d) => d.as_secs() as i64,
1286 // A pre-epoch mtime is well before the 1980 DOS epoch → clamp.
1287 Err(_) => return DOTDOT_TIME,
1288 };
1289 let days = secs.div_euclid(86_400);
1290 let rem = secs.rem_euclid(86_400);
1291 let hour = rem / 3600;
1292 let min = (rem % 3600) / 60;
1293 let sec = rem % 60;
1294
1295 // Howard Hinnant's civil-from-days (days are relative to 1970-01-01).
1296 let z = days + 719_468;
1297 let era = z.div_euclid(146_097);
1298 let doe = z - era * 146_097; // [0, 146096]
1299 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // [0, 399]
1300 let y = yoe + era * 400;
1301 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
1302 let mp = (5 * doy + 2) / 153; // [0, 11]
1303 let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
1304 let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
1305 let y = if m <= 2 { y + 1 } else { y };
1306
1307 // Clamp to the DOS 1980 epoch (DOS cannot represent earlier dates).
1308 if y < 1980 {
1309 return DOTDOT_TIME;
1310 }
1311
1312 let date = (((y - 1980) as u32) << 9) | ((m as u32) << 5) | (d as u32);
1313 let time = ((hour as u32) << 11) | ((min as u32) << 5) | ((sec / 2) as u32);
1314 ((date << 16) | time) as i32
1315}
1316
1317/// A plain view that displays the focused file's path on line 0 and its name +
1318/// size + date on line 1.
1319///
1320/// ## Structural shape
1321///
1322/// This is a **direct [`View`](crate::view::View) impl** over a
1323/// [`ViewState`](crate::view::ViewState) — it does not embed another widget.
1324///
1325/// ## The payload broker — shared with [`FileInputLine`]
1326///
1327/// Like `FileInputLine` it subscribes to the "file focused" broadcast: on it the
1328/// pane requests [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile)
1329/// and the pump resolves the producer's
1330/// [`focused_rec`](FileList::focused_rec), then calls
1331/// [`on_file_focused`](FileInfoPane::on_file_focused) on this view. Unlike the
1332/// input line there is **no not-selected guard** — the pane always updates.
1333///
1334/// ## Cached owner fields
1335///
1336/// `draw` needs the dialog's directory and wildcard. A leaf view cannot read its
1337/// owner directly (and `draw` has no `Context` at all), so both are **cached**
1338/// (`directory` / `wild_card`), set at construction and refreshed by
1339/// [`set_dir_info`](FileInfoPane::set_dir_info) when the dialog re-reads with a
1340/// new mask. The focused record is cached in `file_block`. The pane is drawn in
1341/// the [`Role::InfoPane`](crate::theme::Role::InfoPane) color; the path line is `directory` concatenated with
1342/// `wild_card` (the dialog guarantees `directory` ends with `/`).
1343///
1344/// # Turbo Vision heritage
1345/// Ports `TFileInfoPane` (`stddlg.cpp`/`stddlg.h`), a plain view subclass; the
1346/// owner fields it reads in `draw` are cached because a child can't reach its
1347/// owner directly (deviation D3/D4), and persistence is dropped (deviation D12).
1348pub struct FileInfoPane {
1349 /// The base-view state (bounds, flags, id, …).
1350 state: crate::view::ViewState,
1351 /// Cached copy of the owning dialog's current directory (always
1352 /// `/`-terminated). Set at construction and updated by `set_dir_info`.
1353 /// C++ `TFileInfoPane::draw` read `owner->directory` directly; here it
1354 /// must be cached because `draw` has no `Context` and a child cannot
1355 /// reach back into its parent under the downward-borrow model.
1356 directory: String,
1357 /// Cached copy of the owning dialog's current wildcard (e.g. `"*.rs"`).
1358 /// Same caching rationale as `directory`. Updated by `set_dir_info`
1359 /// whenever `FileDialog::reset_current` re-reads the listing.
1360 wild_card: String,
1361 /// The currently focused file record, or `None` when the listing is empty
1362 /// or the `FILE_FOCUSED` broadcast has not yet fired. `None` → line 1 is
1363 /// blank (no name/size/date). Updated by `on_file_focused` via the pump's
1364 /// `ResolveFocusedFile` broker.
1365 file_block: Option<SearchRec>,
1366}
1367
1368impl FileInfoPane {
1369 /// Construct a `FileInfoPane` at `bounds`, caching `directory` and
1370 /// `wild_card` from the owning [`FileDialog`].
1371 ///
1372 /// The pane can't read its owner at draw time (no `Context` in `draw`, and
1373 /// Rust prevents borrowing a parent through a child), so the dialog passes
1374 /// its `directory` and `wild_card` at construction and refreshes them via
1375 /// [`set_dir_info`](FileInfoPane::set_dir_info) on each directory change.
1376 /// `file_block` starts as `None`; the pump fills it via
1377 /// [`on_file_focused`](FileInfoPane::on_file_focused) after the first
1378 /// `FILE_FOCUSED` broadcast.
1379 pub fn new(
1380 bounds: crate::view::Rect,
1381 directory: impl Into<String>,
1382 wild_card: impl Into<String>,
1383 ) -> Self {
1384 FileInfoPane {
1385 state: crate::view::ViewState::new(bounds),
1386 directory: directory.into(),
1387 wild_card: wild_card.into(),
1388 file_block: None,
1389 }
1390 }
1391
1392 /// Cache the focused record — called by the pump's
1393 /// [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile) broker on
1394 /// a "file focused" broadcast. `None` means no current file → a blank name. No
1395 /// explicit redraw is needed (the whole tree is redrawn each frame).
1396 pub fn on_file_focused(&mut self, rec: Option<SearchRec>) {
1397 self.file_block = rec;
1398 }
1399
1400 /// Update the cached directory / wildcard ([`FileDialog`]'s `reset_current`
1401 /// and [`FileDialog::valid`](crate::view::View::valid)'s navigate branches drive this when the dialog
1402 /// (re-)reads the directory).
1403 pub fn set_dir_info(&mut self, directory: impl Into<String>, wild_card: impl Into<String>) {
1404 self.directory = directory.into();
1405 self.wild_card = wild_card.into();
1406 }
1407}
1408
1409impl crate::view::View for FileInfoPane {
1410 fn state(&self) -> &crate::view::ViewState {
1411 &self.state
1412 }
1413
1414 fn state_mut(&mut self) -> &mut crate::view::ViewState {
1415 &mut self.state
1416 }
1417
1418 /// Line 0 = the directory + wildcard path; line 1 = the focused name + (when
1419 /// named) its size left-aligned at `size.x-38` and its date as
1420 /// `Mon DD, YYYY HH:MMa/p` in the right columns; remaining rows cleared. All
1421 /// text in [`Role::InfoPane`](crate::theme::Role::InfoPane).
1422 fn draw(&mut self, ctx: &mut crate::view::DrawCtx) {
1423 let color = ctx.style(crate::theme::Role::InfoPane);
1424 let w = self.state.size.x;
1425 let h = self.state.size.y;
1426
1427 // --- line 0: the path (directory + wildcard) ------------------------
1428 // `Rect::new` takes corners (ax, ay, bx, by), not (x, y, w, h).
1429 ctx.fill(crate::view::Rect::new(0, 0, w, 1), ' ', color);
1430 let path = format!("{}{}", self.directory, self.wild_card);
1431 ctx.put_str(1, 0, &path, color);
1432
1433 // --- line 1: name + size + date -------------------------------------
1434 ctx.fill(crate::view::Rect::new(0, 1, w, 2), ' ', color);
1435 if let Some(rec) = &self.file_block
1436 && !rec.name.is_empty()
1437 {
1438 ctx.put_str(1, 1, &rec.name, color);
1439
1440 // size, left-aligned at column size.x - 38.
1441 let size_str = rec.size.to_string();
1442 ctx.put_str(w - 38, 1, &size_str, color);
1443
1444 // Unpack the DOS ftime bitfield (see `pack_dos_time` for the layout).
1445 let t = rec.time as u32;
1446 let date = t >> 16;
1447 let time = t & 0xFFFF;
1448 let month = ((date >> 5) & 0xF) as usize;
1449 let day = date & 0x1F;
1450 let year = (date >> 9) + 1980;
1451 let mut hour = time >> 11;
1452 let minute = (time >> 5) & 0x3F;
1453
1454 // month name at size.x - 22 (index guarded — 0..=12).
1455 let month_name = MONTHS.get(month).copied().unwrap_or("");
1456 ctx.put_str(w - 22, 1, month_name, color);
1457
1458 // zero-padded day at size.x - 18.
1459 ctx.put_str(w - 18, 1, &format!("{day:02}"), color);
1460 ctx.put_char(w - 16, 1, ',', color);
1461 // year (already +1980) at size.x - 15.
1462 ctx.put_str(w - 15, 1, &year.to_string(), color);
1463
1464 // 12-hour clock with a/p suffix, computed into the local `hour`;
1465 // `draw` must not mutate the cached `file_block`.
1466 let pm = hour >= 12;
1467 hour %= 12;
1468 if hour == 0 {
1469 hour = 12;
1470 }
1471 ctx.put_str(w - 9, 1, &format!("{hour:02}"), color);
1472 ctx.put_char(w - 7, 1, ':', color);
1473 ctx.put_str(w - 6, 1, &format!("{minute:02}"), color);
1474 ctx.put_str(w - 4, 1, if pm { PM } else { AM }, color);
1475 }
1476
1477 // --- clear the rest (rows 2..h) -------------------------------------
1478 if h > 2 {
1479 ctx.fill(crate::view::Rect::new(0, 2, w, h), ' ', color);
1480 }
1481 }
1482
1483 /// On a "file focused" broadcast (with a resolvable source) request the
1484 /// payload broker. There is no not-selected guard (unlike the input line) —
1485 /// the pane always reflects the focused file. There is no base event handling
1486 /// to run (a non-selectable pane has none).
1487 fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut crate::view::Context) {
1488 if let crate::event::Event::Broadcast {
1489 command,
1490 source: Some(src),
1491 } = *ev
1492 && command == crate::command::Command::FILE_FOCUSED
1493 && let Some(my_id) = self.state.id()
1494 {
1495 ctx.request_resolve_focused_file(my_id, src);
1496 }
1497 }
1498
1499 /// The pump's broker downcasts the resolved subscriber to `FileInfoPane`, so
1500 /// `as_any_mut` MUST return `self`.
1501 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1502 Some(self)
1503 }
1504}
1505
1506// ---------------------------------------------------------------------------
1507// FileDialog
1508// ---------------------------------------------------------------------------
1509
1510use crate::dialog::Dialog;
1511
1512/// Display width of `s`, skipping `~` hotkey markers — used to size the prompt
1513/// label next to the filename field.
1514fn cstrlen(s: &str) -> i32 {
1515 s.chars()
1516 .filter(|&c| c != '~')
1517 .map(|c| unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) as i32)
1518 .sum()
1519}
1520
1521/// The filename field's byte cap (maximum path length).
1522const MAXPATH: i32 = 255;
1523
1524// ---------------------------------------------------------------------------
1525// Path helpers (native `/` paths). Pure, FS-independent unless noted.
1526// ---------------------------------------------------------------------------
1527
1528/// Resolve `input` against `dir`, lexically.
1529///
1530/// If `input` is absolute (starts with `/`) it stands alone; otherwise it is
1531/// joined onto `dir`. The result is then **lexically normalized** — `.` is
1532/// dropped, `..` pops the previous component, and `//` collapses — by walking
1533/// [`Path::components`]. This is **not** [`std::fs::canonicalize`]: it does no
1534/// FS access and does not resolve symlinks (the expansion is purely textual). A
1535/// trailing `/` on the input is preserved in the returned string so the
1536/// bare-directory test ([`split_dir_file`] / [`FileDialog::get_file_name`]) can
1537/// detect a directory-only path.
1538///
1539/// An **empty `dir`** with a relative `input` yields a *relative* path (the join
1540/// is just `input`). That is only reachable before a caller sets `directory`
1541/// (e.g. under `FD_NO_LOAD_DIR`, where `reset_current`'s initial read is
1542/// skipped) — the directory starts out empty.
1543fn expand_path(dir: &str, input: &str) -> String {
1544 use std::path::{Component, Path, PathBuf};
1545
1546 let joined: PathBuf = if Path::new(input).is_absolute() {
1547 PathBuf::from(input)
1548 } else {
1549 Path::new(dir).join(input)
1550 };
1551
1552 let mut out = PathBuf::new();
1553 for comp in joined.components() {
1554 match comp {
1555 Component::Prefix(_) => {} // no Windows prefixes on native paths
1556 Component::RootDir => out.push("/"),
1557 Component::CurDir => {} // "." — drop
1558 Component::ParentDir => {
1559 // Pop the previous Normal component. At/above an absolute root,
1560 // `..` is absorbed (a `/..`-walk stays at `/`).
1561 match out.components().next_back() {
1562 Some(Component::Normal(_)) => {
1563 out.pop();
1564 }
1565 Some(Component::RootDir) => {} // `/..` → `/`
1566 _ => out.push(".."), // relative leading `..`
1567 }
1568 }
1569 Component::Normal(seg) => out.push(seg),
1570 }
1571 }
1572
1573 let mut s = out.to_string_lossy().into_owned();
1574 if s.is_empty() {
1575 s.push('/');
1576 }
1577 // Preserve a trailing slash from the input (a directory-only path) so the
1578 // wildcard-append in get_file_name fires. `components()` strips it.
1579 if (input.ends_with('/') || input.is_empty()) && !s.ends_with('/') {
1580 s.push('/');
1581 }
1582 s
1583}
1584
1585/// Whether `s` contains a `*` or `?` glob metacharacter.
1586fn is_wild(s: &str) -> bool {
1587 s.contains('*') || s.contains('?')
1588}
1589
1590/// Whether `path` is **directory-only** — has no filename part. True when `path`
1591/// ends with `/`, is `/`, is empty, or its final component is `.`/`..`.
1592///
1593/// NOTE: [`Path::file_name`] alone is **wrong** here — it strips a trailing
1594/// slash, so `Path::new("/a/b/").file_name()` is `Some("b")`. We test the
1595/// trailing slash explicitly first.
1596fn is_dir_only(path: &str) -> bool {
1597 use std::path::{Component, Path};
1598 if path.is_empty() || path.ends_with('/') {
1599 return true;
1600 }
1601 matches!(
1602 Path::new(path).components().next_back(),
1603 Some(Component::RootDir | Component::CurDir | Component::ParentDir) | None
1604 )
1605}
1606
1607/// Split an absolute, normalized path into its directory part (with a trailing
1608/// `/`) and its filename part.
1609///
1610/// A path that ends with `/` (or whose final component is `.`/`..`) has an empty
1611/// filename — equivalently [`Path::file_name`] is `None`. The dir part always
1612/// ends with `/` so it satisfies [`FileList::read_directory`]'s precondition.
1613fn split_dir_file(path: &str) -> (String, String) {
1614 use std::path::Path;
1615 if is_dir_only(path) {
1616 // Directory-only path — the whole thing is the dir, empty file.
1617 let mut d = path.to_string();
1618 if !d.ends_with('/') {
1619 d.push('/');
1620 }
1621 return (d, String::new());
1622 }
1623 let p = Path::new(path);
1624 let file = p
1625 .file_name()
1626 .map(|n| n.to_string_lossy().into_owned())
1627 .unwrap_or_default();
1628 let dir = match p.parent() {
1629 Some(par) => {
1630 let mut d = par.to_string_lossy().into_owned();
1631 if !d.ends_with('/') {
1632 d.push('/');
1633 }
1634 d
1635 }
1636 None => "/".to_string(),
1637 };
1638 (dir, file)
1639}
1640
1641/// Whether `s` names an existing directory (follows symlinks). FS-dependent.
1642fn is_dir(s: &str) -> bool {
1643 std::fs::metadata(s).map(|m| m.is_dir()).unwrap_or(false)
1644}
1645
1646/// Whether the directory `s` exists and is a directory. FS-dependent.
1647fn path_valid(s: &str) -> bool {
1648 std::fs::metadata(s).map(|m| m.is_dir()).unwrap_or(false)
1649}
1650
1651/// Whether `s` has a non-empty filename component and no interior NUL. There are
1652/// no charset restrictions on the name — a non-empty name with a real parent is
1653/// accepted, and the OS rejects a truly invalid name at open time.
1654fn valid_file_name(s: &str) -> bool {
1655 if s.is_empty() || s.contains('\0') {
1656 return false;
1657 }
1658 // A directory-only path (trailing `/`, or final `.`/`..`) has no filename.
1659 !is_dir_only(s)
1660}
1661
1662// Validation message text.
1663const INVALID_DRIVE_TEXT: &str = "Invalid drive or directory";
1664const INVALID_FILE_TEXT: &str = "Invalid file name";
1665
1666// ---------------------------------------------------------------------------
1667// FileDialog option flags (options bitmask passed to FileDialog::new)
1668//
1669// Typical combinations:
1670// Open dialog: FD_OPEN_BUTTON | FD_NO_LOAD_DIR (if pre-constructed)
1671// Save-as dialog: FD_OK_BUTTON | FD_REPLACE_BUTTON
1672// With clear: FD_OPEN_BUTTON | FD_CLEAR_BUTTON
1673// With help: FD_OPEN_BUTTON | FD_HELP_BUTTON
1674//
1675// Use at most one of FD_OK_BUTTON / FD_OPEN_BUTTON (they trigger the same
1676// command, Command::FILE_OPEN; they differ only in button label).
1677// FD_NO_LOAD_DIR may be OR-ed with any button combination.
1678// ---------------------------------------------------------------------------
1679
1680/// Insert an "OK" button that closes the dialog with the selected filename.
1681///
1682/// Pass in the `options` bitmask to [`FileDialog::new`] to add this button.
1683/// Both `FD_OK_BUTTON` and [`FD_OPEN_BUTTON`] trigger `Command::FILE_OPEN`
1684/// (the same close command); the label is "OK" vs "Open". Use at most one of
1685/// the two. Common combination: `FD_OK_BUTTON | FD_REPLACE_BUTTON` for a
1686/// save-as dialog that can overwrite.
1687///
1688/// # Turbo Vision heritage
1689///
1690/// Ports `fdOKButton` (`tfileinp.h`).
1691pub const FD_OK_BUTTON: u16 = 0x0001;
1692/// Insert an "Open" button that closes the dialog with the selected filename.
1693///
1694/// Like [`FD_OK_BUTTON`] but labels the button "Open". Use for a classic
1695/// file-open dialog (e.g. `FD_OPEN_BUTTON | FD_NO_LOAD_DIR`); use
1696/// [`FD_OK_BUTTON`] when the OK label fits better (e.g. a save-as dialog).
1697/// Use at most one of the two.
1698///
1699/// # Turbo Vision heritage
1700///
1701/// Ports `fdOpenButton` (`tfileinp.h`).
1702pub const FD_OPEN_BUTTON: u16 = 0x0002;
1703/// Insert a "Replace" button that closes the dialog with the selected filename.
1704///
1705/// Signals the caller (via `Command::FILE_REPLACE`) that the user accepted an
1706/// overwrite. Use for save-as dialogs alongside [`FD_OK_BUTTON`] (the user can
1707/// click OK without overwrite confirmation, or Replace to explicitly confirm).
1708///
1709/// # Turbo Vision heritage
1710///
1711/// Ports `fdReplaceButton` (`tfileinp.h`).
1712pub const FD_REPLACE_BUTTON: u16 = 0x0004;
1713/// Insert a "Clear" button that closes the dialog without a filename.
1714///
1715/// Signals the caller (via `Command::FILE_CLEAR`) that the associated file
1716/// should be cleared/unlinked. The dialog's `valid()` always passes for this
1717/// command (no path check), and [`FileDialog::value`](crate::view::View::value) returns an empty string.
1718/// Combine with [`FD_OPEN_BUTTON`] or [`FD_OK_BUTTON`] to offer both open and
1719/// clear choices in the same dialog.
1720///
1721/// # Turbo Vision heritage
1722///
1723/// Ports `fdClearButton` (`tfileinp.h`).
1724pub const FD_CLEAR_BUTTON: u16 = 0x0008;
1725/// Insert a "Help" button (posts `Command::HELP`; does not close the dialog).
1726///
1727/// The help button is never the default and never triggers path validation.
1728/// May be OR-ed with any other button flag.
1729///
1730/// While the dialog runs modally, `Command::HELP` reaches only the dialog,
1731/// which ignores it, and is then dropped: a program-level command handler
1732/// (for example `run_app`'s) never sees it. To show help, embed the dialog in
1733/// your own view type (`#[delegate(to = dialog)]`) and handle `Command::HELP`
1734/// in that view's `handle_event`.
1735///
1736/// # Turbo Vision heritage
1737///
1738/// Ports `fdHelpButton` (`tfileinp.h`).
1739pub const FD_HELP_BUTTON: u16 = 0x0010;
1740/// Skip the initial directory read when the dialog opens.
1741///
1742/// By default [`FileDialog::reset_current`](crate::view::View::reset_current) reads the process current directory
1743/// into the file list on first show. Pass `FD_NO_LOAD_DIR` to suppress that
1744/// read — useful when the dialog is constructed before its owner is on screen,
1745/// or when the listing is populated by other means. May be OR-ed with any
1746/// button flag combination.
1747///
1748/// # Turbo Vision heritage
1749///
1750/// Ports `fdNoLoadDir` (`tfileinp.h`).
1751pub const FD_NO_LOAD_DIR: u16 = 0x0100;
1752
1753// --- Change-directory dialog options ----------------------------------------
1754
1755/// Default options for [`ChDirDialog`]: no extra buttons, load the directory
1756/// tree on open.
1757///
1758/// Pass to [`ChDirDialog::new`] as `opts` when you want the standard
1759/// change-directory dialog: an input line, a scrollable directory tree, and
1760/// OK / Chdir / Revert buttons. Same as passing `0`.
1761pub const CD_NORMAL: u16 = 0x0000;
1762
1763/// Suppress the initial directory-tree read when the dialog opens.
1764///
1765/// Pass this flag in `opts` to [`ChDirDialog::new`] when the dialog is
1766/// constructed before its owner is visible, or when you want to populate
1767/// the tree yourself before showing the dialog. Without it, `reset_current`
1768/// populates the tree from the process current directory on first show.
1769pub const CD_NO_LOAD_DIR: u16 = 0x0001;
1770
1771/// Add a "Help" button to the [`ChDirDialog`].
1772///
1773/// Pass this flag in `opts` to [`ChDirDialog::new`] to insert an extra Help
1774/// button that posts `Command::HELP`. Omit it (or use [`CD_NORMAL`]) when
1775/// context-sensitive help is not needed. As with [`FD_HELP_BUTTON`], the
1776/// command reaches only the modal dialog: handle it in a view that embeds
1777/// the dialog, not at program level.
1778pub const CD_HELP_BUTTON: u16 = 0x0002;
1779
1780// Change-directory dialog text. (There is no drive selector — no drives.)
1781const CHANGE_DIR_TITLE: &str = "Change Directory";
1782const DIR_NAME_TEXT: &str = "Directory ~n~ame";
1783const DIR_TREE_TEXT: &str = "Directory ~t~ree";
1784const CHDIR_TEXT: &str = "~C~hdir";
1785const REVERT_TEXT: &str = "~R~evert";
1786const INVALID_DIR_TEXT: &str = "Invalid directory";
1787
1788// Button / label text. `~X~` is tvision-rs's hotkey markup (the widgets parse it).
1789const FILES_TEXT: &str = "~F~iles";
1790const OPEN_TEXT: &str = "~O~pen";
1791const OK_TEXT: &str = "O~K~";
1792const REPLACE_TEXT: &str = "~R~eplace";
1793const CLEAR_TEXT: &str = "~C~lear";
1794const CANCEL_TEXT: &str = "Cancel";
1795const HELP_TEXT: &str = "~H~elp";
1796
1797/// The action-button layout for a given `options` mask — the pure decision the
1798/// constructor realizes into buttons. Each tuple is `(text, command, is_default,
1799/// y_top)`.
1800///
1801/// Only the **first** option button (Open/OK/Replace/Clear, in that order) is the
1802/// default: the four option buttons participate in a default chain that the first
1803/// one consumes. **Cancel is always inserted, and Cancel/Help are never the
1804/// default** — they don't participate in the chain (so a dialog with no option
1805/// buttons has no default button at all). The first button is placed at the top
1806/// of the right column and each subsequent button steps `+3` in y (`y_top` = 3,
1807/// 6, 9, …).
1808fn button_specs(options: u16) -> Vec<(&'static str, crate::command::Command, bool, i32)> {
1809 use crate::command::Command;
1810 let mut specs: Vec<(&'static str, Command, bool, i32)> = Vec::new();
1811 let mut y = 3;
1812 let mut default = true;
1813 // `is_opt` = participates in the default-button chain (the four option buttons).
1814 let push = |specs: &mut Vec<_>, y: &mut i32, default: &mut bool, text, cmd, is_opt: bool| {
1815 let is_default = is_opt && *default;
1816 specs.push((text, cmd, is_default, *y));
1817 if is_opt {
1818 *default = false;
1819 }
1820 *y += 3;
1821 };
1822
1823 if options & FD_OPEN_BUTTON != 0 {
1824 push(
1825 &mut specs,
1826 &mut y,
1827 &mut default,
1828 OPEN_TEXT,
1829 Command::FILE_OPEN,
1830 true,
1831 );
1832 }
1833 if options & FD_OK_BUTTON != 0 {
1834 push(
1835 &mut specs,
1836 &mut y,
1837 &mut default,
1838 OK_TEXT,
1839 Command::FILE_OPEN,
1840 true,
1841 );
1842 }
1843 if options & FD_REPLACE_BUTTON != 0 {
1844 push(
1845 &mut specs,
1846 &mut y,
1847 &mut default,
1848 REPLACE_TEXT,
1849 Command::FILE_REPLACE,
1850 true,
1851 );
1852 }
1853 if options & FD_CLEAR_BUTTON != 0 {
1854 push(
1855 &mut specs,
1856 &mut y,
1857 &mut default,
1858 CLEAR_TEXT,
1859 Command::FILE_CLEAR,
1860 true,
1861 );
1862 }
1863 // Cancel: always inserted, never the default button (is_opt = false).
1864 push(
1865 &mut specs,
1866 &mut y,
1867 &mut default,
1868 CANCEL_TEXT,
1869 Command::CANCEL,
1870 false,
1871 );
1872 if options & FD_HELP_BUTTON != 0 {
1873 push(
1874 &mut specs,
1875 &mut y,
1876 &mut default,
1877 HELP_TEXT,
1878 Command::HELP,
1879 false,
1880 );
1881 }
1882 specs
1883}
1884
1885/// A [`Dialog`] that assembles the file picker — the directory/file panes
1886/// ([`FileList`], [`FileInputLine`], [`FileInfoPane`]) plus a filename label, a
1887/// history icon, a scroll bar, and the action buttons — into a working file
1888/// dialog.
1889///
1890/// The file-selection dialog and its building blocks: [`FileDialog`],
1891/// [`ChDirDialog`], the directory/file panes ([`FileList`], [`DirListBox`],
1892/// [`FileInfoPane`], [`FileInputLine`]), and the data types they hold
1893/// ([`DirEntry`], [`SearchRec`], [`DirCollection`], [`FileCollection`]).
1894///
1895/// [`DirEntry`]/[`SearchRec`]/[`DirCollection`]/[`FileCollection`] are pure data;
1896/// [`DirListBox`] is the directory-tree pane, a concrete
1897/// [`ListViewer`](crate::widgets::list_viewer::ListViewer) over a
1898/// [`Vec<DirEntry>`] that renders a tree-indented listing.
1899///
1900/// Following tvision-rs's "collections become `Vec`" convention, `DirCollection` is a
1901/// plain `Vec<DirEntry>` alias and `FileCollection` is a `Vec<SearchRec>` carrying
1902/// only the one piece of real logic — the sorted insert and its comparator. The
1903/// general-purpose collection API (index-of, remove, replace-at, find-first, …) is
1904/// omitted; nothing here needs it.
1905///
1906/// ## Native paths
1907/// Paths are native and `/`-separated, enumerated with `std::fs::read_dir`. There
1908/// is no DOS drive-letter machinery (drive scanning, `\`-separators); it has no
1909/// Linux counterpart and is omitted.
1910///
1911/// ## Structural shape
1912///
1913/// This **embeds** a [`Dialog`] and forwards the un-overridden
1914/// [`View`](crate::view::View) methods (embed-and-delegate composition). It
1915/// overrides only `handle_event`, `reset_current`, and `as_any_mut` (so the
1916/// modal loop / the owner-downcast target is the `FileDialog`, not the inner
1917/// `Dialog`). The 49×19 minimum (`TFileDialog::sizeLimits`) is pushed into the
1918/// embedded window via `set_min_size` at construction (D16), so every clamp
1919/// path — including the interactive corner drag — honors it through the
1920/// delegated `size_limits`.
1921///
1922/// ## Native paths
1923///
1924/// The initial directory comes from [`std::env::current_dir`], normalized to end
1925/// with `/` (the [`FileList::read_directory`] trailing-slash precondition). No
1926/// drive letters, no backslashes.
1927///
1928/// The screen-relative percentage resize is applied at the first `handle_event`
1929/// call (when `ctx.owner_size()` is available) rather than at construction, since
1930/// there is no `Context` in the constructor; this happens before the first draw.
1931///
1932/// # Turbo Vision heritage
1933///
1934/// Ports the `TFileDialog` family — `TFileDialog`, `TChDirDialog`, `TFileList`,
1935/// `TDirListBox`, `TFileInfoPane`, `TFileInputLine`, plus `TDirEntry`,
1936/// `TSearchRec`, `TDirCollection`, `TFileCollection` (`filedial.cpp`,
1937/// `fileopen.cpp`, `tfildlg.cpp` and headers). The DOS file model is re-imagined
1938/// for native Linux `/`-paths (deviation D14); `TCollection`s become `Vec`s and
1939/// `TStreamable` persistence is dropped (deviation D12).
1940///
1941/// Ports `TFileDialog` (`tfildlg.cpp`/`stddlg.h`), a dialog subclass; here it
1942/// becomes embed-and-delegate composition (deviation D2), the DOS path model
1943/// becomes native `/`-paths (deviation D14), and persistence is dropped
1944/// (deviation D12).
1945pub struct FileDialog {
1946 /// The embedded dialog — the delegation target.
1947 dialog: Dialog,
1948 /// The active glob mask (e.g. `"*.rs"`); pushed to [`FileList`],
1949 /// [`FileInfoPane`], and [`FileInputLine`] whenever the listing is re-read.
1950 /// Updated by `valid`'s wildcard branch when the user types a new mask.
1951 wild_card: String,
1952 /// The current directory being browsed; always `/`-terminated.
1953 /// Set on first show by `reset_current` (from `std::env::current_dir`) and
1954 /// on each navigation step by `valid`'s wildcard/dir branches.
1955 directory: String,
1956 /// The [`FileInputLine`] child's id — read by
1957 /// [`get_file_name`](FileDialog::get_file_name)/[`valid`](FileDialog::valid)
1958 /// (the filename the dialog returns).
1959 file_name_id: crate::view::ViewId,
1960 /// The [`FileList`] child's id — used by `valid`/`navigate` to re-read the
1961 /// directory listing and by `handle_event` to request focus on navigation.
1962 file_list_id: crate::view::ViewId,
1963 /// The [`FileInfoPane`] child's id — used by `reset_current`/`navigate` to
1964 /// push updated directory/wildcard info when the listing changes.
1965 info_pane_id: crate::view::ViewId,
1966 /// One-time guard for the `reset_current` initial directory read.
1967 needs_read_directory: bool,
1968 /// One-time guard for the screen-relative percentage resize.
1969 ///
1970 /// A [`Context`](crate::view::Context) is required to get the screen size via
1971 /// `ctx.owner_size()` and to queue the bounds change — neither is available in
1972 /// the constructor. So the resize fires at the first `handle_event` call where
1973 /// `ctx.owner_size()` is non-zero, before the first dispatch to children (and
1974 /// before the first draw).
1975 needs_screen_resize: bool,
1976 /// Cache of the last [`get_file_name`](FileDialog::get_file_name) result, so
1977 /// the `&self` [`value`](FileDialog::value) can return the resolved filename.
1978 /// `get_file_name` needs `&mut self` (it reads the input line via
1979 /// `child_mut`), and an immutable `child` accessor would live outside this
1980 /// module — so `valid()` (the gate the modal gather runs right before reading
1981 /// `value()`) refreshes this cache. Invariant: the cache is current after any
1982 /// `valid()` call.
1983 resolved_name: String,
1984}
1985
1986impl FileDialog {
1987 /// Build a file dialog with the given mask, title, prompt label, options, and
1988 /// history id.
1989 ///
1990 /// - `wild_card` — initial glob mask (e.g. `"*.rs"`); shown in the filename
1991 /// field and used to filter the file list.
1992 /// - `title` — the dialog window title (e.g. `"Open File"`).
1993 /// - `input_name` — the label above the filename field (e.g. `"~F~ile name"`).
1994 /// - `options` — bitwise OR of `FD_*` constants controlling which action
1995 /// buttons appear and whether the listing loads immediately.
1996 /// - `history_id` — identifies the history bucket for the filename field; use a
1997 /// unique constant per dialog type across the application.
1998 ///
1999 /// Assembles the children in a fixed insertion order (so the labels/history
2000 /// can link to the already-created input-line / file-list ids, and
2001 /// `reset_current` focuses the first selectable = the input line). Each
2002 /// child's `grow_mode` is set before insert for correct resize behaviour.
2003 pub fn new(
2004 wild_card: impl Into<String>,
2005 title: impl Into<String>,
2006 input_name: impl Into<String>,
2007 options: u16,
2008 history_id: u8,
2009 ) -> Self {
2010 use crate::view::{GrowMode, Rect, View};
2011 use crate::widgets::{Button, ButtonFlags, Label, ScrollBar, THistory};
2012
2013 let wild_card = wild_card.into();
2014 let input_name = input_name.into();
2015
2016 // Dialog at (15,1)-(64,20); centered; growable.
2017 let mut dialog = Dialog::new(Rect::new(15, 1, 64, 20), Some(title.into()));
2018 // Centering — reachable via the public View::state_mut() → ViewState.
2019 {
2020 let opts = &mut dialog.state_mut().options;
2021 opts.center_x = true;
2022 opts.center_y = true;
2023 }
2024 // Mark the dialog growable; set_flags/flags are pub(crate) on Dialog.
2025 {
2026 let mut f = dialog.flags();
2027 f.grow = true;
2028 dialog.set_flags(f);
2029 }
2030 // The TFileDialog::sizeLimits floor (49×19), pushed down into the
2031 // window (D16): every clamp path incl. the interactive drag reads it.
2032 dialog.set_min_size(crate::view::Point::new(49, 19));
2033
2034 // --- fileName: filename input line at (3,3)-(31,4), cap MAXPATH ------
2035 // Initial text = the wildcard. Grows on the right edge.
2036 let mut fil = FileInputLine::new(Rect::new(3, 3, 31, 4), MAXPATH, wild_card.clone());
2037 fil.inner.data = wild_card.clone();
2038 fil.inner.state.grow_mode = GrowMode {
2039 hi_x: true,
2040 ..Default::default()
2041 };
2042 let file_name_id = dialog.insert_child(Box::new(fil));
2043
2044 // --- prompt label at (2,2)-(3+len(input_name),3), linked to fileName -
2045 let label_w = 3 + cstrlen(&input_name);
2046 dialog.insert_child(Box::new(Label::new(
2047 Rect::new(2, 2, label_w, 3),
2048 input_name,
2049 Some(file_name_id),
2050 )));
2051
2052 // --- history icon at (31,3)-(34,4), bound to fileName + history_id --
2053 // Grows on both horizontal edges.
2054 let mut hist = THistory::new(Rect::new(31, 3, 34, 4), file_name_id, history_id);
2055 hist.state_mut().grow_mode = GrowMode {
2056 lo_x: true,
2057 hi_x: true,
2058 ..Default::default()
2059 };
2060 dialog.insert_child(Box::new(hist));
2061
2062 // --- scroll bar at (3,14)-(34,15) -----------------------------------
2063 let sb_id = dialog.insert_child(Box::new(ScrollBar::new(Rect::new(3, 14, 34, 15))));
2064
2065 // --- fileList: file list at (3,6)-(34,14), wired to the scroll bar --
2066 // Grows on the right and bottom edges.
2067 let mut fl = FileList::new(Rect::new(3, 6, 34, 14), None, Some(sb_id));
2068 fl.lv.state.grow_mode = GrowMode {
2069 hi_x: true,
2070 hi_y: true,
2071 ..Default::default()
2072 };
2073 let file_list_id = dialog.insert_child(Box::new(fl));
2074
2075 // --- "Files" label at (2,5)-(8,6), linked to fileList ---------------
2076 dialog.insert_child(Box::new(Label::new(
2077 Rect::new(2, 5, 8, 6),
2078 FILES_TEXT,
2079 Some(file_list_id),
2080 )));
2081
2082 // --- the action buttons ---------------------------------------------
2083 // The which/order/default/y decision is the pure `button_specs` helper;
2084 // here we just realize each spec into a button at (35, y)-(46, y+2)
2085 // (grows on both horizontal edges), stepping +3 in y per button.
2086 let grow_lo_hi_x = GrowMode {
2087 lo_x: true,
2088 hi_x: true,
2089 ..Default::default()
2090 };
2091 for (text, cmd, is_default, y) in button_specs(options) {
2092 let flags = if is_default {
2093 ButtonFlags {
2094 default: true,
2095 ..Default::default()
2096 }
2097 } else {
2098 ButtonFlags::new()
2099 };
2100 let mut b = Button::new(Rect::new(35, y, 46, y + 2), text, cmd, flags);
2101 b.state.grow_mode = grow_lo_hi_x;
2102 dialog.insert_child(Box::new(b));
2103 }
2104
2105 // --- infoPane: info pane at (1,16)-(48,18) --------------------------
2106 // Grows on the bottom, right, and top edges.
2107 let mut fip = FileInfoPane::new(Rect::new(1, 16, 48, 18), "", wild_card.clone());
2108 fip.state_mut().grow_mode = GrowMode {
2109 lo_y: true,
2110 hi_x: true,
2111 hi_y: true,
2112 ..Default::default()
2113 };
2114 let info_pane_id = dialog.insert_child(Box::new(fip));
2115
2116 // The modal loop's reset_current establishes currency (focuses the first
2117 // selectable child = the input line, inserted first), so no explicit
2118 // focus advance is needed here (see View::reset_current).
2119
2120 // The screen-relative percentage resize runs at the first handle_event
2121 // (it needs ctx.owner_size()). See the `needs_screen_resize` field doc
2122 // for the full note.
2123
2124 FileDialog {
2125 dialog,
2126 wild_card,
2127 directory: String::new(),
2128 file_name_id,
2129 file_list_id,
2130 info_pane_id,
2131 needs_read_directory: options & FD_NO_LOAD_DIR == 0,
2132 needs_screen_resize: true,
2133 resolved_name: String::new(),
2134 }
2135 }
2136
2137 /// Resolve the input-line text into an absolute, normalized filename relative
2138 /// to `directory`.
2139 ///
2140 /// Steps: expand the field text against `directory`
2141 /// (`expand_path`), then split off the filename (`split_dir_file`); when
2142 /// the resolved path is a **bare directory** (no filename part) the wildcard is
2143 /// appended. With native paths the wildcard *is* its own filename, so
2144 /// `self.wild_card` is appended directly.
2145 ///
2146 /// `&mut self` (not `&self`): it reads the [`FileInputLine`] via `child_mut`.
2147 /// It is only called from [`valid`](crate::view::View::valid) (which has `&mut self`)
2148 /// and refreshes `resolved_name` so the `&self`
2149 /// [`value`](crate::view::View::value) can return the result without `child_mut`.
2150 pub fn get_file_name(&mut self) -> String {
2151 let field_text = self
2152 .dialog
2153 .child_mut(self.file_name_id)
2154 .and_then(|v| v.as_any_mut())
2155 .and_then(|a| a.downcast_mut::<FileInputLine>())
2156 .map(|fil| fil.text().to_string())
2157 .unwrap_or_default();
2158
2159 let expanded = expand_path(&self.directory, &field_text);
2160
2161 // Append the wildcard's filename when the resolved path is directory-only
2162 // (see `is_dir_only` — `Path::file_name` alone is wrong, it strips a
2163 // trailing slash).
2164 let resolved = if is_dir_only(&expanded) {
2165 let mut s = expanded;
2166 if !s.ends_with('/') {
2167 s.push('/');
2168 }
2169 s.push_str(&self.wild_card);
2170 s
2171 } else {
2172 expanded
2173 };
2174
2175 self.resolved_name = resolved.clone();
2176 resolved
2177 }
2178
2179 /// Returns `true` when `path` is a valid directory; otherwise pops an
2180 /// informational "invalid drive/dir" error box, refocuses the filename field,
2181 /// and returns `false`.
2182 ///
2183 /// The box is a plain OK-button error with no answer routing, raised via the
2184 /// async-modal-from-a-view seam: `valid()` requests it and returns false;
2185 /// `validate_modal_close` drives it inline and keeps the (false) result.
2186 fn check_directory(&mut self, path: &str, ctx: &mut crate::view::Context) -> bool {
2187 if path_valid(path) {
2188 true
2189 } else {
2190 ctx.request_message_box(
2191 format!("{INVALID_DRIVE_TEXT}: '{path}'"),
2192 crate::dialog::MessageBoxKind::Error,
2193 crate::dialog::MessageBoxButtons::ok(),
2194 None,
2195 None,
2196 );
2197 ctx.request_focus(self.file_name_id);
2198 false
2199 }
2200 }
2201
2202 /// Re-read `directory` into the [`FileList`] and refresh the info pane /
2203 /// input-line caches — the navigation tail shared by the wildcard and
2204 /// directory branches of [`valid`](FileDialog::valid). Mutates the children
2205 /// directly (the dialog owns the group), like `reset_current`.
2206 fn navigate(&mut self, ctx: &mut crate::view::Context) {
2207 let dir = self.directory.clone();
2208 let wild = self.wild_card.clone();
2209 if let Some(fl) = self
2210 .dialog
2211 .child_mut(self.file_list_id)
2212 .and_then(|v| v.as_any_mut())
2213 .and_then(|a| a.downcast_mut::<FileList>())
2214 {
2215 fl.read_directory(&dir, &wild, ctx);
2216 }
2217 if let Some(fip) = self
2218 .dialog
2219 .child_mut(self.info_pane_id)
2220 .and_then(|v| v.as_any_mut())
2221 .and_then(|a| a.downcast_mut::<FileInfoPane>())
2222 {
2223 fip.set_dir_info(&dir, &wild);
2224 }
2225 // Refresh the input line's cached wildcard; without this the next
2226 // directory focus would append the stale mask. The directory branch leaves
2227 // wild_card unchanged, so this is a no-op there.
2228 if let Some(fil) = self
2229 .dialog
2230 .child_mut(self.file_name_id)
2231 .and_then(|v| v.as_any_mut())
2232 .and_then(|a| a.downcast_mut::<FileInputLine>())
2233 {
2234 fil.set_wild_card(&wild);
2235 }
2236 }
2237}
2238
2239#[crate::delegate(
2240 to = dialog,
2241 skip(
2242 apply_scroll_sync,
2243 as_any_mut,
2244 calc_bounds,
2245 grabs_focus_on_click,
2246 select_window_num,
2247 set_value,
2248 value
2249 )
2250)]
2251impl crate::view::View for FileDialog {
2252 /// Run the embedded dialog's event handling first, then:
2253 /// - a file-open / file-replace / file-clear command → end the modal loop with
2254 /// that command + clear the event. (The path-check gate is `valid()`, run by
2255 /// the modal loop on close.)
2256 /// - a "file double-clicked" broadcast → re-post as an OK command + clear. The
2257 /// embedded dialog then turns the OK into a modal close on the next cycle.
2258 ///
2259 /// **One-time pre-delegate work** (before the embedded call): if
2260 /// `needs_screen_resize` is true and the screen size is available from
2261 /// `ctx.owner_size()`, applies the screen-relative percentage resize. It runs
2262 /// at the first `handle_event` where `ctx.owner_size()` is non-zero (set by the
2263 /// owning group), before any event reaches the children — so before the first
2264 /// draw.
2265 fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut crate::view::Context) {
2266 use crate::command::Command;
2267 use crate::event::Event;
2268
2269 // Screen-relative percentage resize. It runs at the first `handle_event`
2270 // where `ctx.owner_size()` (set by the owning group's `handle_event`
2271 // bracket) is non-zero. Before-first-draw ordering is preserved: no event
2272 // is dispatched to children before this fires.
2273 if self.needs_screen_resize {
2274 let screen_size = ctx.owner_size();
2275 if screen_size.x > 0 {
2276 self.needs_screen_resize = false;
2277 let original = crate::view::View::state(self).get_bounds();
2278 let mut bounds = original;
2279 let screen_bounds = crate::view::Rect::new(0, 0, screen_size.x, screen_size.y);
2280 if screen_size.x > 90 {
2281 bounds.grow(15, 0); // new width 79
2282 } else if screen_size.x > 63 {
2283 let mut sb = screen_bounds;
2284 sb.grow(-7, 0);
2285 bounds.a.x = sb.a.x;
2286 bounds.b.x = sb.b.x;
2287 }
2288 if screen_size.y > 34 {
2289 bounds.grow(0, 5); // new height 29
2290 } else if screen_size.y > 25 {
2291 let mut sb = screen_bounds;
2292 sb.grow(0, -3);
2293 bounds.a.y = sb.a.y;
2294 bounds.b.y = sb.b.y;
2295 }
2296 // Apply the size floor. C++ applies this resize via locate(),
2297 // which clamps through sizeLimits; the ChangeBounds deferred
2298 // applies raw change_bounds, so clamp here by hand — reading
2299 // the floor from size_limits (single source: the window's
2300 // min_size, 49×19).
2301 let (floor, _) = crate::view::View::size_limits(self, screen_size);
2302 let w = (bounds.b.x - bounds.a.x).max(floor.x);
2303 let h = (bounds.b.y - bounds.a.y).max(floor.y);
2304 bounds.b.x = bounds.a.x + w;
2305 bounds.b.y = bounds.a.y + h;
2306 // Only queue if the bounds actually changed.
2307 if bounds != original
2308 && let Some(id) = crate::view::View::state(self).id()
2309 {
2310 ctx.request_bounds(id, bounds);
2311 }
2312 }
2313 }
2314
2315 // The embedded dialog handles the event first.
2316 self.dialog.handle_event(ev, ctx);
2317
2318 match *ev {
2319 // The path-check gate is `valid()`, NOT a manual call here: the modal
2320 // loop runs `validate_modal_close → valid(end_state)` on this
2321 // `end_modal`, so implementing `valid()` *is* the gate. A manual
2322 // pre-check would double-validate.
2323 Event::Command(c)
2324 if matches!(
2325 c,
2326 Command::FILE_OPEN | Command::FILE_REPLACE | Command::FILE_CLEAR
2327 ) =>
2328 {
2329 ctx.end_modal(c);
2330 ev.clear();
2331 }
2332 // "file double-clicked" → re-post an OK command, then clear.
2333 Event::Broadcast {
2334 command: Command::FILE_DOUBLE_CLICKED,
2335 ..
2336 } => {
2337 ctx.post(Command::OK);
2338 ev.clear();
2339 }
2340 _ => {}
2341 }
2342 }
2343
2344 /// Framework init hook: called by the modal loop when the dialog first becomes
2345 /// the current view (i.e., when `Program::run_modal` activates it).
2346 ///
2347 /// Focuses the filename input line, then — once, unless `FD_NO_LOAD_DIR` was
2348 /// passed to [`FileDialog::new`] — reads `std::env::current_dir` into the
2349 /// [`FileList`] (with scrollbar sync and focused-file broadcast) and refreshes
2350 /// the [`FileInfoPane`]'s cached directory and wildcard. You do not call this
2351 /// directly; use `FD_NO_LOAD_DIR` to suppress the initial directory read if the
2352 /// dialog is shown before the working directory is set.
2353 fn reset_current(&mut self, ctx: &mut crate::view::Context) {
2354 self.dialog.reset_current(ctx);
2355
2356 if self.needs_read_directory {
2357 self.needs_read_directory = false;
2358 // The initial directory from std::env::current_dir, not a DOS
2359 // current-directory query.
2360 let dir = std::env::current_dir()
2361 .ok()
2362 .and_then(|p| p.to_str().map(String::from))
2363 .unwrap_or_else(|| "/".into());
2364 // Trailing-slash precondition for FileList::read_directory.
2365 let dir = if dir.ends_with('/') {
2366 dir
2367 } else {
2368 format!("{dir}/")
2369 };
2370 self.directory = dir.clone();
2371 let wild = self.wild_card.clone();
2372
2373 // FileList ctx-ful read: builds + scrollbar sync + focused-file
2374 // broadcast (the broker updates the info pane / input line).
2375 if let Some(fl) = self
2376 .dialog
2377 .child_mut(self.file_list_id)
2378 .and_then(|v| v.as_any_mut())
2379 .and_then(|a| a.downcast_mut::<FileList>())
2380 {
2381 fl.read_directory(&dir, &wild, ctx);
2382 }
2383 // Push the dir/wildcard to the info pane (direct child mutation — the
2384 // dialog owns the group, so this is NOT a cross-view broker).
2385 if let Some(fip) = self
2386 .dialog
2387 .child_mut(self.info_pane_id)
2388 .and_then(|v| v.as_any_mut())
2389 .and_then(|a| a.downcast_mut::<FileInfoPane>())
2390 {
2391 fip.set_dir_info(&dir, &wild);
2392 }
2393 }
2394 }
2395
2396 /// The modal loop and any owner-downcast target must reach the `FileDialog`,
2397 /// so `as_any_mut` returns `self`, NOT the inner `Dialog`.
2398 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
2399 Some(self)
2400 }
2401
2402 /// The navigate/accept gate.
2403 ///
2404 /// - On the VALID command → `true` immediately, *before* the group check.
2405 /// - else run the embedded dialog's group validation first; on its `false`
2406 /// → `false` (keep open).
2407 /// - on group-valid, for the accept commands (NOT cancel / file-clear):
2408 /// resolve the filename, then
2409 /// - **wildcard** → NAVIGATE: split into dir+wildcard, check the directory,
2410 /// on success set `directory`/`wild_card` + re-read; always fall through to
2411 /// `false` (keep open).
2412 /// - **existing directory** → NAVIGATE into it: check it, on success append
2413 /// `/`, set `directory`, re-read; `false`.
2414 /// - **valid filename** → ACCEPT (`true`).
2415 /// - else → "invalid file name" box + `false`.
2416 /// - cancel / file-clear → `true` (always valid, *after* the group check —
2417 /// file-clear must still pass the group).
2418 ///
2419 /// Refreshes `resolved_name` via `get_file_name`
2420 /// for every non-VALID command, so the `&self` `value()` is current after any
2421 /// such call — including the cancel / file-clear path that returns before the
2422 /// branches.
2423 fn valid(&mut self, cmd: crate::command::Command, ctx: &mut crate::view::Context) -> bool {
2424 use crate::command::Command;
2425
2426 // The VALID command → true immediately, before the group check.
2427 if cmd == Command::VALID {
2428 return true;
2429 }
2430
2431 // The embedded dialog's group validation runs first.
2432 if !self.dialog.valid(cmd, ctx) {
2433 return false;
2434 }
2435
2436 // Resolve the filename UNCONDITIONALLY. Its side effect — refreshing
2437 // `self.resolved_name` — is what keeps the `&self` `value()` current even
2438 // on the cancel / file-clear path that returns before the navigate/accept
2439 // branches. Harmless for those commands (it only reads the field + caches).
2440 let f_name = self.get_file_name();
2441
2442 // cancel / file-clear are always valid (after the group validation).
2443 if cmd == Command::CANCEL || cmd == Command::FILE_CLEAR {
2444 return true;
2445 }
2446
2447 if is_wild(&f_name) {
2448 // NAVIGATE: change the wildcard + directory, re-read. Falls through
2449 // to `false` (keep the dialog open) regardless of the directory check.
2450 let (dir, file) = split_dir_file(&f_name);
2451 if self.check_directory(&dir, ctx) {
2452 self.directory = dir;
2453 self.wild_card = file;
2454 if cmd != Command::FILE_INIT {
2455 ctx.request_focus(self.file_list_id);
2456 }
2457 self.navigate(ctx);
2458 }
2459 false
2460 } else if is_dir(&f_name) {
2461 // NAVIGATE into an existing directory.
2462 if self.check_directory(&f_name, ctx) {
2463 let mut dir = f_name;
2464 if !dir.ends_with('/') {
2465 dir.push('/');
2466 }
2467 self.directory = dir;
2468 if cmd != Command::FILE_INIT {
2469 ctx.request_focus(self.file_list_id);
2470 }
2471 self.navigate(ctx);
2472 }
2473 false
2474 } else if valid_file_name(&f_name) {
2475 // ACCEPT — a real filename.
2476 true
2477 } else {
2478 ctx.request_message_box(
2479 format!("{INVALID_FILE_TEXT}: '{f_name}'"),
2480 crate::dialog::MessageBoxKind::Error,
2481 crate::dialog::MessageBoxButtons::ok(),
2482 None,
2483 None,
2484 );
2485 false
2486 }
2487 }
2488
2489 /// Returns the resolved filename as `FieldValue::Text(path)`.
2490 ///
2491 /// The modal gather reads this immediately after `valid(end_state)` returns
2492 /// `true`, so you typically access it indirectly: run the dialog modally, then
2493 /// call `dialog.value()` (or let the gather scatter it). On a cancel or
2494 /// file-clear close the value is still valid — `valid()` resolves the field text
2495 /// unconditionally on every non-VALID command, so the cache is always current.
2496 fn value(&self) -> Option<crate::data::FieldValue> {
2497 Some(crate::data::FieldValue::Text(self.resolved_name.clone()))
2498 }
2499
2500 /// Pre-fill the filename field from a [`FieldValue::Text`](crate::data::FieldValue::Text).
2501 ///
2502 /// Use this before the dialog opens to seed the field with a default path (the
2503 /// scatter half of dialog data transfer). Note that `set_value` cannot also
2504 /// trigger a directory navigation or focus request, because it has no
2505 /// `&mut Context` — if you need the listing to reflect the pre-filled path,
2506 /// let `reset_current` handle it (which reads the process cwd on first show)
2507 /// or open the dialog without `FD_NO_LOAD_DIR`.
2508 fn set_value(&mut self, v: crate::data::FieldValue) {
2509 // Forward to the FileInputLine, whose View::set_value delegates to the
2510 // embedded InputLine::set_value (copy text + select-all). We resolve by id
2511 // rather than downcasting to a concrete type so the delegation runs.
2512 if let Some(fil) = self.dialog.child_mut(self.file_name_id) {
2513 crate::view::View::set_value(fil, v);
2514 }
2515 }
2516}
2517
2518// ---------------------------------------------------------------------------
2519// ChDirDialog
2520// ---------------------------------------------------------------------------
2521
2522/// A [`Dialog`] that lets the user change the process current directory,
2523/// assembling a path input line, a directory-tree pane ([`DirListBox`]), a
2524/// history icon, and the OK / Chdir / Revert (and optional Help) buttons.
2525///
2526/// ## Structural shape
2527///
2528/// Like [`FileDialog`], this **embeds** a [`Dialog`] and forwards the
2529/// un-overridden [`View`](crate::view::View) methods (embed-and-delegate
2530/// composition). It overrides only `handle_event`, `reset_current`, and
2531/// `as_any_mut`. `value`/`set_value` are left at the trait default (`None` /
2532/// no-op) because the dialog carries no transfer data; this stops the macro
2533/// forwarding to the inner `Dialog`'s gather/scatter. The 48×18 minimum
2534/// (`TChDirDialog::sizeLimits`) is pushed into the embedded window via
2535/// `set_min_size` at construction (D16), so every clamp path — including the
2536/// interactive corner drag — honors it through the delegated `size_limits`.
2537///
2538/// ## Native paths
2539///
2540/// `/`-separated, root `/`, no drives, no backslashes, no "Drives" entry. The
2541/// initial directory comes from [`std::env::current_dir`]; the revert action
2542/// re-reads the **live** cwd (not a saved baseline — there is no `directory`
2543/// field); `valid`'s accept does the real change-directory via
2544/// [`std::env::set_current_dir`].
2545///
2546/// # Turbo Vision heritage
2547/// Ports `TChDirDialog` (`tchdrdlg.cpp`/`stddlg.h`), a dialog subclass; here it
2548/// becomes embed-and-delegate composition (deviation D2), the DOS drive model
2549/// becomes native `/`-paths (deviation D14), and persistence is dropped
2550/// (deviation D12).
2551pub struct ChDirDialog {
2552 /// The embedded dialog — the delegation target for all un-overridden
2553 /// `View` methods. `handle_event` delegates to it first, then handles
2554 /// `REVERT` and `CHANGE_DIR` itself.
2555 dialog: Dialog,
2556 /// Id of the path `InputLine` child. Read by `handle_event` and `valid`
2557 /// via `dialog.child_mut(dir_input_id)` to get or set the typed path.
2558 dir_input_id: crate::view::ViewId,
2559 /// Id of the `DirListBox` child. Read by `handle_event` to call
2560 /// `new_directory` on the dir list, and used to wire the chdir button
2561 /// during `new` (post-assembly `set_chdir_button` call).
2562 dir_list_id: crate::view::ViewId,
2563 /// Id of the Chdir `Button`. Stored only so it can be passed to
2564 /// `DirListBox::set_chdir_button` during `new`; the button manages its
2565 /// own default state through the `MakeButtonDefault` deferred channel.
2566 chdir_button_id: crate::view::ViewId,
2567 /// `true` until the first `reset_current` call (set to `false` there).
2568 /// When `CD_NO_LOAD_DIR` is set, `reset_current` skips the dir read and
2569 /// clears this flag — so subsequent calls are also no-ops until the next
2570 /// construction.
2571 needs_setup: bool,
2572}
2573
2574impl ChDirDialog {
2575 /// Build a change-directory dialog with the given options and history id.
2576 ///
2577 /// Assembles the children in a fixed insertion order (so the labels link to
2578 /// the already-created input-line / dir-list ids, and `reset_current` focuses
2579 /// the first selectable = the input line). Each child's `grow_mode` is set
2580 /// before insert for correct resize behaviour.
2581 pub fn new(opts: u16, history_id: u8) -> Self {
2582 use crate::view::{GrowMode, Rect, View};
2583 use crate::widgets::{
2584 Button, ButtonFlags, InputLine, Label, LimitMode, ScrollBar, THistory,
2585 };
2586
2587 // Dialog at (16,2)-(64,20) titled "Change Directory"; centered; growable.
2588 let mut dialog = Dialog::new(Rect::new(16, 2, 64, 20), Some(CHANGE_DIR_TITLE.into()));
2589 {
2590 let opts = &mut dialog.state_mut().options;
2591 opts.center_x = true;
2592 opts.center_y = true;
2593 }
2594 // Mark the dialog growable; set_flags/flags are pub(crate) on Dialog.
2595 {
2596 let mut f = dialog.flags();
2597 f.grow = true;
2598 dialog.set_flags(f);
2599 }
2600 // The TChDirDialog::sizeLimits floor (48×18), pushed down into the
2601 // window (D16).
2602 dialog.set_min_size(crate::view::Point::new(48, 18));
2603
2604 // --- dirInput: path input line at (3,3)-(42,4), cap MAXPATH-1 --------
2605 // Grows on the right edge. InputLine::new(MaxBytes) applies its own
2606 // `limit-1`, so passing MAXPATH-1 yields an effective max of MAXPATH-2.
2607 let mut dir_input = InputLine::new(
2608 Rect::new(3, 3, 42, 4),
2609 MAXPATH - 1,
2610 None,
2611 LimitMode::MaxBytes,
2612 );
2613 dir_input.state_mut().grow_mode = GrowMode {
2614 hi_x: true,
2615 ..Default::default()
2616 };
2617 let dir_input_id = dialog.insert_child(Box::new(dir_input));
2618
2619 // --- "Directory name" label at (2,2)-(17,3), linked to dirInput ------
2620 dialog.insert_child(Box::new(Label::new(
2621 Rect::new(2, 2, 17, 3),
2622 DIR_NAME_TEXT,
2623 Some(dir_input_id),
2624 )));
2625
2626 // --- history icon at (42,3)-(45,4), bound to dirInput + history_id ---
2627 // Grows on both horizontal edges.
2628 let mut hist = THistory::new(Rect::new(42, 3, 45, 4), dir_input_id, history_id);
2629 hist.state_mut().grow_mode = GrowMode {
2630 lo_x: true,
2631 hi_x: true,
2632 ..Default::default()
2633 };
2634 dialog.insert_child(Box::new(hist));
2635
2636 // --- scroll bar at (32,6)-(33,16) ------------------------------------
2637 let sb_id = dialog.insert_child(Box::new(ScrollBar::new(Rect::new(32, 6, 33, 16))));
2638
2639 // --- dirList: dir list at (3,6)-(32,16), wired to the scroll bar -----
2640 // Grows on the right and bottom edges.
2641 let mut dir_list = DirListBox::new(Rect::new(3, 6, 32, 16), None, Some(sb_id));
2642 dir_list.lv.state.grow_mode = GrowMode {
2643 hi_x: true,
2644 hi_y: true,
2645 ..Default::default()
2646 };
2647 let dir_list_id = dialog.insert_child(Box::new(dir_list));
2648
2649 // --- "Directory tree" label at (2,5)-(17,6), linked to dirList ------
2650 dialog.insert_child(Box::new(Label::new(
2651 Rect::new(2, 5, 17, 6),
2652 DIR_TREE_TEXT,
2653 Some(dir_list_id),
2654 )));
2655
2656 let grow_lo_hi_x = GrowMode {
2657 lo_x: true,
2658 hi_x: true,
2659 ..Default::default()
2660 };
2661
2662 // --- okButton: "OK" at (35,6)-(45,8), OK command, default -----------
2663 let mut ok_button = Button::new(
2664 Rect::new(35, 6, 45, 8),
2665 OK_TEXT,
2666 crate::command::Command::OK,
2667 ButtonFlags {
2668 default: true,
2669 ..Default::default()
2670 },
2671 );
2672 ok_button.state.grow_mode = grow_lo_hi_x;
2673 dialog.insert_child(Box::new(ok_button));
2674
2675 // --- chDirButton: "Chdir" at (35,9)-(45,11), change-dir command -----
2676 let mut chdir_button = Button::new(
2677 Rect::new(35, 9, 45, 11),
2678 CHDIR_TEXT,
2679 crate::command::Command::CHANGE_DIR,
2680 ButtonFlags::new(),
2681 );
2682 chdir_button.state.grow_mode = grow_lo_hi_x;
2683 let chdir_button_id = dialog.insert_child(Box::new(chdir_button));
2684
2685 // --- revertButton: "Revert" at (35,12)-(45,14), revert command ------
2686 let mut revert_button = Button::new(
2687 Rect::new(35, 12, 45, 14),
2688 REVERT_TEXT,
2689 crate::command::Command::REVERT,
2690 ButtonFlags::new(),
2691 );
2692 revert_button.state.grow_mode = grow_lo_hi_x;
2693 dialog.insert_child(Box::new(revert_button));
2694
2695 // --- helpButton: "Help" at (35,15)-(45,17), help command ------------
2696 // Inserted only when the help-button option is set.
2697 if opts & CD_HELP_BUTTON != 0 {
2698 let mut help_button = Button::new(
2699 Rect::new(35, 15, 45, 17),
2700 HELP_TEXT,
2701 crate::command::Command::HELP,
2702 ButtonFlags::new(),
2703 );
2704 help_button.state.grow_mode = grow_lo_hi_x;
2705 dialog.insert_child(Box::new(help_button));
2706 }
2707
2708 // reset_current establishes currency (focuses the first selectable child
2709 // = dirInput, inserted first) — see View::reset_current.
2710
2711 let mut cd = ChDirDialog {
2712 dialog,
2713 dir_input_id,
2714 dir_list_id,
2715 chdir_button_id,
2716 needs_setup: opts & CD_NO_LOAD_DIR == 0,
2717 };
2718 // Wire the chdir button into the dir list so its focus (un-)defaults it.
2719 // Both ids are now known, so this is an after-insert child_mut reading the
2720 // stored `chdir_button_id`.
2721 cd.wire_chdir_button();
2722 cd
2723 }
2724
2725 /// Hand the dir list the chdir-button id so its focus changes (un-)default the
2726 /// button. Called once from the constructor.
2727 fn wire_chdir_button(&mut self) {
2728 let btn = self.chdir_button_id;
2729 if let Some(dl) = self
2730 .dialog
2731 .child_mut(self.dir_list_id)
2732 .and_then(|v| v.as_any_mut())
2733 .and_then(|a| a.downcast_mut::<DirListBox>())
2734 {
2735 dl.set_chdir_button(btn);
2736 }
2737 }
2738
2739 /// Trim a single trailing `/` from `path`, **keeping the bare root `/`** (the
2740 /// `len > 1` guard protects it).
2741 fn trim_end_separator(path: &str) -> String {
2742 if path.len() > 1 && path.ends_with('/') {
2743 path[..path.len() - 1].to_string()
2744 } else {
2745 path.to_string()
2746 }
2747 }
2748
2749 /// Read the current process directory as a `/`-terminated absolute path (via
2750 /// `std::env::current_dir`), falling back to `/` when it cannot be read.
2751 fn current_dir_normalized() -> String {
2752 let dir = std::env::current_dir()
2753 .ok()
2754 .and_then(|p| p.to_str().map(String::from))
2755 .unwrap_or_else(|| "/".into());
2756 if dir.ends_with('/') {
2757 dir
2758 } else {
2759 format!("{dir}/")
2760 }
2761 }
2762
2763 /// The navigation tail shared by the revert action and a successful
2764 /// change-directory: re-read `dir` into the [`DirListBox`], reflect the trimmed
2765 /// path in the path input line, and focus the dir list. Mutates the children
2766 /// directly (the dialog owns the group), sequenced like
2767 /// [`FileDialog::navigate`] (one `child_mut` borrow at a time).
2768 fn navigate_to(&mut self, dir: &str, ctx: &mut crate::view::Context) {
2769 if let Some(dl) = self
2770 .dialog
2771 .child_mut(self.dir_list_id)
2772 .and_then(|v| v.as_any_mut())
2773 .and_then(|a| a.downcast_mut::<DirListBox>())
2774 {
2775 dl.new_directory(dir, ctx);
2776 }
2777 let trimmed = Self::trim_end_separator(dir);
2778 if let Some(input) = self.dialog.child_mut(self.dir_input_id) {
2779 crate::view::View::set_value(input, crate::data::FieldValue::Text(trimmed));
2780 }
2781 // Make the dir list the current view.
2782 ctx.request_focus(self.dir_list_id);
2783 }
2784}
2785
2786#[crate::delegate(
2787 to = dialog,
2788 skip(
2789 apply_scroll_sync,
2790 as_any_mut,
2791 calc_bounds,
2792 grabs_focus_on_click,
2793 select_window_num,
2794 set_value,
2795 value
2796 )
2797)]
2798impl crate::view::View for ChDirDialog {
2799 /// Run the embedded dialog's event handling first, then handle the revert /
2800 /// change-directory commands:
2801 /// - revert → re-read the **live** cwd.
2802 /// - change-directory → read the **focused** dir-list entry's path; if it
2803 /// starts with `/` append a trailing `/`; otherwise return leaving the event
2804 /// uncleared (it passes through — it is not cleared).
2805 ///
2806 /// Both feed the shared navigate tail (`navigate_to`):
2807 /// re-read the directory → reflect in the path input line → focus the dir list,
2808 /// then clear.
2809 fn handle_event(&mut self, ev: &mut crate::event::Event, ctx: &mut crate::view::Context) {
2810 use crate::command::Command;
2811 use crate::event::Event;
2812
2813 // The embedded dialog handles the event first.
2814 self.dialog.handle_event(ev, ctx);
2815
2816 if let Event::Command(c) = *ev {
2817 let cur_dir = match c {
2818 Command::REVERT => Self::current_dir_normalized(),
2819 Command::CHANGE_DIR => {
2820 // Read the focused entry's path directly.
2821 let focused = self
2822 .dialog
2823 .child_mut(self.dir_list_id)
2824 .and_then(|v| v.as_any_mut())
2825 .and_then(|a| a.downcast_mut::<DirListBox>())
2826 .and_then(|dl| dl.focused_entry().map(|e| e.dir().to_string()));
2827 let Some(mut path) = focused else {
2828 return;
2829 };
2830 // Only a `/`-rooted path is navigable here. Anything else →
2831 // return, leaving the event uncleared (it passes through).
2832 if path.starts_with('/') {
2833 if !path.ends_with('/') {
2834 path.push('/');
2835 }
2836 path
2837 } else {
2838 return;
2839 }
2840 }
2841 _ => return,
2842 };
2843
2844 self.navigate_to(&cur_dir, ctx);
2845 ev.clear();
2846 }
2847 }
2848
2849 /// The ctx-bearing init hook. Establishes the dialog's internal currency first
2850 /// (focuses the path input line), then, once, does the initial directory read:
2851 /// the live cwd (`/`-terminated) is read into the [`DirListBox`] and reflected
2852 /// (trimmed) into the path input line.
2853 fn reset_current(&mut self, ctx: &mut crate::view::Context) {
2854 self.dialog.reset_current(ctx);
2855
2856 if self.needs_setup {
2857 self.needs_setup = false;
2858 let dir = Self::current_dir_normalized();
2859 if let Some(dl) = self
2860 .dialog
2861 .child_mut(self.dir_list_id)
2862 .and_then(|v| v.as_any_mut())
2863 .and_then(|a| a.downcast_mut::<DirListBox>())
2864 {
2865 dl.new_directory(&dir, ctx);
2866 }
2867 let trimmed = Self::trim_end_separator(&dir);
2868 if let Some(input) = self.dialog.child_mut(self.dir_input_id) {
2869 crate::view::View::set_value(input, crate::data::FieldValue::Text(trimmed));
2870 }
2871 }
2872 }
2873
2874 /// The modal loop and any owner-downcast target must reach the `ChDirDialog`,
2875 /// so `as_any_mut` returns `self`, NOT the inner `Dialog`.
2876 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
2877 Some(self)
2878 }
2879
2880 /// The accept gate. On an OK command it reads the path input line, expands it
2881 /// relative to the live cwd, trims the trailing separator, and attempts the
2882 /// **real** directory change ([`std::env::set_current_dir`]). On error → an
2883 /// informational "Invalid directory" box + `false` (the cwd is untouched —
2884 /// `set_current_dir` does not mutate on error). Any other command is always
2885 /// valid.
2886 fn valid(&mut self, cmd: crate::command::Command, ctx: &mut crate::view::Context) -> bool {
2887 if cmd != crate::command::Command::OK {
2888 return true;
2889 }
2890
2891 // Read the path input line's text (value protocol → FieldValue::Text).
2892 let field_text = self
2893 .dialog
2894 .child_mut(self.dir_input_id)
2895 .and_then(|v| v.value())
2896 .and_then(|val| match val {
2897 crate::data::FieldValue::Text(s) => Some(s),
2898 _ => None,
2899 })
2900 .unwrap_or_default();
2901
2902 // Expand relative to the live cwd as the base, then trim the trailing
2903 // separator.
2904 let base = Self::current_dir_normalized();
2905 let expanded = expand_path(&base, &field_text);
2906 let path = Self::trim_end_separator(&expanded);
2907
2908 // The REAL process cwd change.
2909 if std::env::set_current_dir(&path).is_err() {
2910 ctx.request_message_box(
2911 format!("{INVALID_DIR_TEXT}: '{path}'."),
2912 crate::dialog::MessageBoxKind::Error,
2913 crate::dialog::MessageBoxButtons::ok(),
2914 None,
2915 None,
2916 );
2917 false
2918 } else {
2919 true
2920 }
2921 }
2922}
2923
2924// ---------------------------------------------------------------------------
2925// Tests
2926// ---------------------------------------------------------------------------
2927
2928#[cfg(test)]
2929mod tests {
2930 use super::*;
2931
2932 // Helper: build a SearchRec with a given name and optional dir-flag.
2933 fn rec(name: &str, is_dir: bool) -> SearchRec {
2934 SearchRec {
2935 attr: if is_dir { FA_DIREC } else { 0 },
2936 time: 0,
2937 size: 0,
2938 name: name.into(),
2939 }
2940 }
2941
2942 // --- DirEntry ---
2943
2944 #[test]
2945 fn dir_entry_accessors() {
2946 let e = DirEntry::new("~ disp", "/some/dir");
2947 assert_eq!(e.text(), "~ disp");
2948 assert_eq!(e.dir(), "/some/dir");
2949 }
2950
2951 #[test]
2952 fn dir_entry_clone_and_eq() {
2953 let e = DirEntry::new("a", "b");
2954 assert_eq!(e.clone(), e);
2955 }
2956
2957 // --- search_rec_compare: one assertion per branch ---
2958
2959 #[test]
2960 fn compare_equal_names() {
2961 assert_eq!(
2962 search_rec_compare(&rec("foo", false), &rec("foo", false)),
2963 Ordering::Equal
2964 );
2965 }
2966
2967 #[test]
2968 fn compare_a_is_dotdot() {
2969 // ".." sorts after everything → Greater.
2970 assert_eq!(
2971 search_rec_compare(&rec("..", false), &rec("foo", false)),
2972 Ordering::Greater
2973 );
2974 }
2975
2976 #[test]
2977 fn compare_b_is_dotdot() {
2978 // ".." as key2 → Less.
2979 assert_eq!(
2980 search_rec_compare(&rec("foo", false), &rec("..", false)),
2981 Ordering::Less
2982 );
2983 }
2984
2985 #[test]
2986 fn compare_dir_after_file() {
2987 // a is a directory, b is a plain file (different names to avoid the
2988 // equal-name short-circuit) → a sorts after → Greater.
2989 assert_eq!(
2990 search_rec_compare(&rec("src", true), &rec("main.rs", false)),
2991 Ordering::Greater
2992 );
2993 }
2994
2995 #[test]
2996 fn compare_file_before_dir() {
2997 // a is a plain file, b is a directory → a sorts before → Less.
2998 assert_eq!(
2999 search_rec_compare(&rec("main.rs", false), &rec("src", true)),
3000 Ordering::Less
3001 );
3002 }
3003
3004 #[test]
3005 fn compare_both_files_alpha_order() {
3006 // "apple" < "banana" in byte order.
3007 assert_eq!(
3008 search_rec_compare(&rec("apple", false), &rec("banana", false)),
3009 Ordering::Less
3010 );
3011 assert_eq!(
3012 search_rec_compare(&rec("banana", false), &rec("apple", false)),
3013 Ordering::Greater
3014 );
3015 }
3016
3017 #[test]
3018 fn compare_case_sensitive_byte_order() {
3019 // 'Z' (0x5A) < 'a' (0x61) → "Zebra" < "apple".
3020 assert_eq!(
3021 search_rec_compare(&rec("Zebra", false), &rec("apple", false)),
3022 Ordering::Less
3023 );
3024 }
3025
3026 #[test]
3027 fn compare_both_dirs_alpha_order() {
3028 assert_eq!(
3029 search_rec_compare(&rec("alpha", true), &rec("beta", true)),
3030 Ordering::Less
3031 );
3032 }
3033
3034 // --- FileCollection::insert keeps sorted order ---
3035
3036 #[test]
3037 fn file_collection_sorted_insert() {
3038 let mut fc = FileCollection::new();
3039 // Insert out of order: a file, a directory, "..", another file.
3040 fc.insert(rec("readme.txt", false));
3041 fc.insert(rec("..", false));
3042 fc.insert(rec("src", true));
3043 fc.insert(rec("main.rs", false));
3044
3045 // Expected order (by comparator): files alpha, dirs alpha, ".." last.
3046 let names: Vec<&str> = fc.items().iter().map(|r| r.name.as_str()).collect();
3047 assert_eq!(names, vec!["main.rs", "readme.txt", "src", ".."]);
3048
3049 // Also verify adjacent pairs are non-decreasing under the comparator.
3050 for w in fc.items().windows(2) {
3051 assert_ne!(
3052 search_rec_compare(&w[0], &w[1]),
3053 Ordering::Greater,
3054 "pair ({}, {}) is out of order",
3055 w[0].name,
3056 w[1].name
3057 );
3058 }
3059 }
3060
3061 #[test]
3062 fn file_collection_multiple_dirs() {
3063 let mut fc = FileCollection::new();
3064 fc.insert(rec("docs", true));
3065 fc.insert(rec("file.txt", false));
3066 fc.insert(rec("alpha", true));
3067 fc.insert(rec("..", false));
3068 fc.insert(rec("build.rs", false));
3069
3070 let names: Vec<&str> = fc.items().iter().map(|r| r.name.as_str()).collect();
3071 assert_eq!(names, vec!["build.rs", "file.txt", "alpha", "docs", ".."]);
3072 }
3073
3074 // --- at / len / is_empty ---
3075
3076 #[test]
3077 fn file_collection_at_len_is_empty() {
3078 let mut fc = FileCollection::new();
3079 assert!(fc.is_empty());
3080 assert_eq!(fc.len(), 0);
3081 assert!(fc.at(0).is_none());
3082
3083 fc.insert(rec("foo.txt", false));
3084 assert!(!fc.is_empty());
3085 assert_eq!(fc.len(), 1);
3086 assert_eq!(fc.at(0).map(|r| r.name.as_str()), Some("foo.txt"));
3087 assert!(fc.at(1).is_none());
3088 }
3089
3090 #[test]
3091 fn file_collection_default_is_empty() {
3092 let fc = FileCollection::default();
3093 assert!(fc.is_empty());
3094 }
3095
3096 // =========================================================================
3097 // DirListBox
3098 // =========================================================================
3099
3100 // -- build_tree: pure deterministic tests ----------------------------------
3101
3102 /// Verify the deep tree: `/home/oetiker/` with three subdirs.
3103 #[test]
3104 fn build_tree_deep_dir_three_subdirs() {
3105 let subdirs: Vec<String> = vec!["projects".into(), "scratch".into(), "tmp".into()];
3106 let (entries, cur) = DirListBox::build_tree("/home/oetiker/", &subdirs);
3107
3108 // Counts: root + home + oetiker + 3 subdirs = 6.
3109 assert_eq!(entries.len(), 6, "6 entries total");
3110 assert_eq!(cur, 2, "cur == 2 (oetiker is the 3rd entry, idx 2)");
3111
3112 // Ancestor entries.
3113 assert_eq!(entries[0].directory, "/", "root directory");
3114 assert_eq!(entries[1].directory, "/home", "home directory");
3115 assert_eq!(entries[2].directory, "/home/oetiker", "oetiker directory");
3116
3117 // Subdir directory values.
3118 assert_eq!(entries[3].directory, "/home/oetiker/projects");
3119 assert_eq!(entries[4].directory, "/home/oetiker/scratch");
3120 assert_eq!(entries[5].directory, "/home/oetiker/tmp");
3121
3122 // Connector prefixes on ancestor entries (indent 0, 2, 4).
3123 assert!(
3124 entries[0].display_text.contains("└─┬"),
3125 "root uses PATH_DIR"
3126 );
3127 assert!(
3128 entries[1].display_text.contains("└─┬"),
3129 "home uses PATH_DIR"
3130 );
3131 assert!(
3132 entries[2].display_text.contains("└─┬"),
3133 "oetiker uses PATH_DIR"
3134 );
3135
3136 // Connector prefixes on subdirs.
3137 assert!(
3138 entries[3].display_text.contains("└┬─"),
3139 "first subdir uses FIRST_DIR"
3140 );
3141 assert!(
3142 entries[4].display_text.contains(" ├─"),
3143 "middle subdir uses MIDDLE_DIR"
3144 );
3145
3146 // Last-entry fix-up: `├` → `└`.
3147 assert!(
3148 entries[5].display_text.contains('└'),
3149 "last subdir has └ after fix-up"
3150 );
3151 assert!(
3152 !entries[5].display_text.contains('├'),
3153 "last subdir no longer has ├"
3154 );
3155 }
3156
3157 /// Root-only dir (`"/"`) with two subdirs.
3158 #[test]
3159 fn build_tree_root_only_two_subdirs() {
3160 let subdirs: Vec<String> = vec!["etc".into(), "usr".into()];
3161 let (entries, cur) = DirListBox::build_tree("/", &subdirs);
3162
3163 // Counts: root + 2 subdirs = 3.
3164 assert_eq!(entries.len(), 3, "3 entries total");
3165 assert_eq!(cur, 0, "cur == 0 (root is the only ancestor)");
3166
3167 assert_eq!(entries[0].directory, "/");
3168 assert_eq!(entries[1].directory, "/etc");
3169 assert_eq!(entries[2].directory, "/usr");
3170
3171 // Subdirs at indent 2.
3172 assert!(
3173 entries[1].display_text.starts_with(" "),
3174 "subdir indent = 2 spaces"
3175 );
3176 // Last-entry fix-up: `├` → `└`.
3177 assert!(
3178 entries[2].display_text.contains('└'),
3179 "last subdir has └ after fix-up"
3180 );
3181 assert!(!entries[2].display_text.contains('├'));
3182 }
3183
3184 /// Single-subdir fix-up: `└┬─` → `└──`.
3185 #[test]
3186 fn build_tree_single_subdir_fixup() {
3187 let subdirs: Vec<String> = vec!["only".into()];
3188 let (entries, cur) = DirListBox::build_tree("/", &subdirs);
3189
3190 assert_eq!(entries.len(), 2);
3191 assert_eq!(cur, 0);
3192
3193 // The single subdir started as FIRST_DIR "└┬─"; fix-up replaces "┬─" → "──".
3194 let display = &entries[1].display_text;
3195 assert!(
3196 display.contains("└──"),
3197 "single subdir fix-up: '└┬─' → '└──', got: {:?}",
3198 display
3199 );
3200 assert!(!display.contains("┬─"), "no remaining ┬─ after fix-up");
3201 }
3202
3203 /// No subdirs — the fix-up still runs on the deepest ancestor (it is the
3204 /// last entry), turning its "└─┬" connector into a leaf corner "└──".
3205 #[test]
3206 fn build_tree_no_subdirs() {
3207 let (entries, cur) = DirListBox::build_tree("/home/user/", &[]);
3208 // root + home + user = 3 entries, no subdirs.
3209 assert_eq!(entries.len(), 3);
3210 assert_eq!(cur, 2);
3211 // The deepest ancestor (last entry) became a leaf corner "└──user".
3212 assert!(
3213 entries[2].display_text.ends_with("└──user"),
3214 "deepest ancestor fix-up: '└─┬user' → '└──user', got: {:?}",
3215 entries[2].display_text
3216 );
3217 assert!(
3218 !entries[2].display_text.contains('┬'),
3219 "no remaining ┬ after fix-up"
3220 );
3221 // Earlier ancestors keep their "└─┬" connector (they have children).
3222 assert!(
3223 entries[1].display_text.contains("└─┬"),
3224 "home keeps its branch connector"
3225 );
3226 }
3227
3228 /// Root-only, no subdirs — a single entry, fixed up to a leaf corner.
3229 #[test]
3230 fn build_tree_root_only_no_subdirs() {
3231 let (entries, cur) = DirListBox::build_tree("/", &[]);
3232 assert_eq!(entries.len(), 1, "just the root");
3233 assert_eq!(cur, 0);
3234 assert_eq!(entries[0].directory, "/");
3235 // "└─┬/" → "└──/".
3236 assert_eq!(
3237 entries[0].display_text, "└──/",
3238 "root-only fix-up: '└─┬/' → '└──/'"
3239 );
3240 }
3241
3242 /// `is_selected` returns true only for `cur`, not for `focused`.
3243 #[test]
3244 fn dir_list_box_is_selected_returns_cur() {
3245 use crate::widgets::list_viewer::ListViewer;
3246
3247 let subdirs: Vec<String> = vec!["a".into(), "b".into()];
3248 let (items, cur) = DirListBox::build_tree("/home/oetiker/", &subdirs);
3249
3250 let mut dlb = DirListBox::new(crate::view::Rect::new(0, 0, 30, 8), None, None);
3251 dlb.items = items;
3252 dlb.cur = cur;
3253 dlb.lv.range = dlb.items.len() as i32;
3254 dlb.lv.focused = 0; // cursor is on root, not cur
3255
3256 // Only `cur` (index 2) is "selected".
3257 assert!(dlb.is_selected(cur as i32), "cur entry is selected");
3258 assert!(!dlb.is_selected(0), "root entry (focused) is not selected");
3259 assert!(!dlb.is_selected(1), "home entry is not selected");
3260 }
3261
3262 // -- snapshot test: draw the rendered tree ---------------------------------
3263
3264 fn render_dlb(dlb: &mut DirListBox, w: u16, h: u16) -> String {
3265 use crate::backend::{HeadlessBackend, Renderer};
3266 use crate::screen::Buffer;
3267 use crate::theme::Theme;
3268 use crate::view::{DrawCtx, View};
3269
3270 let theme = Theme::classic_blue();
3271 let (backend, screen) = HeadlessBackend::new(w, h);
3272 let mut r = Renderer::new(Box::new(backend));
3273 r.render(|buf: &mut Buffer| {
3274 let bounds = dlb.state().get_bounds();
3275 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
3276 dlb.draw(&mut dc);
3277 });
3278 screen.snapshot()
3279 }
3280
3281 /// Snapshot with `focused == cur`: both focused and is_selected land on
3282 /// the same row so the highlighted row comes from the focused-color branch.
3283 #[test]
3284 fn snapshot_dir_list_box_tree() {
3285 let subdirs: Vec<String> = vec!["projects".into(), "scratch".into(), "tmp".into()];
3286 let (items, cur) = DirListBox::build_tree("/home/oetiker/", &subdirs);
3287
3288 let mut dlb = DirListBox::new(crate::view::Rect::new(0, 0, 30, 8), None, None);
3289 // Seed directly (no Context needed for draw test).
3290 dlb.lv.state.state.selected = true;
3291 dlb.lv.state.state.active = true;
3292 dlb.lv.state.state.focused = true;
3293 dlb.items = items;
3294 dlb.cur = cur;
3295 dlb.lv.range = dlb.items.len() as i32;
3296 dlb.lv.focused = cur as i32;
3297
3298 insta::assert_snapshot!(render_dlb(&mut dlb, 30, 8));
3299 }
3300
3301 /// Snapshot with `focused != cur` — exercises `is_selected` through the
3302 /// draw path. The cursor sits on the root (row 0, `focused=0`) while
3303 /// `is_selected` still marks the oetiker ancestor (`cur=2`).
3304 ///
3305 /// In `list_viewer::draw`, the color precedence is:
3306 /// focused == item → focused_color (root row, cursor here)
3307 /// is_selected(item) → selected_color (cur row, highlighted here)
3308 /// else → normal_color
3309 ///
3310 /// If `is_selected` were broken (always false) the cur row would render in
3311 /// normal_color and this snapshot would differ — making the check bite.
3312 #[test]
3313 fn snapshot_dir_list_box_tree_cursor_off_cur() {
3314 let subdirs: Vec<String> = vec!["projects".into(), "scratch".into(), "tmp".into()];
3315 let (items, cur) = DirListBox::build_tree("/home/oetiker/", &subdirs);
3316
3317 let mut dlb = DirListBox::new(crate::view::Rect::new(0, 0, 30, 8), None, None);
3318 dlb.lv.state.state.selected = true;
3319 dlb.lv.state.state.active = true;
3320 dlb.lv.state.state.focused = true;
3321 dlb.items = items;
3322 dlb.cur = cur; // cur == 2 (oetiker) remains the "selected" dir.
3323 dlb.lv.range = dlb.items.len() as i32;
3324 dlb.lv.focused = 0; // cursor on root — NOT the current dir.
3325
3326 insta::assert_snapshot!(render_dlb(&mut dlb, 30, 8));
3327 }
3328
3329 // =========================================================================
3330 // FileList
3331 // =========================================================================
3332
3333 use crate::event::{Event, Key, KeyEvent, KeyModifiers};
3334 use crate::view::{Context, Deferred, View};
3335 use crate::widgets::list_viewer::ListViewer;
3336 use std::collections::VecDeque;
3337
3338 fn fl_make_ctx<'a>(
3339 out: &'a mut VecDeque<Event>,
3340 timers: &'a mut crate::timer::TimerQueue,
3341 deferred: &'a mut Vec<Deferred>,
3342 ) -> Context<'a> {
3343 Context::new(out, timers, 0, deferred)
3344 }
3345
3346 fn fl_key(c: char) -> Event {
3347 Event::KeyDown(KeyEvent::new(Key::Char(c), KeyModifiers::default()))
3348 }
3349
3350 // -- 1. wildcard_match -----------------------------------------------------
3351
3352 #[test]
3353 fn wildcard_star_matches_all() {
3354 assert!(FileList::wildcard_match("*", ""));
3355 assert!(FileList::wildcard_match("*", "anything.rs"));
3356 assert!(FileList::wildcard_match("*", "no.extension.here"));
3357 }
3358
3359 #[test]
3360 fn wildcard_extension_filter() {
3361 assert!(FileList::wildcard_match("*.txt", "a.txt"));
3362 assert!(FileList::wildcard_match("*.txt", "longer.name.txt"));
3363 assert!(!FileList::wildcard_match("*.txt", "a.rs"));
3364 assert!(!FileList::wildcard_match("*.txt", "txt")); // no dot
3365 }
3366
3367 #[test]
3368 fn wildcard_question_mark_single_char() {
3369 assert!(FileList::wildcard_match("?.rs", "a.rs"));
3370 assert!(!FileList::wildcard_match("?.rs", "ab.rs")); // ? is exactly one
3371 assert!(!FileList::wildcard_match("?.rs", ".rs")); // needs one char
3372 }
3373
3374 #[test]
3375 fn wildcard_star_edges() {
3376 // "a*z" — prefix 'a', suffix 'z', any middle.
3377 assert!(FileList::wildcard_match("a*z", "az")); // empty middle
3378 assert!(FileList::wildcard_match("a*z", "abcz"));
3379 assert!(!FileList::wildcard_match("a*z", "abc")); // no trailing z
3380 assert!(!FileList::wildcard_match("a*z", "bz")); // no leading a
3381 // Case-sensitive (Linux build).
3382 assert!(!FileList::wildcard_match("*.TXT", "a.txt"));
3383 }
3384
3385 // -- 2. build_listing ------------------------------------------------------
3386
3387 // Helper: a raw (name, is_dir, size, mtime) tuple. The tests don't exercise
3388 // the date display, so `mtime` is always `None` (→ packed `time = 0`).
3389 fn raw(
3390 name: &str,
3391 is_dir: bool,
3392 size: i32,
3393 ) -> (String, bool, i32, Option<std::time::SystemTime>) {
3394 (name.into(), is_dir, size, None)
3395 }
3396
3397 #[test]
3398 fn build_listing_files_filtered_dirs_always() {
3399 let raw_entries = vec![
3400 raw("keep.txt", false, 10),
3401 raw("skip.rs", false, 20),
3402 raw("src", true, 0), // dir: kept regardless of wildcard
3403 raw("docs", true, 0), // dir: kept regardless of wildcard
3404 ];
3405 let items = FileList::build_listing("/home/oetiker/", "*.txt", &raw_entries);
3406 let names: Vec<&str> = items.iter().map(|r| r.name.as_str()).collect();
3407 // File "skip.rs" filtered out; both dirs kept; ".." appended.
3408 assert_eq!(names, vec!["keep.txt", "docs", "src", ".."]);
3409 // "keep.txt" carries its size; dirs/".." carry FA_DIREC.
3410 assert_eq!(items[0].size, 10);
3411 assert_eq!(items[0].attr & FA_DIREC, 0, "file has no FA_DIREC");
3412 assert_eq!(items[1].attr & FA_DIREC, FA_DIREC, "docs is a dir");
3413 assert_eq!(items[3].attr & FA_DIREC, FA_DIREC, ".. is a dir");
3414 }
3415
3416 #[test]
3417 fn build_listing_drops_hidden_dirs_and_dot_entries() {
3418 let raw_entries = vec![
3419 raw(".git", true, 0), // hidden dir -> dropped
3420 raw(".", true, 0), // self -> dropped
3421 raw("..", true, 0), // parent in raw -> dropped (synthesized below)
3422 raw("visible", true, 0),
3423 raw(".hidden", false, 5), // hidden FILE: matched by "*" -> kept
3424 ];
3425 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3426 let names: Vec<&str> = items.iter().map(|r| r.name.as_str()).collect();
3427 // Hidden file kept (wildcard "*"); hidden/./.. dirs dropped; ".." synthesized last.
3428 assert_eq!(names, vec![".hidden", "visible", ".."]);
3429 }
3430
3431 #[test]
3432 fn build_listing_dotdot_only_off_root() {
3433 // Off the root: ".." appended.
3434 let items = FileList::build_listing("/home/oetiker/", "*", &[raw("a", true, 0)]);
3435 assert!(
3436 items.iter().any(|r| r.name == ".."),
3437 "dotdot present off root"
3438 );
3439
3440 // At the root: no "..".
3441 let items = FileList::build_listing("/", "*", &[raw("a", true, 0)]);
3442 assert!(
3443 !items.iter().any(|r| r.name == ".."),
3444 "no dotdot at the root"
3445 );
3446 }
3447
3448 #[test]
3449 fn build_listing_order_matches_comparator() {
3450 let raw_entries = vec![
3451 raw("zebra.rs", false, 1),
3452 raw("apple.rs", false, 1),
3453 raw("src", true, 0),
3454 raw("bin", true, 0),
3455 ];
3456 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3457 let names: Vec<&str> = items.iter().map(|r| r.name.as_str()).collect();
3458 // Files alpha, dirs alpha, ".." last.
3459 assert_eq!(names, vec!["apple.rs", "zebra.rs", "bin", "src", ".."]);
3460
3461 // get_text appends "/" to dirs and "..".
3462 let mut fl = FileList::new(crate::view::Rect::new(0, 0, 30, 8), None, None);
3463 fl.items = items;
3464 assert_eq!(fl.get_text(0), "apple.rs", "file: no slash");
3465 assert_eq!(fl.get_text(2), "bin/", "dir: trailing slash");
3466 assert_eq!(fl.get_text(4), "../", "dotdot dir: trailing slash");
3467 }
3468
3469 // -- 3. search: the discriminating comparator test -------------------------
3470
3471 /// The key check that `search` compares via `search_rec_compare` (with the
3472 /// attr'd key), NOT via `get_text`.
3473 ///
3474 /// Seed a FILE "src.rs" and a DIRECTORY "src". Under the collection order:
3475 /// files first (alpha), then dirs (alpha), then "..". So:
3476 /// items = ["src.rs" (file), "src" (dir), ".." (dir)]
3477 /// Searching "s" with shift_state == 0 → attr 0 → a FILE key → lands at the
3478 /// first item not-less-than it, which is the file "src.rs" (index 0 — the
3479 /// file section). Searching "s" with shift_state == KB_SHIFT → attr FA_DIREC
3480 /// → a DIR key → sorts AFTER every file → lands at the first dir "src"
3481 /// (index 1 — the dir section). A get_text-based impl ignores attr and would
3482 /// return the SAME index for both — this test rules that out.
3483 #[test]
3484 fn search_attr_routes_into_file_vs_dir_section() {
3485 use crate::widgets::list_viewer::{KB_SHIFT, SortedSearch};
3486
3487 let raw_entries = vec![raw("src.rs", false, 1), raw("src", true, 0)];
3488 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3489 // Expected sorted: file "src.rs" (0), dir "src" (1), ".." (2).
3490 assert_eq!(
3491 items.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
3492 vec!["src.rs", "src", ".."]
3493 );
3494
3495 let mut fl = FileList::new(crate::view::Rect::new(0, 0, 30, 8), None, None);
3496 fl.items = items;
3497 fl.lv.range = fl.items.len() as i32;
3498
3499 // shift_state 0 → file key → lands in the FILE section (index 0).
3500 fl.shift_state = 0;
3501 assert_eq!(
3502 fl.search(&['s']),
3503 0,
3504 "file key lands at the first file >= 's' (src.rs, idx 0)"
3505 );
3506
3507 // shift_state KB_SHIFT → dir key → lands in the DIR section (index 1).
3508 fl.shift_state = KB_SHIFT;
3509 assert_eq!(
3510 fl.search(&['s']),
3511 1,
3512 "dir key sorts after all files -> first dir (src, idx 1)"
3513 );
3514
3515 // A leading '.' in the prefix ALSO routes to FA_DIREC (the search key's
3516 // `name` starts with '.'), even with shift_state == 0 — the discriminating
3517 // proof that the key's attr (not the display text) drives the search. A
3518 // dir-key "." sorts AMONG the
3519 // dirs (after all files), and "." < "src" < ".." in byte order, so it
3520 // lands at the first dir, index 1. (A get_text impl with shift 0 would
3521 // treat "." as a plain name and land it in the file section at index 0.)
3522 fl.shift_state = 0;
3523 assert_eq!(
3524 fl.search(&['.']),
3525 1,
3526 "leading '.' -> dir key -> first dir (src, idx 1), NOT the file section"
3527 );
3528 }
3529
3530 #[test]
3531 fn search_plain_first_ge() {
3532 use crate::widgets::list_viewer::SortedSearch;
3533 // Files only: a search for "s" finds the first file >= "s".
3534 let raw_entries = vec![
3535 raw("alpha.rs", false, 1),
3536 raw("sigma.rs", false, 1),
3537 raw("zeta.rs", false, 1),
3538 ];
3539 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3540 let mut fl = FileList::new(crate::view::Rect::new(0, 0, 30, 8), None, None);
3541 fl.items = items;
3542 fl.lv.range = fl.items.len() as i32;
3543 // "alpha.rs"(0) "sigma.rs"(1) "zeta.rs"(2) ".."(3, a dir).
3544 assert_eq!(
3545 fl.search(&['s']),
3546 1,
3547 "first file >= 's' is sigma.rs (idx 1)"
3548 );
3549 }
3550
3551 // -- 4. type-to-search smoke test through handle_event ---------------------
3552
3553 #[test]
3554 fn file_list_type_to_jump_focuses_match() {
3555 let raw_entries = vec![
3556 raw("alpha.rs", false, 1),
3557 raw("sigma.rs", false, 1),
3558 raw("zeta.rs", false, 1),
3559 ];
3560 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3561
3562 let mut fl = FileList::new(crate::view::Rect::new(0, 0, 30, 8), None, None);
3563 fl.items = items;
3564 fl.lv.range = fl.items.len() as i32;
3565 fl.lv.focused = 0; // start on "alpha.rs"
3566
3567 let mut out: VecDeque<Event> = VecDeque::new();
3568 let mut timers = crate::timer::TimerQueue::new();
3569 let mut deferred: Vec<Deferred> = vec![];
3570
3571 // Type 's' -> jump to "sigma.rs" (index 1).
3572 let mut ev = fl_key('s');
3573 {
3574 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
3575 fl.handle_event(&mut ev, &mut ctx);
3576 }
3577 assert_eq!(fl.lv().focused, 1, "'s' -> focus sigma.rs (idx 1)");
3578 assert!(ev.is_nothing(), "alphabetic char consumed");
3579
3580 // After that single char the search machine advanced search_pos to 0
3581 // (the index of the matched char in the focused item's text), confirming
3582 // the type-to-search seam is wired through handle_event.
3583 use crate::widgets::list_viewer::SortedSearch;
3584 assert_eq!(fl.search_pos(), 0, "search_pos == 0 after one char");
3585 }
3586
3587 // -- 5. snapshot of a rendered FileList ------------------------------------
3588
3589 fn render_fl(fl: &mut FileList, w: u16, h: u16) -> String {
3590 use crate::backend::{HeadlessBackend, Renderer};
3591 use crate::screen::Buffer;
3592 use crate::theme::Theme;
3593 use crate::view::{DrawCtx, View};
3594
3595 let theme = Theme::classic_blue();
3596 let (backend, screen) = HeadlessBackend::new(w, h);
3597 let mut r = Renderer::new(Box::new(backend));
3598 r.render(|buf: &mut Buffer| {
3599 let bounds = fl.state().get_bounds();
3600 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
3601 fl.draw(&mut dc);
3602 });
3603 screen.snapshot()
3604 }
3605
3606 #[test]
3607 fn snapshot_file_list() {
3608 let raw_entries = vec![
3609 raw("main.rs", false, 100),
3610 raw("lib.rs", false, 200),
3611 raw("readme.txt", false, 50),
3612 raw("src", true, 0),
3613 raw("tests", true, 0),
3614 ];
3615 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3616
3617 // 2-column layout (num_cols == 2). Width 30 so each column is ~15 wide.
3618 let mut fl = FileList::new(crate::view::Rect::new(0, 0, 30, 6), None, None);
3619 fl.lv.state.state.selected = true;
3620 fl.lv.state.state.active = true;
3621 fl.lv.state.state.focused = true;
3622 fl.items = items;
3623 fl.lv.range = fl.items.len() as i32;
3624 fl.lv.focused = 0;
3625
3626 insta::assert_snapshot!(render_fl(&mut fl, 30, 6));
3627 }
3628
3629 // =========================================================================
3630 // FileInputLine + the cmFileFocused payload broker
3631 // =========================================================================
3632
3633 use crate::command::Command;
3634 use crate::view::{Group, Rect};
3635
3636 /// Insert `fl` into a fresh group, returning the group + the stamped id so we
3637 /// can drive it through `as_any_mut().downcast_mut::<FileList>()` and read the
3638 /// broadcasts it queues with `self` as `source`.
3639 fn fl_in_group(fl: FileList) -> (Group, crate::view::ViewId) {
3640 let mut g = Group::new(Rect::new(0, 0, 40, 12));
3641 let id = g.insert(Box::new(fl));
3642 (g, id)
3643 }
3644
3645 fn count_broadcasts(out: &VecDeque<Event>, cmd: Command, src: crate::view::ViewId) -> usize {
3646 out.iter()
3647 .filter(|e| {
3648 matches!(e, Event::Broadcast { command, source }
3649 if *command == cmd && *source == Some(src))
3650 })
3651 .count()
3652 }
3653
3654 // -- 1. on_focus_changed queues FILE_FOCUSED { source = self } -------------
3655
3656 #[test]
3657 fn focus_change_broadcasts_file_focused_with_self_source() {
3658 let raw_entries = vec![raw("a.rs", false, 1), raw("b.rs", false, 1)];
3659 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3660 let mut fl = FileList::new(Rect::new(0, 0, 30, 8), None, None);
3661 fl.items = items;
3662 fl.lv.range = fl.items.len() as i32;
3663 fl.lv.focused = 0;
3664
3665 let (mut g, id) = fl_in_group(fl);
3666 let mut out = VecDeque::new();
3667 let mut timers = crate::timer::TimerQueue::new();
3668 let mut deferred: Vec<Deferred> = vec![];
3669
3670 // Drive a focus change through the shared `focus_item` funnel.
3671 {
3672 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
3673 let fl = g
3674 .find_mut(id)
3675 .and_then(|v| v.as_any_mut())
3676 .and_then(|a| a.downcast_mut::<FileList>())
3677 .unwrap();
3678 crate::widgets::list_viewer::focus_item(fl, 1, &mut ctx);
3679 assert_eq!(fl.lv().focused, 1);
3680 }
3681 assert_eq!(
3682 count_broadcasts(&out, Command::FILE_FOCUSED, id),
3683 1,
3684 "focus change broadcasts exactly one FILE_FOCUSED with self as source"
3685 );
3686 }
3687
3688 // -- 2. focused_rec returns the focused entry / None when empty -----------
3689
3690 #[test]
3691 fn focused_rec_returns_focused_or_none() {
3692 let raw_entries = vec![raw("a.rs", false, 1), raw("b.rs", false, 1)];
3693 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3694 let mut fl = FileList::new(Rect::new(0, 0, 30, 8), None, None);
3695 fl.items = items;
3696 fl.lv.range = fl.items.len() as i32;
3697
3698 fl.lv.focused = 0;
3699 assert_eq!(fl.focused_rec().map(|r| r.name), Some("a.rs".to_string()));
3700 fl.lv.focused = 1;
3701 assert_eq!(fl.focused_rec().map(|r| r.name), Some("b.rs".to_string()));
3702
3703 // Empty listing -> None.
3704 let empty = FileList::new(Rect::new(0, 0, 30, 8), None, None);
3705 assert_eq!(empty.focused_rec(), None);
3706 }
3707
3708 // -- 3. select_item queues FILE_DOUBLE_CLICKED ----------------------------
3709
3710 #[test]
3711 fn select_item_broadcasts_file_double_clicked() {
3712 let raw_entries = vec![raw("a.rs", false, 1)];
3713 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3714 let mut fl = FileList::new(Rect::new(0, 0, 30, 8), None, None);
3715 fl.items = items;
3716 fl.lv.range = fl.items.len() as i32;
3717
3718 let (mut g, id) = fl_in_group(fl);
3719 let mut out = VecDeque::new();
3720 let mut timers = crate::timer::TimerQueue::new();
3721 let mut deferred: Vec<Deferred> = vec![];
3722 {
3723 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
3724 let fl = g
3725 .find_mut(id)
3726 .and_then(|v| v.as_any_mut())
3727 .and_then(|a| a.downcast_mut::<FileList>())
3728 .unwrap();
3729 fl.select_item(0, &mut ctx);
3730 }
3731 assert_eq!(
3732 count_broadcasts(&out, Command::FILE_DOUBLE_CLICKED, id),
3733 1,
3734 "selectItem broadcasts FILE_DOUBLE_CLICKED with self as source"
3735 );
3736 // Faithful: it does NOT also broadcast cmListItemSelected (no base call).
3737 assert_eq!(
3738 count_broadcasts(&out, Command::LIST_ITEM_SELECTED, id),
3739 0,
3740 "selectItem does NOT call the base -> no cmListItemSelected"
3741 );
3742 }
3743
3744 // -- 4. read_directory on an empty dir queues a FILE_FOCUSED (noFile) ------
3745
3746 /// Verifies the `read_directory` noFile-branch **contract by construction**:
3747 /// an empty listing (range 0) has no focusable item, so it must broadcast
3748 /// `FILE_FOCUSED` directly rather than via `focus_item`. A genuinely-empty
3749 /// listing is unreachable end-to-end (off-root always synthesizes `..`; `/`
3750 /// always has subdirs on a live system), so this cannot drive `read_directory`
3751 /// for real — it instead exercises the exact `else` arm's logic in isolation.
3752 #[test]
3753 fn empty_listing_branch_broadcasts_file_focused_by_contract() {
3754 let fl = FileList::new(Rect::new(0, 0, 30, 8), None, None);
3755 let (mut g, id) = fl_in_group(fl);
3756 let mut out = VecDeque::new();
3757 let mut timers = crate::timer::TimerQueue::new();
3758 let mut deferred: Vec<Deferred> = vec![];
3759 {
3760 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
3761 let fl = g
3762 .find_mut(id)
3763 .and_then(|v| v.as_any_mut())
3764 .and_then(|a| a.downcast_mut::<FileList>())
3765 .unwrap();
3766 // Mirrors the production `read_directory` `else` arm verbatim (an empty
3767 // listing can't be produced end-to-end, so we reproduce its logic here):
3768 // empty items, range 0 -> broadcast FILE_FOCUSED directly (focus_item
3769 // never runs with range 0).
3770 fl.items.clear();
3771 crate::widgets::list_viewer::set_range(fl, 0, &mut ctx);
3772 assert_eq!(fl.lv().range, 0);
3773 if fl.lv().range == 0
3774 && let Some(vid) = fl.lv().state.id()
3775 {
3776 ctx.broadcast(Command::FILE_FOCUSED, Some(vid));
3777 }
3778 }
3779 assert_eq!(
3780 count_broadcasts(&out, Command::FILE_FOCUSED, id),
3781 1,
3782 "empty-listing branch broadcasts FILE_FOCUSED (noFile) once"
3783 );
3784 }
3785
3786 /// Non-empty `read_directory` (off-root, so `..` is present) takes the
3787 /// `focus_item(0)` path -> `on_focus_changed` -> exactly one FILE_FOCUSED.
3788 #[test]
3789 fn read_directory_nonempty_broadcasts_file_focused_once() {
3790 let tmp = std::env::temp_dir().join(format!("rstv_filedlg_{}", std::process::id()));
3791 let _ = std::fs::remove_dir_all(&tmp);
3792 std::fs::create_dir_all(&tmp).unwrap();
3793 std::fs::write(tmp.join("keep.txt"), b"x").unwrap();
3794 let dir = format!("{}/", tmp.to_string_lossy());
3795
3796 let fl = FileList::new(Rect::new(0, 0, 30, 8), None, None);
3797 let (mut g, id) = fl_in_group(fl);
3798 let mut out = VecDeque::new();
3799 let mut timers = crate::timer::TimerQueue::new();
3800 let mut deferred: Vec<Deferred> = vec![];
3801 {
3802 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
3803 let fl = g
3804 .find_mut(id)
3805 .and_then(|v| v.as_any_mut())
3806 .and_then(|a| a.downcast_mut::<FileList>())
3807 .unwrap();
3808 fl.read_directory(&dir, "*", &mut ctx);
3809 assert!(fl.lv().range > 0, "off-root dir has at least '..'");
3810 }
3811 let _ = std::fs::remove_dir_all(&tmp);
3812 assert_eq!(
3813 count_broadcasts(&out, Command::FILE_FOCUSED, id),
3814 1,
3815 "non-empty read_directory broadcasts exactly one FILE_FOCUSED (item 0)"
3816 );
3817 }
3818
3819 // -- 5. on_file_focused: file / dir / None --------------------------------
3820
3821 #[test]
3822 fn file_input_line_on_file_focused_file_dir_none() {
3823 let mut fil = FileInputLine::new(Rect::new(0, 0, 20, 1), 80, "*.rs");
3824
3825 // A plain file -> just the name, no slash.
3826 fil.on_file_focused(Some(SearchRec {
3827 attr: 0,
3828 time: 0,
3829 size: 10,
3830 name: "main.rs".into(),
3831 }));
3832 assert_eq!(fil.inner.data, "main.rs");
3833
3834 // A directory -> "name/<wild_card>" (trailing slash).
3835 fil.on_file_focused(Some(SearchRec {
3836 attr: FA_DIREC,
3837 time: 0,
3838 size: 0,
3839 name: "src".into(),
3840 }));
3841 assert_eq!(fil.inner.data, "src/*.rs");
3842
3843 // None (the noFile sentinel) -> blank.
3844 fil.on_file_focused(None);
3845 assert_eq!(fil.inner.data, "");
3846 }
3847
3848 // -- 6. handle_event requests ResolveFocusedFile (guarded by the selected flag) --
3849
3850 #[test]
3851 fn file_input_line_handle_event_requests_broker_when_not_selected() {
3852 let fil = FileInputLine::new(Rect::new(0, 0, 20, 1), 80, "*.rs");
3853 let mut g = Group::new(Rect::new(0, 0, 40, 12));
3854 let fil_id = g.insert(Box::new(fil));
3855 // A producer id to name as the broadcast source.
3856 let src_id = crate::view::ViewId::next();
3857
3858 // NOT selected (default) -> the broker IS requested.
3859 let mut out = VecDeque::new();
3860 let mut timers = crate::timer::TimerQueue::new();
3861 let mut deferred: Vec<Deferred> = vec![];
3862 {
3863 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
3864 let mut ev = Event::Broadcast {
3865 command: Command::FILE_FOCUSED,
3866 source: Some(src_id),
3867 };
3868 g.find_mut(fil_id).unwrap().handle_event(&mut ev, &mut ctx);
3869 }
3870 assert_eq!(
3871 deferred
3872 .iter()
3873 .filter(|d| matches!(d,
3874 Deferred::ResolveFocusedFile { subscriber, source }
3875 if *subscriber == fil_id && *source == src_id))
3876 .count(),
3877 1,
3878 "not-selected FILE_FOCUSED -> one ResolveFocusedFile request"
3879 );
3880
3881 // SELECTED (user typing) -> the broker is NOT requested (selected guard).
3882 if let Some(v) = g.find_mut(fil_id) {
3883 v.state_mut().state.selected = true;
3884 }
3885 let mut out2 = VecDeque::new();
3886 let mut timers2 = crate::timer::TimerQueue::new();
3887 let mut deferred2: Vec<Deferred> = vec![];
3888 {
3889 let mut ctx = fl_make_ctx(&mut out2, &mut timers2, &mut deferred2);
3890 let mut ev = Event::Broadcast {
3891 command: Command::FILE_FOCUSED,
3892 source: Some(src_id),
3893 };
3894 g.find_mut(fil_id).unwrap().handle_event(&mut ev, &mut ctx);
3895 }
3896 assert!(
3897 !deferred2
3898 .iter()
3899 .any(|d| matches!(d, Deferred::ResolveFocusedFile { .. })),
3900 "selected (typing) FILE_FOCUSED -> no broker request (sfSelected guard)"
3901 );
3902 }
3903
3904 // -- 7. full pump-free round trip: broker resolves producer into consumer -
3905
3906 #[test]
3907 fn file_focused_round_trip_through_broker() {
3908 // Producer FileList with a focused dir entry, consumer FileInputLine —
3909 // both in one group; emulate the pump's ResolveFocusedFile apply.
3910 let raw_entries = vec![raw("readme.txt", false, 1), raw("src", true, 0)];
3911 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
3912 let mut fl = FileList::new(Rect::new(0, 0, 30, 8), None, None);
3913 fl.items = items;
3914 fl.lv.range = fl.items.len() as i32;
3915 fl.lv.focused = 1; // the "src" directory
3916
3917 let mut g = Group::new(Rect::new(0, 0, 40, 12));
3918 let src_id = g.insert(Box::new(fl));
3919 let sub_id = g.insert(Box::new(FileInputLine::new(
3920 Rect::new(0, 1, 20, 1),
3921 80,
3922 "*.c",
3923 )));
3924
3925 // Emulate the pump's broker: read producer's focused rec, write to consumer.
3926 let rec = g
3927 .find_mut(src_id)
3928 .and_then(|v| v.as_any_mut())
3929 .and_then(|a| a.downcast_mut::<FileList>())
3930 .and_then(|fl| fl.focused_rec());
3931 let fil = g
3932 .find_mut(sub_id)
3933 .and_then(|v| v.as_any_mut())
3934 .and_then(|a| a.downcast_mut::<FileInputLine>())
3935 .unwrap();
3936 fil.on_file_focused(rec);
3937
3938 // "src" is a directory -> "src/" + wildCard "*.c".
3939 assert_eq!(fil.inner.data, "src/*.c");
3940 }
3941
3942 // -- 8. snapshot of a rendered FileInputLine ------------------------------
3943
3944 fn render_fil(fil: &mut FileInputLine, w: u16, h: u16) -> String {
3945 use crate::backend::{HeadlessBackend, Renderer};
3946 use crate::screen::Buffer;
3947 use crate::theme::Theme;
3948 use crate::view::{DrawCtx, View};
3949
3950 let theme = Theme::classic_blue();
3951 let (backend, screen) = HeadlessBackend::new(w, h);
3952 let mut r = Renderer::new(Box::new(backend));
3953 r.render(|buf: &mut Buffer| {
3954 let bounds = fil.state().get_bounds();
3955 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
3956 fil.draw(&mut dc);
3957 });
3958 screen.snapshot()
3959 }
3960
3961 #[test]
3962 fn snapshot_file_input_line() {
3963 let mut fil = FileInputLine::new(Rect::new(0, 0, 20, 1), 80, "*.rs");
3964 fil.inner.state.state.selected = true;
3965 fil.inner.state.state.active = true;
3966 // A directory focus -> "src/*.rs" in the field.
3967 fil.on_file_focused(Some(SearchRec {
3968 attr: FA_DIREC,
3969 time: 0,
3970 size: 0,
3971 name: "src".into(),
3972 }));
3973 insta::assert_snapshot!(render_fil(&mut fil, 20, 1));
3974 }
3975
3976 // =========================================================================
3977 // FileInfoPane
3978 // =========================================================================
3979
3980 // -- 1. on_file_focused sets / clears the cached record -------------------
3981
3982 #[test]
3983 fn file_info_pane_on_file_focused_sets_and_clears() {
3984 let mut fip = FileInfoPane::new(Rect::new(0, 0, 47, 3), "/home/oetiker/", "*.rs");
3985 assert_eq!(fip.file_block, None, "starts blank");
3986
3987 let r = SearchRec {
3988 attr: 0,
3989 time: 0,
3990 size: 42,
3991 name: "main.rs".into(),
3992 };
3993 fip.on_file_focused(Some(r.clone()));
3994 assert_eq!(fip.file_block, Some(r));
3995
3996 // None (the noFile sentinel) clears it back to blank.
3997 fip.on_file_focused(None);
3998 assert_eq!(fip.file_block, None);
3999 }
4000
4001 // -- 2. handle_event requests ResolveFocusedFile on FILE_FOCUSED ----------
4002
4003 #[test]
4004 fn file_info_pane_handle_event_requests_broker() {
4005 let fip = FileInfoPane::new(Rect::new(0, 0, 47, 3), "/home/oetiker/", "*.rs");
4006 let mut g = Group::new(Rect::new(0, 0, 60, 20));
4007 let fip_id = g.insert(Box::new(fip));
4008 let src_id = crate::view::ViewId::next();
4009
4010 let mut out = VecDeque::new();
4011 let mut timers = crate::timer::TimerQueue::new();
4012 let mut deferred: Vec<Deferred> = vec![];
4013 {
4014 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4015 let mut ev = Event::Broadcast {
4016 command: Command::FILE_FOCUSED,
4017 source: Some(src_id),
4018 };
4019 g.find_mut(fip_id).unwrap().handle_event(&mut ev, &mut ctx);
4020 }
4021 assert_eq!(
4022 deferred
4023 .iter()
4024 .filter(|d| matches!(d,
4025 Deferred::ResolveFocusedFile { subscriber, source }
4026 if *subscriber == fip_id && *source == src_id))
4027 .count(),
4028 1,
4029 "FILE_FOCUSED -> one ResolveFocusedFile request (no sfSelected guard)"
4030 );
4031
4032 // Unlike FileInputLine, the pane has NO selected guard: even when
4033 // selected it STILL requests the broker.
4034 if let Some(v) = g.find_mut(fip_id) {
4035 v.state_mut().state.selected = true;
4036 }
4037 let mut out2 = VecDeque::new();
4038 let mut timers2 = crate::timer::TimerQueue::new();
4039 let mut deferred2: Vec<Deferred> = vec![];
4040 {
4041 let mut ctx = fl_make_ctx(&mut out2, &mut timers2, &mut deferred2);
4042 let mut ev = Event::Broadcast {
4043 command: Command::FILE_FOCUSED,
4044 source: Some(src_id),
4045 };
4046 g.find_mut(fip_id).unwrap().handle_event(&mut ev, &mut ctx);
4047 }
4048 assert_eq!(
4049 deferred2
4050 .iter()
4051 .filter(|d| matches!(d, Deferred::ResolveFocusedFile { .. }))
4052 .count(),
4053 1,
4054 "selected pane STILL requests the broker (no sfSelected guard)"
4055 );
4056 }
4057
4058 // -- 3. the DOS-time pack: known vector + round-trip ----------------------
4059
4060 #[test]
4061 fn pack_dos_time_known_vector_and_round_trip() {
4062 use std::time::{Duration, UNIX_EPOCH};
4063 // 2021-01-01 00:00:00 UTC = 1609459200.
4064 let t = UNIX_EPOCH + Duration::from_secs(1_609_459_200);
4065 let packed = pack_dos_time(&t);
4066 // year-1980 = 41 (0x29), month 1, day 1, time 0 -> date 0x5221, time 0.
4067 assert_eq!(
4068 packed, 0x5221_0000,
4069 "2021-01-01 00:00 UTC packs to 0x52210000"
4070 );
4071
4072 // Unpack the SAME bitfield the draw uses; round-trip to Y/M/D H:M.
4073 let v = packed as u32;
4074 let date = v >> 16;
4075 let time = v & 0xFFFF;
4076 assert_eq!((date >> 9) + 1980, 2021, "year");
4077 assert_eq!((date >> 5) & 0xF, 1, "month");
4078 assert_eq!(date & 0x1F, 1, "day");
4079 assert_eq!(time >> 11, 0, "hour");
4080 assert_eq!((time >> 5) & 0x3F, 0, "minute");
4081 }
4082
4083 #[test]
4084 fn pack_dos_time_afternoon_vector() {
4085 use std::time::{Duration, UNIX_EPOCH};
4086 // 2021-06-15 14:37:00 UTC = 1623767820.
4087 let t = UNIX_EPOCH + Duration::from_secs(1_623_767_820);
4088 let v = pack_dos_time(&t) as u32;
4089 let date = v >> 16;
4090 let time = v & 0xFFFF;
4091 assert_eq!((date >> 9) + 1980, 2021, "year");
4092 assert_eq!((date >> 5) & 0xF, 6, "month = Jun");
4093 assert_eq!(date & 0x1F, 15, "day");
4094 assert_eq!(time >> 11, 14, "hour (24h)");
4095 assert_eq!((time >> 5) & 0x3F, 37, "minute");
4096 }
4097
4098 #[test]
4099 fn pack_dos_time_pre_1980_clamps() {
4100 use std::time::{Duration, UNIX_EPOCH};
4101 // 1970-01-01 00:00:00 UTC is before the DOS 1980 epoch -> clamp.
4102 assert_eq!(pack_dos_time(&UNIX_EPOCH), DOTDOT_TIME);
4103 // 1979-12-31 23:59:59 UTC also clamps.
4104 let t = UNIX_EPOCH + Duration::from_secs(315_532_799);
4105 assert_eq!(pack_dos_time(&t), DOTDOT_TIME);
4106 }
4107
4108 /// A date in 2044+ sets DOS date bit 15 (`year-1980 >= 64`), which lands in
4109 /// bit 31 of the packed `u32` — so the `i32` `time` is **negative**. This is
4110 /// intentional: the `draw` recovers the fields via `(time as u32)` (the same
4111 /// cast `FileInfoPane::draw` uses), so the negative value round-trips
4112 /// correctly. Pinning it here so nobody "fixes" the sign.
4113 #[test]
4114 fn pack_dos_time_far_future_is_negative_and_round_trips() {
4115 use std::time::{Duration, UNIX_EPOCH};
4116 // 2050-01-01 00:00:00 UTC = 2524608000 secs since the epoch.
4117 let t = UNIX_EPOCH + Duration::from_secs(2_524_608_000);
4118 let packed = pack_dos_time(&t);
4119 // year-1980 = 70 (0x46); date = (70<<9)|(1<<5)|1 = 0x8C21; time = 0.
4120 // As a u32 that is 0x8C210000, whose i32 reinterpretation is negative.
4121 assert!(packed < 0, "year >= 2044 sets bit 31 -> negative i32");
4122 assert_eq!(packed as u32, 0x8C21_0000, "packed bit pattern");
4123
4124 // Unpack via the SAME `as u32` recovery the draw uses.
4125 let v = packed as u32;
4126 let date = v >> 16;
4127 let time = v & 0xFFFF;
4128 assert_eq!((date >> 9) + 1980, 2050, "year round-trips");
4129 assert_eq!((date >> 5) & 0xF, 1, "month");
4130 assert_eq!(date & 0x1F, 1, "day");
4131 assert_eq!(time >> 11, 0, "hour");
4132 assert_eq!((time >> 5) & 0x3F, 0, "minute");
4133 }
4134
4135 #[test]
4136 fn build_listing_packs_mtime_and_dotdot_constant() {
4137 use std::time::{Duration, UNIX_EPOCH};
4138 let t = UNIX_EPOCH + Duration::from_secs(1_609_459_200); // 2021-01-01
4139 let raw_entries = vec![("a.rs".to_string(), false, 10, Some(t))];
4140 let items = FileList::build_listing("/home/oetiker/", "*", &raw_entries);
4141 // items: "a.rs" (file, packed time), ".." (dir, DOTDOT_TIME).
4142 let a = items.iter().find(|r| r.name == "a.rs").unwrap();
4143 assert_eq!(a.time, 0x5221_0000, "file carries its packed mtime");
4144 let dd = items.iter().find(|r| r.name == "..").unwrap();
4145 assert_eq!(dd.time, DOTDOT_TIME, ".. carries the 0x210000 constant");
4146 }
4147
4148 // -- 4. snapshots ---------------------------------------------------------
4149
4150 fn render_fip(fip: &mut FileInfoPane, w: u16, h: u16) -> String {
4151 use crate::backend::{HeadlessBackend, Renderer};
4152 use crate::screen::Buffer;
4153 use crate::theme::Theme;
4154 use crate::view::{DrawCtx, View};
4155
4156 let theme = Theme::classic_blue();
4157 let (backend, screen) = HeadlessBackend::new(w, h);
4158 let mut r = Renderer::new(Box::new(backend));
4159 r.render(|buf: &mut Buffer| {
4160 let bounds = fip.state().get_bounds();
4161 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
4162 fip.draw(&mut dc);
4163 });
4164 screen.snapshot()
4165 }
4166
4167 /// A file entry with a real size + date. Width 47 (the pane in the dialog is
4168 /// 47 wide) so the right-aligned `size.x-38..` columns fit. Hand-verify the
4169 /// `Mon DD, YYYY HH:MMa/p` layout against the column offsets and the
4170 /// fg=cyan(3) bg=blue(1) InfoPane color.
4171 ///
4172 /// The frozen `report.t12345` in the snapshot is **expected** single-row-buffer
4173 /// behavior, NOT a bug: the name is drawn at col 1, then the size is drawn at
4174 /// col `size.x - 38` (= 9 here), overwriting the name's tail (`report.txt` →
4175 /// `report.t` + `12345`) — one shared row buffer, last write wins.
4176 #[test]
4177 fn snapshot_file_info_pane_file() {
4178 use std::time::{Duration, UNIX_EPOCH};
4179 let mut fip = FileInfoPane::new(Rect::new(0, 0, 47, 3), "/home/oetiker/", "*.rs");
4180 // 2021-06-15 14:37:00 UTC -> "Jun 15, 2021 02:37p".
4181 let t = UNIX_EPOCH + Duration::from_secs(1_623_767_820);
4182 fip.on_file_focused(Some(SearchRec {
4183 attr: 0,
4184 time: pack_dos_time(&t),
4185 size: 12345,
4186 name: "report.txt".into(),
4187 }));
4188 insta::assert_snapshot!(render_fip(&mut fip, 47, 3));
4189 }
4190
4191 /// The blank / noFile state: only the path line draws, no name/size/date.
4192 #[test]
4193 fn snapshot_file_info_pane_blank() {
4194 let mut fip = FileInfoPane::new(Rect::new(0, 0, 47, 3), "/home/oetiker/", "*.rs");
4195 // file_block stays None -> blank line 1.
4196 insta::assert_snapshot!(render_fip(&mut fip, 47, 3));
4197 }
4198
4199 // =========================================================================
4200 // FileDialog
4201 // =========================================================================
4202
4203 /// Resolve a `FileList` child by id, panicking if absent (test helper).
4204 fn fd_file_list(fd: &mut FileDialog) -> &mut FileList {
4205 fd.dialog
4206 .child_mut(fd.file_list_id)
4207 .and_then(|v| v.as_any_mut())
4208 .and_then(|a| a.downcast_mut::<FileList>())
4209 .expect("file_list resolves")
4210 }
4211
4212 // -- 1. assembly: ids distinct + the three captured children resolve -------
4213
4214 #[test]
4215 fn file_dialog_assembles_children() {
4216 // Open + Help selected (plus the always-present Cancel).
4217 let mut fd = FileDialog::new(
4218 "*.rs",
4219 "Open a File",
4220 "Name",
4221 FD_OPEN_BUTTON | FD_HELP_BUTTON,
4222 0,
4223 );
4224
4225 // The three captured ids are distinct and non-zero.
4226 assert_ne!(fd.file_name_id, fd.file_list_id);
4227 assert_ne!(fd.file_list_id, fd.info_pane_id);
4228 assert_ne!(fd.file_name_id, fd.info_pane_id);
4229
4230 // Each captured child resolves via child_mut + downcast.
4231 assert!(
4232 fd.dialog
4233 .child_mut(fd.file_name_id)
4234 .and_then(|v| v.as_any_mut())
4235 .and_then(|a| a.downcast_mut::<FileInputLine>())
4236 .is_some(),
4237 "file_name resolves to a FileInputLine"
4238 );
4239 assert!(
4240 fd.dialog
4241 .child_mut(fd.file_list_id)
4242 .and_then(|v| v.as_any_mut())
4243 .and_then(|a| a.downcast_mut::<FileList>())
4244 .is_some(),
4245 "file_list resolves to a FileList"
4246 );
4247 assert!(
4248 fd.dialog
4249 .child_mut(fd.info_pane_id)
4250 .and_then(|v| v.as_any_mut())
4251 .and_then(|a| a.downcast_mut::<FileInfoPane>())
4252 .is_some(),
4253 "info_pane resolves to a FileInfoPane"
4254 );
4255
4256 // The input line shows the wildcard as its initial text (strnzcpy).
4257 let fil = fd
4258 .dialog
4259 .child_mut(fd.file_name_id)
4260 .and_then(|v| v.as_any_mut())
4261 .and_then(|a| a.downcast_mut::<FileInputLine>())
4262 .unwrap();
4263 assert_eq!(fil.inner.data, "*.rs", "input line initial text = wildcard");
4264
4265 // needs_read_directory is armed when fdNoLoadDir is NOT set.
4266 assert!(fd.needs_read_directory, "armed without fdNoLoadDir");
4267 }
4268
4269 /// `FD_NO_LOAD_DIR` suppresses the initial directory-read arming.
4270 #[test]
4271 fn file_dialog_no_load_dir_disarms_read() {
4272 let fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4273 assert!(
4274 !fd.needs_read_directory,
4275 "fdNoLoadDir clears needs_read_directory"
4276 );
4277 }
4278
4279 // -- 1a. button_specs: the which/order/default/y chain by option mask ------
4280
4281 /// The pure button-layout decision (the source of the ctor's button set).
4282 /// Covers the degenerate no-option case, a single-option default, and the
4283 /// all-options chain (only the first is default; y steps +3).
4284 #[test]
4285 fn file_dialog_button_specs_combinations() {
4286 use crate::command::Command;
4287
4288 // No option buttons -> only Cancel, and NO default button at all.
4289 let none = button_specs(0);
4290 assert_eq!(none.len(), 1, "only Cancel inserted");
4291 assert_eq!(none[0].1, Command::CANCEL);
4292 assert!(!none[0].2, "Cancel is never the default (bfNormal)");
4293 assert_eq!(none[0].3, 3, "Cancel at the base y = 3");
4294
4295 // FD_OK_BUTTON alone -> OK (default, cmFileOpen) + Cancel.
4296 let ok = button_specs(FD_OK_BUTTON);
4297 assert_eq!(ok.len(), 2, "OK + Cancel");
4298 assert_eq!(ok[0].0, OK_TEXT);
4299 assert_eq!(ok[0].1, Command::FILE_OPEN, "OK fires cmFileOpen");
4300 assert!(ok[0].2, "the lone option button is the default");
4301 assert_eq!(ok[1].1, Command::CANCEL);
4302 assert!(!ok[1].2, "Cancel not default");
4303
4304 // All option buttons + Help -> Open, OK, Replace, Clear, Cancel, Help.
4305 let all = button_specs(
4306 FD_OPEN_BUTTON | FD_OK_BUTTON | FD_REPLACE_BUTTON | FD_CLEAR_BUTTON | FD_HELP_BUTTON,
4307 );
4308 assert_eq!(all.len(), 6, "4 option + Cancel + Help");
4309 // Order + commands.
4310 assert_eq!(
4311 all.iter().map(|b| b.1).collect::<Vec<_>>(),
4312 vec![
4313 Command::FILE_OPEN, // Open
4314 Command::FILE_OPEN, // OK
4315 Command::FILE_REPLACE, // Replace
4316 Command::FILE_CLEAR, // Clear
4317 Command::CANCEL, // Cancel
4318 Command::HELP, // Help
4319 ]
4320 );
4321 // Only the first (Open) is the default.
4322 assert!(all[0].2, "Open is the default");
4323 assert!(
4324 !all[1..].iter().any(|b| b.2),
4325 "no button after the first is the default"
4326 );
4327 // y steps +3 per button, starting at 3.
4328 assert!(
4329 all.iter().enumerate().all(|(i, b)| b.3 == 3 + 3 * i as i32),
4330 "y_top steps +3 per button: {:?}",
4331 all.iter().map(|b| b.3).collect::<Vec<_>>()
4332 );
4333 }
4334
4335 // -- 1b. reset_current performs the initial directory read (the title task) --
4336
4337 /// Driving `reset_current` (the ctx-bearing init hook) once flips the guard,
4338 /// sets the trailing-slash directory, and reads the current dir into the
4339 /// FileList. Asserts invariants (not the machine-dependent cwd contents): the
4340 /// guard flips, `directory` ends with `/`, and the FileList got a non-empty
4341 /// listing (the cwd always has at least `..`). A second call is a no-op.
4342 #[test]
4343 fn file_dialog_reset_current_reads_directory() {
4344 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON, 0);
4345 assert!(fd.needs_read_directory);
4346
4347 let mut out: VecDeque<Event> = VecDeque::new();
4348 let mut timers = crate::timer::TimerQueue::new();
4349 let mut deferred: Vec<Deferred> = vec![];
4350 {
4351 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4352 View::reset_current(&mut fd, &mut ctx);
4353 }
4354 assert!(!fd.needs_read_directory, "guard flips after the first run");
4355 assert!(
4356 fd.directory.ends_with('/'),
4357 "trailing-slash precondition on directory: {:?}",
4358 fd.directory
4359 );
4360 assert!(
4361 fd_file_list(&mut fd).lv().range > 0,
4362 "current dir read into the FileList (cwd always has at least '..')"
4363 );
4364
4365 // A second reset_current is a no-op (the guard already cleared).
4366 let range_after_first = fd_file_list(&mut fd).lv().range;
4367 {
4368 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4369 View::reset_current(&mut fd, &mut ctx);
4370 }
4371 assert_eq!(
4372 fd_file_list(&mut fd).lv().range,
4373 range_after_first,
4374 "second reset_current does not re-read"
4375 );
4376 }
4377
4378 // -- 2. handle_event: result commands end the modal ------------------------
4379
4380 #[test]
4381 fn file_dialog_file_open_ends_modal() {
4382 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON, 0);
4383
4384 let mut out: VecDeque<Event> = VecDeque::new();
4385 let mut timers = crate::timer::TimerQueue::new();
4386 let mut deferred: Vec<Deferred> = vec![];
4387 let mut ev = Event::Command(Command::FILE_OPEN);
4388 {
4389 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4390 fd.handle_event(&mut ev, &mut ctx);
4391 }
4392 assert!(ev.is_nothing(), "cmFileOpen consumed");
4393 assert_eq!(
4394 deferred
4395 .iter()
4396 .filter(|d| matches!(d, Deferred::EndModal(Command::FILE_OPEN)))
4397 .count(),
4398 1,
4399 "cmFileOpen queues EndModal(FILE_OPEN) directly (no modal-flag gate)"
4400 );
4401 }
4402
4403 // -- 3. handle_event: double-click re-posts an OK command ------------------
4404
4405 #[test]
4406 fn file_dialog_double_click_posts_ok() {
4407 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON, 0);
4408
4409 let mut out: VecDeque<Event> = VecDeque::new();
4410 let mut timers = crate::timer::TimerQueue::new();
4411 let mut deferred: Vec<Deferred> = vec![];
4412 let mut ev = Event::Broadcast {
4413 command: Command::FILE_DOUBLE_CLICKED,
4414 source: Some(crate::view::ViewId::next()),
4415 };
4416 {
4417 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4418 fd.handle_event(&mut ev, &mut ctx);
4419 }
4420 assert!(ev.is_nothing(), "cmFileDoubleClicked consumed");
4421 assert!(
4422 out.iter().any(|e| *e == Event::Command(Command::OK)),
4423 "cmFileDoubleClicked re-injects cmOK (putEvent == ctx.post)"
4424 );
4425 }
4426
4427 // -- 4. read_directory_listing (ctx-free) populates the listing ------------
4428
4429 #[test]
4430 fn file_list_read_directory_listing_populates() {
4431 // Deterministic fixture dir under the system temp dir.
4432 let tmp = std::env::temp_dir().join(format!("rstv_filedlg_b1_{}", std::process::id()));
4433 let _ = std::fs::remove_dir_all(&tmp);
4434 std::fs::create_dir_all(&tmp).unwrap();
4435 std::fs::write(tmp.join("keep.txt"), b"x").unwrap();
4436 std::fs::write(tmp.join("skip.rs"), b"y").unwrap();
4437 std::fs::create_dir_all(tmp.join("sub")).unwrap();
4438 let dir = format!("{}/", tmp.to_string_lossy());
4439
4440 let mut fl = FileList::new(Rect::new(0, 0, 30, 8), None, None);
4441 fl.read_directory_listing(&dir, "*.txt");
4442 let _ = std::fs::remove_dir_all(&tmp);
4443
4444 let names: Vec<&str> = fl.list().iter().map(|r| r.name.as_str()).collect();
4445 // "keep.txt" matches; "skip.rs" filtered; "sub" dir kept; ".." synthesized.
4446 assert_eq!(names, vec!["keep.txt", "sub", ".."]);
4447 // range/focused/top_item published without a Context.
4448 assert_eq!(fl.lv().range, 3, "range == listing length");
4449 assert_eq!(fl.lv().focused, 0, "focused reset to 0");
4450 assert_eq!(fl.lv().top_item, 0, "top_item reset to 0");
4451 }
4452
4453 // -- 5. snapshot: a fully-assembled dialog with a deterministic listing ----
4454
4455 /// Render the assembled FileDialog with a hardcoded listing injected (so the
4456 /// frame is deterministic — no real-filesystem size/mtime). The info pane's
4457 /// `file_block` is left `None` (blank size/date line); only its path line
4458 /// draws. Hand-verify: the frame + title, the input field showing "*.rs",
4459 /// the "Name" + "Files" labels, the Open/Cancel buttons, the two-column
4460 /// file list, and the "/fixture/*.rs" path line in the info pane.
4461 #[test]
4462 fn snapshot_file_dialog() {
4463 use crate::backend::{HeadlessBackend, Renderer};
4464 use crate::screen::Buffer;
4465 use crate::theme::Theme;
4466 use crate::view::DrawCtx;
4467
4468 let mut fd = FileDialog::new("*.rs", "Open a File", "Name", FD_OPEN_BUTTON, 0);
4469 // Mark the dialog selected/active so the frame draws its active style.
4470 fd.dialog.state_mut().state.selected = true;
4471 fd.dialog.state_mut().state.active = true;
4472
4473 // Inject a deterministic listing into the FileList (no fs read).
4474 {
4475 let fl = fd_file_list(&mut fd);
4476 fl.items = vec![
4477 SearchRec {
4478 attr: 0,
4479 time: 0,
4480 size: 100,
4481 name: "lib.rs".into(),
4482 },
4483 SearchRec {
4484 attr: 0,
4485 time: 0,
4486 size: 200,
4487 name: "main.rs".into(),
4488 },
4489 SearchRec {
4490 attr: FA_DIREC,
4491 time: 0,
4492 size: 0,
4493 name: "src".into(),
4494 },
4495 SearchRec {
4496 attr: FA_DIREC,
4497 time: DOTDOT_TIME,
4498 size: 0,
4499 name: "..".into(),
4500 },
4501 ];
4502 fl.lv.range = fl.items.len() as i32;
4503 fl.lv.focused = 0;
4504 fl.lv.state.state.selected = true;
4505 fl.lv.state.state.active = true;
4506 fl.lv.state.state.focused = true;
4507 }
4508 // Set the info pane's path line deterministically.
4509 if let Some(fip) = fd
4510 .dialog
4511 .child_mut(fd.info_pane_id)
4512 .and_then(|v| v.as_any_mut())
4513 .and_then(|a| a.downcast_mut::<FileInfoPane>())
4514 {
4515 fip.set_dir_info("/fixture/", "*.rs");
4516 }
4517
4518 let theme = Theme::classic_blue();
4519 let (backend, screen) = HeadlessBackend::new(64, 20);
4520 let mut r = Renderer::new(Box::new(backend));
4521 let mut view: Box<dyn View> = Box::new(fd);
4522 r.render(|buf: &mut Buffer| {
4523 let bounds = view.state().get_bounds();
4524 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
4525 view.draw(&mut dc);
4526 });
4527 insta::assert_snapshot!(screen.snapshot());
4528 }
4529
4530 // =========================================================================
4531 // FileDialog: path logic + valid + messageBoxes
4532 // =========================================================================
4533
4534 // -- 6a. pure path helpers -------------------------------------------------
4535
4536 #[test]
4537 fn expand_path_absolute_passthrough() {
4538 // Absolute input ignores `dir`.
4539 assert_eq!(expand_path("/home/oetiker/", "/etc/hosts"), "/etc/hosts");
4540 assert_eq!(expand_path("/some/where/", "/"), "/");
4541 }
4542
4543 #[test]
4544 fn expand_path_relative_joins_dir() {
4545 assert_eq!(
4546 expand_path("/home/oetiker/", "foo.txt"),
4547 "/home/oetiker/foo.txt"
4548 );
4549 assert_eq!(
4550 expand_path("/home/oetiker/", "sub/bar"),
4551 "/home/oetiker/sub/bar"
4552 );
4553 }
4554
4555 #[test]
4556 fn expand_path_dotdot_and_dot_normalize() {
4557 // `..` pops a component; `.` is dropped.
4558 assert_eq!(expand_path("/home/oetiker/", "../foo"), "/home/foo");
4559 assert_eq!(expand_path("/home/oetiker/", "./bar"), "/home/oetiker/bar");
4560 assert_eq!(expand_path("/a/b/c/", "../../x"), "/a/x");
4561 // `..` past the root stays at the root (never pops the RootDir).
4562 assert_eq!(expand_path("/", "../../etc"), "/etc");
4563 }
4564
4565 #[test]
4566 fn expand_path_collapses_double_slash() {
4567 // `//` collapses (components() ignores empty segments).
4568 assert_eq!(expand_path("/home//oetiker/", "x"), "/home/oetiker/x");
4569 assert_eq!(expand_path("/home/oetiker/", "a//b"), "/home/oetiker/a/b");
4570 }
4571
4572 #[test]
4573 fn expand_path_preserves_trailing_slash_for_bare_dir() {
4574 // A trailing slash (directory-only input) is preserved so get_file_name
4575 // can detect the bare-dir case.
4576 assert_eq!(expand_path("/home/oetiker/", "sub/"), "/home/oetiker/sub/");
4577 // An empty field resolves to the directory itself (trailing slash).
4578 assert_eq!(expand_path("/home/oetiker/", ""), "/home/oetiker/");
4579 }
4580
4581 #[test]
4582 fn is_wild_detects_glob() {
4583 assert!(is_wild("*.txt"));
4584 assert!(is_wild("foo?.rs"));
4585 assert!(!is_wild("plain.txt"));
4586 assert!(!is_wild("/a/b/c"));
4587 }
4588
4589 #[test]
4590 fn split_dir_file_splits() {
4591 assert_eq!(
4592 split_dir_file("/home/oetiker/foo.txt"),
4593 ("/home/oetiker/".to_string(), "foo.txt".to_string())
4594 );
4595 // Wildcard pattern: dir + the `*.txt` "filename".
4596 assert_eq!(
4597 split_dir_file("/home/oetiker/*.txt"),
4598 ("/home/oetiker/".to_string(), "*.txt".to_string())
4599 );
4600 // Bare directory (trailing slash) → empty file part.
4601 assert_eq!(
4602 split_dir_file("/home/oetiker/"),
4603 ("/home/oetiker/".to_string(), String::new())
4604 );
4605 // Root.
4606 assert_eq!(split_dir_file("/"), ("/".to_string(), String::new()));
4607 }
4608
4609 #[test]
4610 fn valid_file_name_basic() {
4611 assert!(valid_file_name("/home/oetiker/foo.txt"));
4612 assert!(valid_file_name("foo.txt"));
4613 assert!(!valid_file_name(""));
4614 assert!(!valid_file_name("/home/oetiker/")); // bare dir → no filename
4615 assert!(!valid_file_name("a\0b")); // interior NUL
4616 }
4617
4618 // -- 6b. get_file_name: wildcard-append on a bare-dir field ----------------
4619
4620 /// A no-load dialog with a bare-directory field resolves to
4621 /// `<dir>/<wildcard>` (no filename part → the wildcard is appended).
4622 #[test]
4623 fn get_file_name_appends_wildcard_for_bare_dir() {
4624 let mut fd = FileDialog::new("*.rs", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4625 fd.directory = "/home/oetiker/".into();
4626 // Field text is a bare subdirectory (trailing slash → no filename part).
4627 fd_set_field(&mut fd, "sub/");
4628 assert_eq!(fd.get_file_name(), "/home/oetiker/sub/*.rs");
4629 // The resolved_name cache mirrors the return value.
4630 assert_eq!(fd.resolved_name, "/home/oetiker/sub/*.rs");
4631 }
4632
4633 /// A plain filename field resolves to the absolute path, no wildcard append.
4634 #[test]
4635 fn get_file_name_plain_filename() {
4636 let mut fd = FileDialog::new("*.rs", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4637 fd.directory = "/home/oetiker/".into();
4638 fd_set_field(&mut fd, "main.rs");
4639 assert_eq!(fd.get_file_name(), "/home/oetiker/main.rs");
4640 }
4641
4642 // -- 6c. valid() branches --------------------------------------------------
4643
4644 /// Set the FileInputLine's text (test helper).
4645 fn fd_set_field(fd: &mut FileDialog, text: &str) {
4646 fd.dialog
4647 .child_mut(fd.file_name_id)
4648 .and_then(|v| v.as_any_mut())
4649 .and_then(|a| a.downcast_mut::<FileInputLine>())
4650 .expect("file_name resolves")
4651 .inner
4652 .data = text.to_string();
4653 }
4654
4655 fn count_open_boxes(deferred: &[Deferred]) -> usize {
4656 deferred
4657 .iter()
4658 .filter(|d| matches!(d, Deferred::OpenMessageBox { .. }))
4659 .count()
4660 }
4661
4662 /// The cancel and file-clear commands are always valid: they return true after
4663 /// the group validation without a navigate/accept branch or a message box.
4664 /// `get_file_name` does run, but for a wildcard field it is purely lexical —
4665 /// no FS touch, no error box.
4666 #[test]
4667 fn valid_cancel_and_file_clear_always_true() {
4668 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4669 // A clearly-invalid wildcard path — the directory check must NOT run for these.
4670 fd.directory = "/no/such/dir/at/all/".into();
4671 fd_set_field(&mut fd, "/no/such/dir/at/all/*.x");
4672
4673 let mut out: VecDeque<Event> = VecDeque::new();
4674 let mut timers = crate::timer::TimerQueue::new();
4675 let mut deferred: Vec<Deferred> = vec![];
4676 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4677
4678 assert!(fd.valid(Command::CANCEL, &mut ctx), "cmCancel always valid");
4679 assert!(
4680 fd.valid(Command::FILE_CLEAR, &mut ctx),
4681 "cmFileClear always valid"
4682 );
4683 assert_eq!(count_open_boxes(&deferred), 0, "no messageBox for these");
4684 }
4685
4686 /// `valid(FILE_CLEAR)` returns true AND leaves `value()` reflecting the
4687 /// resolved field name — pinning the cache-refresh fix: the filename is
4688 /// resolved unconditionally, so the cancel/clear path must still refresh
4689 /// `resolved_name` (it runs `get_file_name` before the early-return).
4690 #[test]
4691 fn valid_file_clear_refreshes_value_cache() {
4692 let mut fd = FileDialog::new("*", "t", "Name", FD_CLEAR_BUTTON | FD_NO_LOAD_DIR, 0);
4693 fd.directory = "/home/oetiker/".into();
4694 fd_set_field(&mut fd, "report.txt");
4695 // Before any valid() the cache is empty.
4696 assert_eq!(
4697 View::value(&fd),
4698 Some(crate::data::FieldValue::Text(String::new())),
4699 "cache empty before valid()"
4700 );
4701
4702 let mut out: VecDeque<Event> = VecDeque::new();
4703 let mut timers = crate::timer::TimerQueue::new();
4704 let mut deferred: Vec<Deferred> = vec![];
4705 let accepted = {
4706 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4707 fd.valid(Command::FILE_CLEAR, &mut ctx)
4708 };
4709 assert!(accepted, "cmFileClear is valid");
4710 // value() now reflects the resolved field name, not a stale/empty value.
4711 assert_eq!(
4712 View::value(&fd),
4713 Some(crate::data::FieldValue::Text(
4714 "/home/oetiker/report.txt".into()
4715 )),
4716 "resolved_name refreshed on the cmFileClear path"
4717 );
4718 assert_eq!(count_open_boxes(&deferred), 0, "no messageBox");
4719 }
4720
4721 /// `cmValid` returns true immediately (before the base call).
4722 #[test]
4723 fn valid_cmvalid_short_circuits() {
4724 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4725 let mut out: VecDeque<Event> = VecDeque::new();
4726 let mut timers = crate::timer::TimerQueue::new();
4727 let mut deferred: Vec<Deferred> = vec![];
4728 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4729 assert!(fd.valid(Command::VALID, &mut ctx));
4730 }
4731
4732 /// A wildcard field over an existing directory → NAVIGATE: returns false,
4733 /// updates `directory`/`wild_card`, re-reads the FileList, no messageBox.
4734 #[test]
4735 fn valid_wildcard_navigates() {
4736 let tmp = std::env::temp_dir().join(format!("rstv_fd_wild_{}", std::process::id()));
4737 let _ = std::fs::remove_dir_all(&tmp);
4738 std::fs::create_dir_all(&tmp).unwrap();
4739 std::fs::write(tmp.join("keep.md"), b"x").unwrap();
4740 let dir = format!("{}/", tmp.to_string_lossy());
4741
4742 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4743 fd.directory = dir.clone();
4744 // A wildcard pattern rooted at the fixture dir.
4745 fd_set_field(&mut fd, &format!("{dir}*.md"));
4746
4747 let mut out: VecDeque<Event> = VecDeque::new();
4748 let mut timers = crate::timer::TimerQueue::new();
4749 let mut deferred: Vec<Deferred> = vec![];
4750 let accepted = {
4751 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4752 fd.valid(Command::FILE_OPEN, &mut ctx)
4753 };
4754 let _ = std::fs::remove_dir_all(&tmp);
4755
4756 assert!(!accepted, "a wildcard navigates → not accepted (false)");
4757 assert_eq!(fd.wild_card, "*.md", "wild_card updated to the new mask");
4758 assert_eq!(fd.directory, dir, "directory unchanged (same dir)");
4759 assert_eq!(count_open_boxes(&deferred), 0, "valid dir → no error box");
4760 // The FileList was re-read with the new mask (only keep.md + "..").
4761 let names: Vec<String> = fd_file_list(&mut fd)
4762 .list()
4763 .iter()
4764 .map(|r| r.name.clone())
4765 .collect();
4766 assert!(
4767 names.contains(&"keep.md".to_string()),
4768 "matched file present"
4769 );
4770 }
4771
4772 /// An existing directory field → NAVIGATE into it: false, `directory`
4773 /// updated (with a trailing slash), no messageBox.
4774 #[test]
4775 fn valid_existing_dir_navigates_into_it() {
4776 let tmp = std::env::temp_dir().join(format!("rstv_fd_dir_{}", std::process::id()));
4777 let _ = std::fs::remove_dir_all(&tmp);
4778 std::fs::create_dir_all(tmp.join("sub")).unwrap();
4779 let dir = format!("{}/", tmp.to_string_lossy());
4780 let subdir = format!("{}/sub", tmp.to_string_lossy());
4781
4782 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4783 fd.directory = dir;
4784 fd_set_field(&mut fd, &subdir); // existing dir, no trailing slash
4785
4786 let mut out: VecDeque<Event> = VecDeque::new();
4787 let mut timers = crate::timer::TimerQueue::new();
4788 let mut deferred: Vec<Deferred> = vec![];
4789 let accepted = {
4790 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4791 fd.valid(Command::FILE_OPEN, &mut ctx)
4792 };
4793 let _ = std::fs::remove_dir_all(&tmp);
4794
4795 assert!(!accepted, "navigating into a dir → not accepted");
4796 assert_eq!(
4797 fd.directory,
4798 format!("{subdir}/"),
4799 "directory updated to the sub dir with a trailing '/'"
4800 );
4801 assert_eq!(count_open_boxes(&deferred), 0);
4802 }
4803
4804 /// A plain, valid filename → ACCEPT (true), no messageBox.
4805 #[test]
4806 fn valid_filename_accepts() {
4807 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4808 fd.directory = "/home/oetiker/".into();
4809 fd_set_field(&mut fd, "report.txt");
4810
4811 let mut out: VecDeque<Event> = VecDeque::new();
4812 let mut timers = crate::timer::TimerQueue::new();
4813 let mut deferred: Vec<Deferred> = vec![];
4814 let accepted = {
4815 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4816 fd.valid(Command::FILE_OPEN, &mut ctx)
4817 };
4818 assert!(accepted, "a real filename is accepted");
4819 assert_eq!(count_open_boxes(&deferred), 0);
4820 // value() now returns the resolved name (cache refreshed by valid()).
4821 assert_eq!(
4822 View::value(&fd),
4823 Some(crate::data::FieldValue::Text(
4824 "/home/oetiker/report.txt".into()
4825 ))
4826 );
4827 }
4828
4829 /// A wildcard over a NON-existent directory → the directory check fails → an
4830 /// invalid-drive box is queued + refocus the field + false.
4831 #[test]
4832 fn valid_wildcard_bad_dir_queues_error_box() {
4833 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4834 fd.directory = "/".into();
4835 fd_set_field(&mut fd, "/no/such/dir/zzz/*.x");
4836
4837 let mut out: VecDeque<Event> = VecDeque::new();
4838 let mut timers = crate::timer::TimerQueue::new();
4839 let mut deferred: Vec<Deferred> = vec![];
4840 let accepted = {
4841 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4842 fd.valid(Command::FILE_OPEN, &mut ctx)
4843 };
4844 assert!(!accepted, "bad-dir wildcard keeps the dialog open");
4845 assert_eq!(
4846 count_open_boxes(&deferred),
4847 1,
4848 "one invalid-drive box queued"
4849 );
4850 assert!(
4851 deferred
4852 .iter()
4853 .any(|d| matches!(d, Deferred::FocusById(id) if *id == fd.file_name_id)),
4854 "field is refocused after the error"
4855 );
4856 }
4857
4858 /// The invalid-file branch: not wild, not an existing dir, not a valid
4859 /// filename → the invalid-file box is queued + false.
4860 ///
4861 /// To reach an empty filename component after `get_file_name`, the wildcard
4862 /// itself must be empty (otherwise the bare-dir case appends a non-empty
4863 /// name). With an empty wildcard and a bare-directory field over a
4864 /// non-existent dir, the resolved path stays directory-only → not an existing
4865 /// directory, not a valid filename → invalid-file.
4866 #[test]
4867 fn valid_invalid_filename_queues_error_box() {
4868 // Empty wildcard so get_file_name does NOT append a filename to a bare dir.
4869 let mut fd = FileDialog::new("", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4870 fd.directory = "/no/such/dir/qqq/".into();
4871 // Field text resolves to a non-existent bare directory (trailing slash).
4872 fd_set_field(&mut fd, "/no/such/dir/qqq/sub/");
4873
4874 let mut out: VecDeque<Event> = VecDeque::new();
4875 let mut timers = crate::timer::TimerQueue::new();
4876 let mut deferred: Vec<Deferred> = vec![];
4877 let accepted = {
4878 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
4879 fd.valid(Command::FILE_OPEN, &mut ctx)
4880 };
4881 assert!(!accepted, "invalid filename keeps the dialog open");
4882 assert_eq!(
4883 count_open_boxes(&deferred),
4884 1,
4885 "one invalid-file box queued"
4886 );
4887 }
4888
4889 // -- 6d. set_value loads the field -----------------------------------------
4890
4891 #[test]
4892 fn set_value_loads_field_text() {
4893 let mut fd = FileDialog::new("*", "t", "Name", FD_OPEN_BUTTON | FD_NO_LOAD_DIR, 0);
4894 View::set_value(&mut fd, crate::data::FieldValue::Text("loaded.txt".into()));
4895 let text = fd
4896 .dialog
4897 .child_mut(fd.file_name_id)
4898 .and_then(|v| v.as_any_mut())
4899 .and_then(|a| a.downcast_mut::<FileInputLine>())
4900 .unwrap()
4901 .text()
4902 .to_string();
4903 assert_eq!(text, "loaded.txt");
4904 }
4905
4906 // =========================================================================
4907 // ChDirDialog
4908 // =========================================================================
4909
4910 /// Resolve the `DirListBox` child by id (for deterministic injection).
4911 fn cd_dir_list(cd: &mut ChDirDialog) -> &mut DirListBox {
4912 cd.dialog
4913 .child_mut(cd.dir_list_id)
4914 .and_then(|v| v.as_any_mut())
4915 .and_then(|a| a.downcast_mut::<DirListBox>())
4916 .expect("dir_list resolves")
4917 }
4918
4919 // -- assembly --------------------------------------------------------------
4920
4921 /// The three captured ids are distinct, resolve to the right types, and the
4922 /// Chdir button carries the change-directory command. (Mirrors
4923 /// `file_dialog_assembles_children` — id-distinctness + downcast, no
4924 /// child-count accessor on `Dialog`.)
4925 #[test]
4926 fn chdir_dialog_assembles_children() {
4927 let mut cd = ChDirDialog::new(CD_NORMAL, 0);
4928
4929 assert_ne!(cd.dir_input_id, cd.dir_list_id);
4930 assert_ne!(cd.dir_list_id, cd.chdir_button_id);
4931 assert_ne!(cd.dir_input_id, cd.chdir_button_id);
4932
4933 // dir_input is a plain InputLine (no as_any_mut override → not
4934 // downcastable); verify it resolves and exposes a Text value.
4935 assert!(
4936 matches!(
4937 cd.dialog.child_mut(cd.dir_input_id).and_then(|v| v.value()),
4938 Some(crate::data::FieldValue::Text(_))
4939 ),
4940 "dir_input resolves to a Text-valued InputLine"
4941 );
4942 assert!(
4943 cd.dialog
4944 .child_mut(cd.dir_list_id)
4945 .and_then(|v| v.as_any_mut())
4946 .and_then(|a| a.downcast_mut::<DirListBox>())
4947 .is_some(),
4948 "dir_list resolves to a DirListBox"
4949 );
4950 // The Chdir button carries the change-directory command (public `command`).
4951 let cmd = cd
4952 .dialog
4953 .child_mut(cd.chdir_button_id)
4954 .and_then(|v| v.as_any_mut())
4955 .and_then(|a| a.downcast_mut::<crate::widgets::Button>())
4956 .map(|b| b.command);
4957 assert_eq!(cmd, Some(Command::CHANGE_DIR), "chdir button cmChangeDir");
4958 }
4959
4960 /// `dataSize() == 0`: `value`/`set_value` are skip-listed so they fall to
4961 /// the `View` trait default (`None` / no-op), NOT the inner `Dialog`'s
4962 /// group-gather. Proven empirically: `value()` returns `None` (a gather would
4963 /// return `Some(Record(..))`), and `set_value` is a silent no-op (value stays
4964 /// `None` after a set).
4965 #[test]
4966 fn chdir_dialog_value_is_trait_default_none() {
4967 let mut cd = ChDirDialog::new(CD_NORMAL, 0);
4968 assert_eq!(
4969 crate::view::View::value(&cd),
4970 None,
4971 "value() is the trait default None (skip-listed; not the Dialog gather)"
4972 );
4973 // set_value is a no-op (trait default) — it does not establish a value.
4974 crate::view::View::set_value(&mut cd, crate::data::FieldValue::Text("x".into()));
4975 assert_eq!(
4976 crate::view::View::value(&cd),
4977 None,
4978 "set_value is a no-op; value() stays None"
4979 );
4980 }
4981
4982 /// The Chdir button id is wired into the dir list (so its focus changes
4983 /// (un-)default it).
4984 #[test]
4985 fn chdir_dialog_wires_chdir_button_into_dir_list() {
4986 let mut cd = ChDirDialog::new(CD_NORMAL, 0);
4987 let chdir_id = cd.chdir_button_id;
4988 assert_eq!(
4989 cd_dir_list(&mut cd).chdir_button,
4990 Some(chdir_id),
4991 "dir list knows the chdir button id"
4992 );
4993 }
4994
4995 // -- select_item posts cmChangeDir ----------------------------------------
4996
4997 /// Selecting a dir-list item posts a change-directory command (payload-less;
4998 /// the dialog reads the focused entry).
4999 #[test]
5000 fn dir_list_select_item_posts_change_dir() {
5001 let mut dl = DirListBox::new(Rect::new(0, 0, 30, 10), None, None);
5002 let mut out: VecDeque<Event> = VecDeque::new();
5003 let mut timers = crate::timer::TimerQueue::new();
5004 let mut deferred: Vec<Deferred> = vec![];
5005 {
5006 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5007 dl.select_item(2, &mut ctx);
5008 }
5009 assert_eq!(
5010 out.iter()
5011 .filter(|e| matches!(e, Event::Command(c) if *c == Command::CHANGE_DIR))
5012 .count(),
5013 1,
5014 "selectItem posts exactly one cmChangeDir"
5015 );
5016 }
5017
5018 // -- set_state -> MakeButtonDefault ----------------------------------------
5019
5020 /// A focus-state change on the dir list queues
5021 /// `MakeButtonDefault { button, enable }` for the wired chdir button.
5022 #[test]
5023 fn dir_list_set_state_focus_queues_make_button_default() {
5024 let mut dl = DirListBox::new(Rect::new(0, 0, 30, 10), None, None);
5025 let btn = crate::view::ViewId::next();
5026 dl.set_chdir_button(btn);
5027
5028 let mut out: VecDeque<Event> = VecDeque::new();
5029 let mut timers = crate::timer::TimerQueue::new();
5030 let mut deferred: Vec<Deferred> = vec![];
5031 {
5032 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5033 View::set_state(&mut dl, crate::view::StateFlag::Focused, true, &mut ctx);
5034 }
5035 assert!(
5036 deferred.iter().any(|d| matches!(
5037 d,
5038 Deferred::MakeButtonDefault { button, enable: true } if *button == btn
5039 )),
5040 "focus-gain queues MakeButtonDefault(enable=true)"
5041 );
5042 }
5043
5044 /// Losing focus queues `MakeButtonDefault { enable: false }`.
5045 #[test]
5046 fn dir_list_set_state_unfocus_queues_make_button_default_false() {
5047 let mut dl = DirListBox::new(Rect::new(0, 0, 30, 10), None, None);
5048 let btn = crate::view::ViewId::next();
5049 dl.set_chdir_button(btn);
5050
5051 let mut out: VecDeque<Event> = VecDeque::new();
5052 let mut timers = crate::timer::TimerQueue::new();
5053 let mut deferred: Vec<Deferred> = vec![];
5054 {
5055 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5056 View::set_state(&mut dl, crate::view::StateFlag::Focused, false, &mut ctx);
5057 }
5058 assert!(
5059 deferred.iter().any(|d| matches!(
5060 d,
5061 Deferred::MakeButtonDefault { button, enable: false } if *button == btn
5062 )),
5063 "focus-loss queues MakeButtonDefault(enable=false)"
5064 );
5065 }
5066
5067 /// A non-focus state change, or no wired button, queues nothing.
5068 #[test]
5069 fn dir_list_set_state_no_button_queues_nothing() {
5070 let mut dl = DirListBox::new(Rect::new(0, 0, 30, 10), None, None);
5071 // chdir_button is None (no change-directory owner).
5072 let mut out: VecDeque<Event> = VecDeque::new();
5073 let mut timers = crate::timer::TimerQueue::new();
5074 let mut deferred: Vec<Deferred> = vec![];
5075 {
5076 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5077 View::set_state(&mut dl, crate::view::StateFlag::Focused, true, &mut ctx);
5078 }
5079 assert!(
5080 !deferred
5081 .iter()
5082 .any(|d| matches!(d, Deferred::MakeButtonDefault { .. })),
5083 "no wired button -> no MakeButtonDefault"
5084 );
5085 }
5086
5087 // -- new_directory trailing-slash normalize --------------------------------
5088
5089 /// `new_directory` normalizes a no-trailing-slash dir (as `current_dir`
5090 /// returns) to a trailing `/` before building the tree, so `self.dir` is
5091 /// always `/`-terminated. `/tmp` (a real dir) is used so the fs read succeeds.
5092 #[test]
5093 fn new_directory_normalizes_trailing_slash() {
5094 let mut dl = DirListBox::new(Rect::new(0, 0, 30, 10), None, None);
5095 let mut out: VecDeque<Event> = VecDeque::new();
5096 let mut timers = crate::timer::TimerQueue::new();
5097 let mut deferred: Vec<Deferred> = vec![];
5098 {
5099 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5100 // No trailing slash on input.
5101 dl.new_directory("/tmp", &mut ctx);
5102 }
5103 assert_eq!(dl.dir, "/tmp/", "stored dir is trailing-slash-normalized");
5104 // The root entry plus the /tmp ancestor are present.
5105 assert_eq!(dl.list()[0].dir(), "/", "root entry");
5106 }
5107
5108 // -- trim_end_separator (root guard) ---------------------------------------
5109
5110 #[test]
5111 fn trim_end_separator_keeps_root() {
5112 assert_eq!(ChDirDialog::trim_end_separator("/"), "/", "root preserved");
5113 assert_eq!(ChDirDialog::trim_end_separator("/home/"), "/home");
5114 assert_eq!(ChDirDialog::trim_end_separator("/home"), "/home");
5115 assert_eq!(ChDirDialog::trim_end_separator("/a/b/c/"), "/a/b/c");
5116 }
5117
5118 // -- valid: failure path ONLY (never really chdir's; cwd is process-global) -
5119
5120 /// `valid(OK)` on a guaranteed-nonexistent directory: the real
5121 /// `set_current_dir` fails, so an "Invalid directory" box is queued and the
5122 /// dialog stays open (`false`). The cwd is NOT changed (`set_current_dir`
5123 /// does not mutate on error), so this is safe to run alongside other tests.
5124 #[test]
5125 fn chdir_valid_bad_dir_queues_error_box() {
5126 let mut cd = ChDirDialog::new(CD_NO_LOAD_DIR, 0);
5127 // Set the path input line's text directly (ChDirDialog has no set_value of its own
5128 // — value/set_value are skip-listed to the trait default). A path that
5129 // cannot exist (absolute, so expand_path passes it through verbatim).
5130 if let Some(input) = cd.dialog.child_mut(cd.dir_input_id) {
5131 crate::view::View::set_value(
5132 input,
5133 crate::data::FieldValue::Text("/nonexistent_rstv_xyz_zzz".into()),
5134 );
5135 }
5136
5137 let mut out: VecDeque<Event> = VecDeque::new();
5138 let mut timers = crate::timer::TimerQueue::new();
5139 let mut deferred: Vec<Deferred> = vec![];
5140 let accepted = {
5141 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5142 cd.valid(Command::OK, &mut ctx)
5143 };
5144 assert!(!accepted, "bad dir keeps the dialog open");
5145 assert_eq!(count_open_boxes(&deferred), 1, "one invalid-dir box queued");
5146 }
5147
5148 /// `valid` for any non-OK command is always true (and queues nothing).
5149 #[test]
5150 fn chdir_valid_non_ok_always_true() {
5151 let mut cd = ChDirDialog::new(CD_NO_LOAD_DIR, 0);
5152 let mut out: VecDeque<Event> = VecDeque::new();
5153 let mut timers = crate::timer::TimerQueue::new();
5154 let mut deferred: Vec<Deferred> = vec![];
5155 let ok = {
5156 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5157 cd.valid(Command::CANCEL, &mut ctx)
5158 };
5159 assert!(ok, "non-cmOK is always valid");
5160 assert_eq!(count_open_boxes(&deferred), 0, "no box for non-cmOK");
5161 }
5162
5163 // -- snapshot: deterministic, NO reset_current (which reads cwd) -----------
5164
5165 #[test]
5166 fn snapshot_chdir_dialog() {
5167 use crate::backend::{HeadlessBackend, Renderer};
5168 use crate::screen::Buffer;
5169 use crate::theme::Theme;
5170 use crate::view::DrawCtx;
5171
5172 let mut cd = ChDirDialog::new(CD_HELP_BUTTON, 0);
5173 cd.dialog.state_mut().state.selected = true;
5174 cd.dialog.state_mut().state.active = true;
5175
5176 // Inject a deterministic dir tree (no fs read): /home/user/ with two
5177 // subdirs. build_tree gives a real tree + cur index.
5178 {
5179 let (items, cur) =
5180 DirListBox::build_tree("/home/user/", &["projects".into(), "src".into()]);
5181 let dl = cd_dir_list(&mut cd);
5182 dl.items = items;
5183 dl.cur = cur;
5184 dl.dir = "/home/user/".into();
5185 dl.lv.range = dl.items.len() as i32;
5186 dl.lv.focused = cur as i32;
5187 dl.lv.state.state.selected = true;
5188 dl.lv.state.state.active = true;
5189 dl.lv.state.state.focused = true;
5190 }
5191 // Set the dirInput text deterministically (the trimmed current dir).
5192 if let Some(input) = cd.dialog.child_mut(cd.dir_input_id) {
5193 crate::view::View::set_value(input, crate::data::FieldValue::Text("/home/user".into()));
5194 }
5195
5196 let theme = Theme::classic_blue();
5197 let (backend, screen) = HeadlessBackend::new(64, 20);
5198 let mut r = Renderer::new(Box::new(backend));
5199 let mut view: Box<dyn View> = Box::new(cd);
5200 r.render(|buf: &mut Buffer| {
5201 let bounds = view.state().get_bounds();
5202 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
5203 view.draw(&mut dc);
5204 });
5205 insta::assert_snapshot!(screen.snapshot());
5206 }
5207
5208 // -- reset_current focuses dirInput (currency) without the cwd read --------
5209
5210 /// `reset_current` with `cdNoLoadDir` set establishes currency (focuses the
5211 /// first selectable = dirInput) but skips the cwd read, so it is cwd-safe.
5212 #[test]
5213 fn chdir_reset_current_no_load_dir_skips_read() {
5214 let mut cd = ChDirDialog::new(CD_NO_LOAD_DIR, 0);
5215 assert!(!cd.needs_setup, "cdNoLoadDir clears the setup guard");
5216 let mut out: VecDeque<Event> = VecDeque::new();
5217 let mut timers = crate::timer::TimerQueue::new();
5218 let mut deferred: Vec<Deferred> = vec![];
5219 {
5220 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5221 View::reset_current(&mut cd, &mut ctx);
5222 }
5223 // The dir list was never populated (no cwd read).
5224 assert!(
5225 cd_dir_list(&mut cd).list().is_empty(),
5226 "no directory read under cdNoLoadDir"
5227 );
5228 }
5229
5230 // =========================================================================
5231 // finishers: wfGrow, screen-relative resize, SearchRec fs metadata
5232 // =========================================================================
5233
5234 // ---- finisher 1: growable flag ------------------------------------------
5235
5236 /// The file dialog constructor marks the dialog growable; verify the flag is
5237 /// set after construction.
5238 #[test]
5239 fn file_dialog_ctor_sets_wf_grow() {
5240 let fd = FileDialog::new("*.*", "Test", "Name", FD_OPEN_BUTTON, 0);
5241 let flags = fd.dialog.flags();
5242 assert!(flags.grow, "grow flag must be set on FileDialog");
5243 assert!(flags.r#move, "wfMove retained");
5244 assert!(flags.close, "wfClose retained");
5245 assert!(!flags.zoom, "wfZoom not set (dialog has no zoom)");
5246 }
5247
5248 /// The change-directory dialog constructor marks the dialog growable; verify
5249 /// the flag is set after construction.
5250 #[test]
5251 fn chdir_dialog_ctor_sets_wf_grow() {
5252 let cd = ChDirDialog::new(CD_NO_LOAD_DIR, 0);
5253 let flags = cd.dialog.flags();
5254 assert!(flags.grow, "grow flag must be set on ChDirDialog");
5255 assert!(flags.r#move, "wfMove retained");
5256 assert!(flags.close, "wfClose retained");
5257 assert!(!flags.zoom, "wfZoom not set");
5258 }
5259
5260 // ---- finisher 2: screen-relative resize ---------------------------------
5261
5262 /// On a wide screen (> 90 cols) the resize formula fires `grow(15, 0)` —
5263 /// dialog width goes from 49 to 79. Verify via handle_event with
5264 /// `ctx.owner_size` = (100, 25).
5265 #[test]
5266 fn file_dialog_screen_resize_wide_screen() {
5267 use crate::view::Point;
5268
5269 let mut fd = FileDialog::new("*.*", "T", "N", FD_NO_LOAD_DIR, 0);
5270 assert!(fd.needs_screen_resize, "flag set by ctor");
5271
5272 // Assign an id so request_bounds can reference it.
5273 fd.dialog.state_mut().id = Some(crate::view::ViewId::next());
5274
5275 let bounds_before = crate::view::View::state(&fd).get_bounds();
5276 let w_before = bounds_before.b.x - bounds_before.a.x;
5277 assert_eq!(w_before, 49, "base width 49 before resize");
5278
5279 let mut out: VecDeque<Event> = VecDeque::new();
5280 let mut timers = crate::timer::TimerQueue::new();
5281 let mut deferred: Vec<Deferred> = vec![];
5282 {
5283 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5284 // owner_size = (100, 25): triggers the x > 90 branch (grow 15) but
5285 // NOT the y > 34 branch, so height stays 19.
5286 ctx.set_owner_size(Point::new(100, 25));
5287 let mut ev = crate::event::Event::Nothing;
5288 crate::view::View::handle_event(&mut fd, &mut ev, &mut ctx);
5289 }
5290
5291 assert!(
5292 !fd.needs_screen_resize,
5293 "flag cleared after first handle_event"
5294 );
5295 // A ChangeBounds deferred should have been queued.
5296 let bounds_deferred = deferred.iter().find_map(|d| {
5297 if let Deferred::ChangeBounds(_, r) = d {
5298 Some(*r)
5299 } else {
5300 None
5301 }
5302 });
5303 let new_bounds = bounds_deferred.expect("ChangeBounds deferred must be queued");
5304 let new_w = new_bounds.b.x - new_bounds.a.x;
5305 let new_h = new_bounds.b.y - new_bounds.a.y;
5306 assert_eq!(
5307 new_w, 79,
5308 "wide screen: width grows from 49 to 79 (grow 15)"
5309 );
5310 assert_eq!(new_h, 19, "height unchanged (y <= 34)");
5311 }
5312
5313 /// On a tall screen (> 34 rows) the resize formula fires `grow(0, 5)` —
5314 /// dialog height goes from 19 to 29. Width stays 49 (screen width = 64,
5315 /// neither > 90 nor > 63).
5316 #[test]
5317 fn file_dialog_screen_resize_tall_screen() {
5318 use crate::view::Point;
5319
5320 let mut fd = FileDialog::new("*.*", "T", "N", FD_NO_LOAD_DIR, 0);
5321 fd.dialog.state_mut().id = Some(crate::view::ViewId::next());
5322
5323 let mut out: VecDeque<Event> = VecDeque::new();
5324 let mut timers = crate::timer::TimerQueue::new();
5325 let mut deferred: Vec<Deferred> = vec![];
5326 {
5327 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5328 // owner_size = (64, 40): exactly on the x > 63 boundary AND y > 34.
5329 ctx.set_owner_size(Point::new(64, 40));
5330 let mut ev = crate::event::Event::Nothing;
5331 crate::view::View::handle_event(&mut fd, &mut ev, &mut ctx);
5332 }
5333
5334 let bounds_deferred = deferred.iter().find_map(|d| {
5335 if let Deferred::ChangeBounds(_, r) = d {
5336 Some(*r)
5337 } else {
5338 None
5339 }
5340 });
5341 let new_bounds = bounds_deferred.expect("ChangeBounds deferred must be queued");
5342 let new_h = new_bounds.b.y - new_bounds.a.y;
5343 assert_eq!(
5344 new_h, 29,
5345 "tall screen: height grows from 19 to 29 (grow 5)"
5346 );
5347 }
5348
5349 /// A second handle_event call does NOT re-queue a ChangeBounds — the resize
5350 /// fires exactly once.
5351 #[test]
5352 fn file_dialog_screen_resize_fires_once() {
5353 use crate::view::Point;
5354
5355 let mut fd = FileDialog::new("*.*", "T", "N", FD_NO_LOAD_DIR, 0);
5356 fd.dialog.state_mut().id = Some(crate::view::ViewId::next());
5357
5358 let dispatch = |fd: &mut FileDialog, deferred: &mut Vec<Deferred>| {
5359 let mut out: VecDeque<Event> = VecDeque::new();
5360 let mut timers = crate::timer::TimerQueue::new();
5361 let mut ctx = fl_make_ctx(&mut out, &mut timers, deferred);
5362 ctx.set_owner_size(Point::new(100, 25));
5363 let mut ev = crate::event::Event::Nothing;
5364 crate::view::View::handle_event(fd, &mut ev, &mut ctx);
5365 };
5366
5367 let mut deferred: Vec<Deferred> = vec![];
5368 dispatch(&mut fd, &mut deferred);
5369 let count_first: usize = deferred
5370 .iter()
5371 .filter(|d| matches!(d, Deferred::ChangeBounds(..)))
5372 .count();
5373 assert_eq!(count_first, 1, "exactly one ChangeBounds on first call");
5374
5375 deferred.clear();
5376 dispatch(&mut fd, &mut deferred);
5377 let count_second: usize = deferred
5378 .iter()
5379 .filter(|d| matches!(d, Deferred::ChangeBounds(..)))
5380 .count();
5381 assert_eq!(
5382 count_second, 0,
5383 "no ChangeBounds on second call (fires once)"
5384 );
5385 }
5386
5387 /// On a small screen (<= 63 wide, <= 25 tall) no resize fires: the dialog
5388 /// keeps its base 49×19 size.
5389 #[test]
5390 fn file_dialog_screen_resize_small_screen_no_change() {
5391 use crate::view::Point;
5392
5393 let mut fd = FileDialog::new("*.*", "T", "N", FD_NO_LOAD_DIR, 0);
5394 fd.dialog.state_mut().id = Some(crate::view::ViewId::next());
5395
5396 let mut out: VecDeque<Event> = VecDeque::new();
5397 let mut timers = crate::timer::TimerQueue::new();
5398 let mut deferred: Vec<Deferred> = vec![];
5399 {
5400 let mut ctx = fl_make_ctx(&mut out, &mut timers, &mut deferred);
5401 ctx.set_owner_size(Point::new(63, 25)); // at the boundary, not over
5402 let mut ev = crate::event::Event::Nothing;
5403 crate::view::View::handle_event(&mut fd, &mut ev, &mut ctx);
5404 }
5405
5406 // No ChangeBounds should be queued — the formula branches don't fire.
5407 let cb_count: usize = deferred
5408 .iter()
5409 .filter(|d| matches!(d, Deferred::ChangeBounds(..)))
5410 .count();
5411 assert_eq!(cb_count, 0, "small screen: no resize queued");
5412 }
5413
5414 // ---- finisher 3: SearchRec fs metadata ----------------------------------
5415
5416 /// `FileList::raw_from_fs` populates real size, mtime, and is_dir from the
5417 /// filesystem. This test creates a fixture directory with a known-size file
5418 /// and a subdirectory, then asserts the metadata is non-stub:
5419 /// - size > 0 for the regular file
5420 /// - time != 0 for the regular file (mtime present)
5421 /// - attr has FA_DIREC for the directory entry
5422 /// - attr is 0 for the file entry
5423 #[test]
5424 fn search_rec_metadata_populated_from_fixture_dir() {
5425 let tmp = std::env::temp_dir().join(format!("rstv_b6_searchrec_{}", std::process::id()));
5426 let _ = std::fs::remove_dir_all(&tmp);
5427 std::fs::create_dir_all(&tmp).unwrap();
5428 // Write a file with known content so size > 0.
5429 std::fs::write(tmp.join("hello.rs"), b"fn main() {}").unwrap();
5430 // Create a subdirectory.
5431 std::fs::create_dir_all(tmp.join("subdir")).unwrap();
5432 let dir = format!("{}/", tmp.to_string_lossy());
5433
5434 let raw = FileList::raw_from_fs(&dir);
5435 let _ = std::fs::remove_dir_all(&tmp);
5436
5437 // Find the file entry.
5438 let file_entry = raw
5439 .iter()
5440 .find(|(name, _, _, _)| name == "hello.rs")
5441 .expect("hello.rs must appear in the raw listing");
5442 let (_, is_dir_file, size, mtime) = file_entry;
5443 assert!(!is_dir_file, "hello.rs is not a directory");
5444 assert!(*size > 0, "file size must be > 0");
5445 assert!(
5446 mtime.is_some(),
5447 "mtime must be populated for a regular file"
5448 );
5449
5450 // Find the subdir entry.
5451 let dir_entry = raw
5452 .iter()
5453 .find(|(name, _, _, _)| name == "subdir")
5454 .expect("subdir must appear in the raw listing");
5455 let (_, is_dir_dir, _, _) = dir_entry;
5456 assert!(*is_dir_dir, "subdir must be flagged as a directory");
5457
5458 // Verify that build_listing correctly maps these to SearchRec attr/size/time.
5459 let recs = FileList::build_listing(&dir, "*.rs", &raw);
5460 let file_rec = recs
5461 .iter()
5462 .find(|r| r.name == "hello.rs")
5463 .expect("hello.rs must be in listing (matches *.rs)");
5464 assert_eq!(file_rec.attr, 0, "file attr must not have FA_DIREC");
5465 assert!(file_rec.size > 0, "file size propagated to SearchRec");
5466 assert_ne!(file_rec.time, 0, "time propagated to SearchRec (non-zero)");
5467
5468 let dir_rec = recs
5469 .iter()
5470 .find(|r| r.name == "subdir")
5471 .expect("subdir must be in listing (dirs always included)");
5472 assert_eq!(dir_rec.attr, FA_DIREC, "directory attr must be FA_DIREC");
5473 assert_eq!(dir_rec.size, 0, "directory size is 0 in listing");
5474 }
5475
5476 /// The TFileDialog 49×19 floor, reported through the delegated
5477 /// `size_limits` (the floor lives on the embedded window via
5478 /// `set_min_size`, not in an override). Catches a forgotten
5479 /// `set_min_size` in the constructor.
5480 #[test]
5481 fn file_dialog_size_limits_floor() {
5482 let fd = FileDialog::new("*.*", "Open a File", "~N~ame", 0, 100);
5483 let (min, max) = crate::view::View::size_limits(&fd, crate::view::Point::new(100, 40));
5484 assert_eq!(min, crate::view::Point::new(49, 19), "TFileDialog floor");
5485 assert_eq!(
5486 max,
5487 crate::view::Point::new(100, 40),
5488 "max is the owner size"
5489 );
5490 }
5491
5492 /// The TChDirDialog 48×18 floor, same mechanism.
5493 #[test]
5494 fn chdir_dialog_size_limits_floor() {
5495 let cd = ChDirDialog::new(0, 100);
5496 let (min, _) = crate::view::View::size_limits(&cd, crate::view::Point::new(100, 40));
5497 assert_eq!(min, crate::view::Point::new(48, 18), "TChDirDialog floor");
5498 }
5499}