Skip to main content

brep_app/panels/
file_explorer.rs

1//! Reusable, embeddable file explorer for the application's persistent store.
2//! It owns only transient browsing state; callers decide what activating a file
3//! means (open a document, choose a Save-As name, or insert an ACOMP part).
4//!
5//! Interaction model (matches a conventional file dialog): a single click
6//! anywhere on a row (name, type, size, date or blank space) selects it — the
7//! whole row highlights on hover and when selected; a double-click, the Enter
8//! key, or the footer confirm button *activates* it. Activating a FILE hands it
9//! to the caller; activating a FOLDER walks into it, so a single click on a
10//! folder only selects it. A left sidebar offers quick
11//! places + pinned folders, and the top bar is a clickable breadcrumb with an
12//! editable path and back / forward history — all driven through the
13//! [`ModelStore`] seam so web and native share one UI.
14//!
15//! The explorer never sizes itself: it FILLS the region its host hands it. A
16//! modal host wraps its whole body in [`dialog_body`], which puts one resize
17//! grip at the dialog window's bottom-right corner; a window host ([`egui::Window`])
18//! already has that grip. Either way the host's own trailing widgets go in a
19//! [`dialog_footer`] BEFORE the explorer, so they pin to the bottom and the
20//! file list is the only part that scrolls.
21
22use crate::automation::hit_keys::HitKeyDoc;
23use crate::store::{BrowserEntry, BrowserPlace, ModelStore, PlaceKind, PINNED_KEY};
24use eframe::egui;
25use egui_extras::{Column, TableBuilder};
26use std::cmp::Ordering;
27
28#[derive(Clone, Copy)]
29pub struct FileExplorerOptions<'a> {
30    pub hit_prefix: &'a str,
31    pub empty_label: &'a str,
32    pub row_icon: &'a str,
33    pub current: Option<&'a str>,
34    pub allow_delete: bool,
35    pub allow_import: bool,
36    pub import_label: &'a str,
37    pub import_hit: &'a str,
38    pub show_cancel: bool,
39    /// Footer primary/confirm button label (`"Open"` / `"Import"` / `"Insert"`).
40    /// `None` when the caller supplies its own action button and uses the
41    /// explorer only for navigation + name selection (Save As, step-parts
42    /// destination) — then keyboard confirm is disabled too, leaving Enter to
43    /// the caller's name field.
44    pub confirm_label: Option<&'a str>,
45    pub extensions: &'a [&'a str],
46}
47
48impl<'a> FileExplorerOptions<'a> {
49    pub fn open(current: Option<&'a str>) -> Self {
50        Self {
51            hit_prefix: "open",
52            empty_label: "(no saved models)",
53            row_icon: "\u{1F5CE}",
54            current,
55            allow_delete: true,
56            allow_import: false,
57            import_label: "Upload\u{2026}",
58            import_hit: "upload",
59            show_cancel: true,
60            confirm_label: Some("Open"),
61            extensions: crate::store::MODEL_EXTENSIONS,
62        }
63    }
64}
65
66/// The hit keys the EXPLORER publishes, documented beside the publisher
67/// (`automation::hit_keys`) rather than in each host panel: the widget set is
68/// the explorer's, only the `hit_prefix` is the host's, so one registration per
69/// prefix covers every key the shell can draw. A file ROW is keyed by its own
70/// displayed name (`open:bracket.nbrep`), which is what lets a script open
71/// a document through the modal the way a user does.
72///
73/// Until a script opened the modal these keys had never been published under
74/// `hit_keys_check`: every native script reached its document through
75/// `session_start`'s `document` or `document_open`, both of which bypass the
76/// interface entirely.
77pub static HIT_KEYS: &[HitKeyDoc] = &[
78    HitKeyDoc { panel: "file", prefix: "open:", meaning: "the Open modal's explorer: open:<file or folder name> (a row's name cell; one click selects, a double click opens the file or enters the folder), open:cell:<column>:<name> (the type, size or date cell of the same row, which selects it the same way), open:confirm, open:filter, open:back / forward / up, open:path-edit, open:path-edit-toggle, open:crumb:<i>, open:place:<label>, open:pin:<label>, open:unpin:<label>, open:pin-current, open:new-folder, open:new-folder-name, open:hidden-toggle, open:sort:<column>", command: Some("doc_load") },
79    HitKeyDoc { panel: "file", prefix: "import:", meaning: "the Import modal's explorer, same key set under the `import` prefix, plus import:upload", command: Some("doc_import") },
80    HitKeyDoc { panel: "file", prefix: "saveas:", meaning: "the Save As modal's destination explorer (saveas:file:<key>) and saveas:upload", command: Some("doc_json") },
81    HitKeyDoc { panel: "file", prefix: "insert:", meaning: "the Insert-component modal: insert:lib:<name> for a parts-library entry, insert:model:<key> for the store explorer, insert:upload", command: None },
82    HitKeyDoc { panel: "file", prefix: "del:", meaning: "delete the file on that explorer row (del:<file name>)", command: None },
83    HitKeyDoc { panel: "file", prefix: "upload", meaning: "the explorer's Upload… action where the platform has real-file interchange", command: None },
84    HitKeyDoc { panel: "stepparts", prefix: "steplib:dest:", meaning: "the parts-library destination explorer, the same key set under the `steplib:dest` prefix", command: None },
85];
86
87#[derive(Default)]
88pub struct FileExplorerOutput {
89    /// A file was CONFIRMED (double-click, Enter, or the footer confirm button):
90    /// the caller acts on it and closes the modal.
91    pub activated: Option<String>,
92    /// The file currently highlighted, persisting across frames until the
93    /// browser location changes. Mirrors the live selection for callers that
94    /// want it (and for the headed verifier). `None` when a directory or nothing
95    /// is selected.
96    pub selected: Option<String>,
97    /// A file row was single-clicked THIS frame — a one-shot event. Name-field
98    /// callers (Save As, step-parts) fill their field from it without clobbering
99    /// keystrokes the user makes afterwards.
100    pub picked: Option<String>,
101    pub remove: Option<String>,
102    pub import: bool,
103    pub cancel: bool,
104    pub hits: Vec<(String, egui::Rect)>,
105}
106
107/// Which column the file table is sorted by.
108#[derive(Clone, Copy, PartialEq, Eq, Default)]
109enum SortKey {
110    #[default]
111    Name,
112    Kind,
113    Size,
114    Date,
115}
116
117/// Embeddable browser state. The search text deliberately survives modal uses,
118/// making repeated Open / ACOMP operations retain the user's working filter.
119#[derive(Default)]
120pub struct FileExplorer {
121    query: String,
122    new_folder: String,
123    error: String,
124    /// The highlighted FILE identity. Persists across frames so the footer
125    /// confirm button and keyboard Enter have a stable target; cleared when the
126    /// browser location changes so a stale highlight never leaks into a
127    /// different directory. At most one of `selected` / `selected_dir` is set.
128    selected: Option<String>,
129    /// The highlighted FOLDER identity: one click on a folder row selects it,
130    /// and only a double click, Enter or the footer confirm walks into it. Kept
131    /// apart from `selected` so no caller ever receives a folder as a file
132    /// choice (`selected()`, `picked`, `activated` are files only).
133    selected_dir: Option<String>,
134    /// A folder activated THIS frame. Entered at the end of
135    /// [`Self::show_store`], after every widget has drawn from this frame's
136    /// listing, so the footer and the table never disagree about the location.
137    enter_dir: Option<String>,
138    /// The location `selected` belongs to — a mismatch means we walked into
139    /// another directory and must drop the highlight.
140    selected_at: String,
141    /// Visited-location back / forward stacks for the nav buttons.
142    history: Vec<String>,
143    forward: Vec<String>,
144    /// `Some` while the breadcrumb is swapped for an editable path field.
145    editing_path: Option<String>,
146    /// Grab focus for the path field on the frame it appears.
147    path_focus: bool,
148    /// The visible rows (identity, is-folder) in display order — the
149    /// keyboard-nav target set, refreshed every frame by [`Self::show_list`].
150    nav_rows: Vec<(String, bool)>,
151    /// Which column the file table sorts by, and its direction (`false` = asc).
152    sort_key: SortKey,
153    sort_desc: bool,
154    /// Show dotfile / hidden entries in the list. Off by default; toggling it on
155    /// never affects navigation — a hidden path can always be entered directly.
156    show_hidden: bool,
157}
158
159impl FileExplorer {
160    pub fn new() -> Self {
161        Self::default()
162    }
163
164    /// The file identity currently highlighted (for the headed verifier and any
165    /// caller mirroring the selection). `None` when nothing / a directory holds
166    /// the highlight.
167    pub fn selected(&self) -> Option<&str> {
168        self.selected.as_deref()
169    }
170
171    /// Drop the file highlight. The host calls it when the explorer is shown for
172    /// another PURPOSE: one explorer serves Import, Insert component and Open in
173    /// the same folder, and a file highlighted for one of them is not a choice
174    /// made for the next. Without it a `.kicad_sym` picked in Import was still
175    /// Insert component's footer choice, and Insert sent it to the parts library.
176    pub fn clear_selection(&mut self) {
177        self.selected = None;
178        self.selected_dir = None;
179    }
180
181    /// The folder identity currently highlighted (for the verifier), `None`
182    /// when a file or nothing holds the highlight.
183    pub fn selected_folder(&self) -> Option<&str> {
184        self.selected_dir.as_deref()
185    }
186
187    /// Highlight a row: a file becomes the file selection, a folder the folder
188    /// selection, and either one drops the other.
189    fn select(&mut self, identity: &str, is_dir: bool) {
190        if is_dir {
191            self.selected = None;
192            self.selected_dir = Some(identity.to_string());
193        } else {
194            self.selected_dir = None;
195            self.selected = Some(identity.to_string());
196        }
197    }
198
199    /// Activate a row: a file is confirmed to the caller, a folder is entered
200    /// at the end of the frame.
201    fn activate(&mut self, identity: &str, is_dir: bool, out: &mut FileExplorerOutput) {
202        self.select(identity, is_dir);
203        if is_dir {
204            self.enter_dir = Some(identity.to_string());
205        } else {
206            out.activated = Some(identity.to_string());
207        }
208    }
209
210    /// Browse the model entries exposed by a platform [`ModelStore`].
211    pub fn show_store(
212        &mut self,
213        ui: &mut egui::Ui,
214        store: &dyn ModelStore,
215        options: FileExplorerOptions<'_>,
216    ) -> FileExplorerOutput {
217        let entries = store.browser_entries(options.extensions);
218        let location = store.browser_location();
219        if location != self.selected_at {
220            self.selected = None;
221            self.selected_dir = None;
222            self.selected_at = location.clone();
223        }
224        let places = store.browser_places();
225        let pins = Self::read_pins(store);
226        let mut out = FileExplorerOutput::default();
227
228        let selected_before = (self.selected.clone(), self.selected_dir.clone());
229        let compact = crate::viewport::touch::compact(ui.ctx());
230        if compact {
231            ui.horizontal_wrapped(|ui| {
232                let places_menu = ui.menu_button("Places", |ui| {
233                    ui.set_height((ui.ctx().content_rect().height() - 100.0).clamp(80.0, 300.0));
234                    self.show_sidebar(ui, store, &places, &pins, &location, options, &mut out);
235                });
236                out.hits.push((format!("{}:places-menu", options.hit_prefix), places_menu.response.rect));
237                let up = ui.add(egui::Button::new("Up").min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
238                out.hits.push((format!("{}:up", options.hit_prefix), up.rect));
239                if up.clicked() { self.nav(store, || store.browser_up()); }
240                let folder = ui.menu_button("Folder", |ui| {
241                    self.show_nav_bar(ui, store, &location, options, &mut out);
242                    let hidden = ui.checkbox(&mut self.show_hidden, "Show hidden files");
243                    out.hits.push((format!("{}:hidden-toggle", options.hit_prefix), hidden.rect));
244                });
245                out.hits.push((format!("{}:folder-menu", options.hit_prefix), folder.response.rect));
246                let filter_width = ui.available_width().clamp(60.0, 150.0);
247                let filter = ui.add(egui::TextEdit::singleline(&mut self.query).margin(crate::viewport::touch::text_edit_margin(ui)).hint_text("Filter files")
248                    .desired_width(filter_width).min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
249                out.hits.push((format!("{}:filter", options.hit_prefix), filter.rect));
250            });
251        } else { self.show_nav_bar(ui, store, &location, options, &mut out); }
252        if !self.error.is_empty() {
253            ui.colored_label(ui.visuals().error_fg_color, &self.error);
254        }
255        ui.add_space(2.0);
256        ui.separator();
257
258        // The explorer FILLS the region its host gave it — a modal's resizable
259        // body ([`dialog_body`]), a window's content — rather than carrying a
260        // resize handle of its own around the file table: the footer pins to the
261        // bottom (under anything the host already pinned there) and the browse
262        // area takes every pixel between it and the nav bar, so the file list is
263        // the only thing that scrolls.
264        bottom_panel(ui, "brep-file-explorer-footer", options.hit_prefix, |ui| {
265            self.show_footer(ui, options, &mut out)
266        });
267        if compact {
268            self.show_list(ui, &entries, options, &mut out);
269        } else { ui.horizontal_top(|ui| {
270            if !places.is_empty() {
271                ui.vertical(|ui| {
272                    self.show_sidebar(ui, store, &places, &pins, &location, options, &mut out);
273                });
274                ui.separator();
275            }
276            ui.vertical(|ui| {
277                self.show_list(ui, &entries, options, &mut out);
278            });
279        }); }
280
281        self.handle_keys(ui, options, &mut out);
282        // A folder activated this frame (double click, Enter, footer confirm)
283        // is entered only now, after the listing drew from the old location.
284        if let Some(dir) = self.enter_dir.take() {
285            self.nav(store, || store.browser_enter(&dir));
286            ui.ctx().request_repaint();
287        }
288        out.selected = self.selected.clone();
289        // The footer (and any host footer: a name field, a confirm button) was
290        // drawn BEFORE the row that just changed the highlight, so it is showing
291        // last frame's selection. Ask for one more frame rather than leaving a
292        // confirm button greyed out until the pointer happens to move again.
293        if out.picked.is_some() || (self.selected.clone(), self.selected_dir.clone()) != selected_before {
294            ui.ctx().request_repaint();
295        }
296        out
297    }
298
299    // --- navigation with history ---------------------------------------------
300
301    /// Run a navigation action and, when it actually changes location, record the
302    /// previous location on the back stack (clearing the forward stack) and drop
303    /// the file highlight. Shared by up / breadcrumb / place / enter-directory.
304    fn nav<F: FnOnce() -> Result<(), String>>(&mut self, store: &dyn ModelStore, action: F) {
305        let before = store.browser_location();
306        match action() {
307            Ok(()) => {
308                let after = store.browser_location();
309                if after != before {
310                    self.history.push(before);
311                    self.forward.clear();
312                }
313                self.error.clear();
314                self.selected = None;
315                self.selected_dir = None;
316            }
317            Err(error) => self.error = error,
318        }
319    }
320
321    /// Step back to the previous location, remembering the current one for
322    /// forward. A failed navigate restores the stack unchanged.
323    fn back(&mut self, store: &dyn ModelStore) {
324        if let Some(prev) = self.history.pop() {
325            let current = store.browser_location();
326            if store.browser_navigate(&prev).is_ok() {
327                self.forward.push(current);
328                self.selected = None;
329                self.selected_dir = None;
330                self.error.clear();
331            } else {
332                self.history.push(prev);
333            }
334        }
335    }
336
337    fn forward_go(&mut self, store: &dyn ModelStore) {
338        if let Some(next) = self.forward.pop() {
339            let current = store.browser_location();
340            if store.browser_navigate(&next).is_ok() {
341                self.history.push(current);
342                self.selected = None;
343                self.selected_dir = None;
344                self.error.clear();
345            } else {
346                self.forward.push(next);
347            }
348        }
349    }
350
351    // --- top navigation bar: back/forward/up + breadcrumb + new folder --------
352
353    fn show_nav_bar(
354        &mut self,
355        ui: &mut egui::Ui,
356        store: &dyn ModelStore,
357        location: &str,
358        options: FileExplorerOptions<'_>,
359        out: &mut FileExplorerOutput,
360    ) {
361        ui.horizontal(|ui| {
362            let back = ui.add_enabled(!self.history.is_empty(), egui::Button::new("\u{25C0}").small()
363                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
364            out.hits.push((format!("{}:back", options.hit_prefix), back.rect));
365            if back.clicked() {
366                self.back(store);
367            }
368            let fwd = {
369            let b = crate::icon_text::icon_button(ui, "\u{25B6}").small()
370                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO));
371            ui.add_enabled(!self.forward.is_empty(), b)
372        };
373            out.hits.push((format!("{}:forward", options.hit_prefix), fwd.rect));
374            if fwd.clicked() {
375                self.forward_go(store);
376            }
377            let up = ui.add(egui::Button::new("\u{2191}").small()
378                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
379            out.hits.push((format!("{}:up", options.hit_prefix), up.rect));
380            if up.clicked() {
381                self.nav(store, || store.browser_up());
382            }
383            ui.separator();
384            self.show_breadcrumb(ui, store, location, options, out);
385        });
386        ui.horizontal(|ui| {
387            let create = ui.add(egui::Button::new("+ Folder").small()
388                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
389            out.hits
390                .push((format!("{}:new-folder", options.hit_prefix), create.rect));
391            let field = ui.add(
392                egui::TextEdit::singleline(&mut self.new_folder).margin(crate::viewport::touch::text_edit_margin(ui))
393                    .hint_text("New folder")
394                    .desired_width(140.0)
395                    .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)),
396            );
397            out.hits
398                .push((format!("{}:new-folder-name", options.hit_prefix), field.rect));
399            let submit = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
400            if (create.clicked() || submit) && !self.new_folder.trim().is_empty() {
401                match store.browser_create_dir(self.new_folder.trim()) {
402                    Ok(()) => {
403                        self.new_folder.clear();
404                        self.error.clear();
405                    }
406                    Err(error) => self.error = error,
407                }
408            }
409        });
410    }
411
412    /// Either a clickable breadcrumb (each ancestor navigates) with a pencil
413    /// toggle, or — while editing — a path field that navigates on Enter.
414    fn show_breadcrumb(
415        &mut self,
416        ui: &mut egui::Ui,
417        store: &dyn ModelStore,
418        location: &str,
419        options: FileExplorerOptions<'_>,
420        out: &mut FileExplorerOutput,
421    ) {
422        if self.editing_path.is_some() {
423            let mut buf = self.editing_path.take().unwrap();
424            let resp = ui.add(
425                egui::TextEdit::singleline(&mut buf).margin(crate::viewport::touch::text_edit_margin(ui))
426                    .hint_text("type a path, Enter to go")
427                    .desired_width(300.0),
428            );
429            out.hits
430                .push((format!("{}:path-edit", options.hit_prefix), resp.rect));
431            if self.path_focus {
432                resp.request_focus();
433                self.path_focus = false;
434            }
435            let go = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
436            if go {
437                self.nav(store, || store.browser_navigate(&buf));
438            } else if !resp.lost_focus() {
439                self.editing_path = Some(buf); // still editing
440            }
441            // lost focus without Enter → cancel (editing_path stays None)
442            return;
443        }
444        // The pencil comes FIRST, outside the crumbs' scroll area: at the end of
445        // a long path it sat past the dialog's right edge (x = 1910 in a
446        // 1400-wide window), where no one could press it.
447        let edit = ui.add(crate::icon_text::icon_button(ui, "\u{270E}").small()
448            .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO))); // ✎
449        out.hits
450            .push((format!("{}:path-edit-toggle", options.hit_prefix), edit.rect));
451        if edit.on_hover_text("Type a path").clicked() {
452            self.editing_path = Some(location.to_string());
453            self.path_focus = true;
454        }
455        let avail = ui.available_width();
456        egui::ScrollArea::horizontal()
457            .id_salt(format!("{}-crumbs", options.hit_prefix))
458            .max_width(avail)
459            // Fill the row width (so a long path scrolls horizontally) but shrink
460            // to ONE row's height — `false` here would balloon vertically to the
461            // modal's huge available height and push the dialog off-screen.
462            .auto_shrink([false, true])
463            // The folder you are IN is the crumb that matters: a long path shows
464            // its tail, and scrolls back to its root.
465            .stick_to_right(true)
466            .show(ui, |ui| {
467                ui.horizontal(|ui| {
468                    for (i, (label, path)) in breadcrumb_segments(location).into_iter().enumerate() {
469                        if i > 0 {
470                            ui.weak("\u{203A}"); // ›
471                        }
472                        let seg = ui.add(egui::Button::new(label).frame(false).small()
473                            .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
474                        out.hits
475                            .push((format!("{}:crumb:{i}", options.hit_prefix), seg.rect));
476                        if seg.clicked() {
477                            self.nav(store, || store.browser_navigate(&path));
478                        }
479                    }
480                });
481            });
482    }
483
484    // --- left sidebar: places + pinned folders --------------------------------
485
486    #[allow(clippy::too_many_arguments)]
487    fn show_sidebar(
488        &mut self,
489        ui: &mut egui::Ui,
490        store: &dyn ModelStore,
491        places: &[BrowserPlace],
492        pins: &[String],
493        location: &str,
494        options: FileExplorerOptions<'_>,
495        out: &mut FileExplorerOutput,
496    ) {
497        ui.set_min_width(132.0);
498        ui.set_max_width(152.0);
499        egui::ScrollArea::vertical()
500            .id_salt(format!("{}-sidebar", options.hit_prefix))
501            .auto_shrink([false, false])
502            .show(ui, |ui| {
503                ui.weak("Places");
504                for place in places {
505                    let caption = format!("{} {}", place_glyph(place.kind), place.label);
506                    let resp = ui.add(sidebar_row(ui, &caption));
507                    out.hits
508                        .push((format!("{}:place:{}", options.hit_prefix, place.label), resp.rect));
509                    if resp.clicked() {
510                        let loc = place.location.clone();
511                        self.nav(store, || store.browser_navigate(&loc));
512                    }
513                }
514                if !pins.is_empty() {
515                    ui.add_space(6.0);
516                    ui.weak("Pinned");
517                    for pin in pins {
518                        ui.horizontal(|ui| {
519                            let label = pin.rsplit(['/', '\\']).find(|s| !s.is_empty()).unwrap_or(pin);
520                            let caption = format!("{PIN_GLYPH} {label}");
521                            let resp = ui.add(sidebar_row(ui, &caption));
522                            out.hits
523                                .push((format!("{}:pin:{label}", options.hit_prefix), resp.rect));
524                            if resp.clicked() {
525                                let loc = pin.clone();
526                                self.nav(store, || store.browser_navigate(&loc));
527                            }
528                            let x = {
529                                let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
530                                ui.add(b)
531                            };
532                            out.hits
533                                .push((format!("{}:unpin:{label}", options.hit_prefix), x.rect));
534                            if x.clicked() {
535                                Self::set_pin(store, pin, false);
536                            }
537                        });
538                    }
539                }
540                ui.add_space(6.0);
541                let pinned_now = pins.iter().any(|p| p == location);
542                let label = if pinned_now { "\u{2715} Unpin folder" } else { "Pin folder" };
543                let btn = ui.add(crate::icon_text::icon_button(ui, label).small());
544                out.hits
545                    .push((format!("{}:pin-current", options.hit_prefix), btn.rect));
546                if btn.clicked() {
547                    Self::set_pin(store, location, !pinned_now);
548                }
549            });
550    }
551
552    /// Read the pinned-locations list (a JSON array under the reserved key).
553    fn read_pins(store: &dyn ModelStore) -> Vec<String> {
554        store
555            .read(PINNED_KEY)
556            .and_then(|raw| serde_json::from_str::<Vec<String>>(&raw).ok())
557            .unwrap_or_default()
558    }
559
560    /// Add or remove `location` from the pinned list, persisting the result.
561    fn set_pin(store: &dyn ModelStore, location: &str, want: bool) {
562        let mut pins = Self::read_pins(store);
563        let has = pins.iter().any(|p| p == location);
564        if want && !has {
565            pins.push(location.to_string());
566        } else if !want && has {
567            pins.retain(|p| p != location);
568        } else {
569            return;
570        }
571        let _ = store.write(
572            PINNED_KEY,
573            &serde_json::to_string(&pins).unwrap_or_else(|_| "[]".into()),
574        );
575    }
576
577    // --- central file list ----------------------------------------------------
578
579    fn show_list(
580        &mut self,
581        ui: &mut egui::Ui,
582        entries: &[BrowserEntry],
583        options: FileExplorerOptions<'_>,
584        out: &mut FileExplorerOutput,
585    ) {
586        // Header row: hidden toggle (left) + filter (right).
587        if !crate::viewport::touch::compact(ui.ctx()) { ui.horizontal(|ui| {
588            let hidden = ui.checkbox(&mut self.show_hidden, "Hidden");
589            out.hits
590                .push((format!("{}:hidden-toggle", options.hit_prefix), hidden.rect));
591            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
592                let search = ui.add(
593                    egui::TextEdit::singleline(&mut self.query).margin(crate::viewport::touch::text_edit_margin(ui))
594                        .hint_text("Filter files")
595                        .desired_width(150.0),
596                );
597                out.hits
598                    .push((format!("{}:filter", options.hit_prefix), search.rect));
599            });
600        }); }
601
602        let query = self.query.trim().to_ascii_lowercase();
603        // Each name lowercased ONCE, for the filter and the sort: lowercasing
604        // both names in every comparison was ~130,000 allocations a frame for
605        // a 5,000-part PLM folder, while the dialog sat open.
606        let mut named: Vec<(String, &BrowserEntry)> = entries
607            .iter()
608            .filter_map(|entry| {
609                // Dotfiles hide unless toggled on; the filter box applies to files.
610                let hidden = entry.name.starts_with('.');
611                let lower = entry.name.to_ascii_lowercase();
612                ((self.show_hidden || !hidden) && (entry.is_dir || query.is_empty() || lower.contains(&query))).then_some((lower, entry))
613            })
614            .collect();
615        // Directories always first; within each group, by the active column.
616        let (key, desc) = (self.sort_key, self.sort_desc);
617        named.sort_by(|(a_name, a), (b_name, b)| {
618            b.is_dir.cmp(&a.is_dir).then_with(|| {
619                let by_name = || a_name.cmp(b_name);
620                let ord = match key {
621                    SortKey::Name => by_name(),
622                    SortKey::Kind => entry_kind(a).cmp(&entry_kind(b)).then_with(by_name),
623                    SortKey::Size => a.size.unwrap_or(0).cmp(&b.size.unwrap_or(0)).then_with(by_name),
624                    SortKey::Date => cmp_opt(a.modified, b.modified).then_with(by_name),
625                };
626                if desc { ord.reverse() } else { ord }
627            })
628        });
629        let visible: Vec<&BrowserEntry> = named.into_iter().map(|(_, entry)| entry).collect();
630        self.nav_rows = visible
631            .iter()
632            .map(|entry| (entry.identity.clone(), entry.is_dir))
633            .collect();
634
635        if visible.is_empty() {
636            ui.separator();
637            ui.weak(options.empty_label);
638            return;
639        }
640
641        if crate::viewport::touch::compact(ui.ctx()) {
642            let sort = ui.menu_button("Sort", |ui| {
643                for (label, key) in [("Name", SortKey::Name), ("Type", SortKey::Kind), ("Size", SortKey::Size), ("Date", SortKey::Date)] {
644                    if ui.selectable_label(self.sort_key == key, label).clicked() {
645                        if self.sort_key == key { self.sort_desc = !self.sort_desc; }
646                        else { self.sort_key = key; self.sort_desc = false; }
647                        ui.close();
648                    }
649                }
650            });
651            out.hits.push((format!("{}:sort-menu", options.hit_prefix), sort.response.rect));
652            let row_h = crate::viewport::touch::target_size(ui.ctx(), egui::vec2(0.0, egui::TextStyle::Body.resolve(ui.style()).size + 6.0)).y;
653            egui::ScrollArea::vertical().id_salt(format!("{}-compact-list", options.hit_prefix)).show(ui, |ui| {
654                for entry in visible {
655                    ui.horizontal(|ui| {
656                        let icon = if entry.is_dir { "\u{1F5C0}" } else { options.row_icon };
657                        let highlight = self.row_highlight(entry, options.current);
658                        let deletable = options.allow_delete && !entry.is_dir;
659                        let width = (ui.available_width() - if deletable { 44.0 + ui.spacing().item_spacing.x } else { 0.0 }).max(44.0);
660                        let text = format!("{icon} {}", entry.name);
661                        let r = ui.add_sized([width, row_h], crate::icon_text::icon_button(ui, &text).selected(highlight).truncate());
662                        out.hits.push((format!("{}:{}", options.hit_prefix, entry.name), r.rect));
663                        self.row_clicked(&r, entry, out);
664                        if deletable {
665                            let delete = ui.add(crate::icon_text::icon_button(ui, "\u{2715}").small()
666                                .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
667                            out.hits.push((format!("del:{}", entry.name), delete.rect));
668                            if delete.clicked() { out.remove = Some(entry.identity.clone()); }
669                        }
670                    });
671                }
672            });
673            return;
674        }
675
676        // The PRIMARY layout: a sortable Name / Type / Size / Date table whose
677        // body scrolls inside the height the host left us. Header cells toggle
678        // the sort.
679        let row_h = egui::TextStyle::Body.resolve(ui.style()).size + 6.0;
680        let mut clicked_sort: Option<SortKey> = None;
681        // The WHOLE ROW is the click target: every cell senses clicks and the
682        // row's union response selects / activates. Only the delete button is
683        // interactive on top of it, so it keeps its own click. Labels must not
684        // be text-selectable here, or a selectable label would take the click
685        // (egui's default `selectable_labels` senses click-and-drag).
686        ui.scope(|ui| {
687        ui.style_mut().interaction.selectable_labels = false;
688        TableBuilder::new(ui)
689            .id_salt(format!("{}-table", options.hit_prefix))
690            .striped(true)
691            .sense(egui::Sense::click())
692            .cell_layout(egui::Layout::left_to_right(egui::Align::Center))
693            .column(Column::remainder().at_least(150.0).clip(true)) // Name
694            .column(Column::auto().at_least(72.0)) // Type
695            .column(Column::auto().at_least(66.0)) // Size
696            .column(Column::auto().at_least(120.0)) // Date
697            .column(Column::auto().at_least(20.0)) // delete
698            .header(row_h, |mut header| {
699                for (label, col) in [
700                    ("Name", SortKey::Name),
701                    ("Type", SortKey::Kind),
702                    ("Size", SortKey::Size),
703                    ("Date", SortKey::Date),
704                ] {
705                    header.col(|ui| {
706                        let arrow = if key == col {
707                            if desc {
708                                " \u{25BE}"
709                            } else {
710                                " \u{25B4}"
711                            }
712                        } else {
713                            ""
714                        };
715                        let btn =
716                            ui.add(egui::Button::new(format!("{label}{arrow}")).frame(false));
717                        out.hits.push((
718                            format!("{}:sort:{}", options.hit_prefix, sort_slug(col)),
719                            btn.rect,
720                        ));
721                        if btn.clicked() {
722                            clicked_sort = Some(col);
723                        }
724                    });
725                }
726                header.col(|_ui| {});
727            })
728            .body(|body| {
729                body.rows(row_h, visible.len(), |mut row| {
730                    let entry = visible[row.index()];
731                    let icon = if entry.is_dir {
732                        "\u{1F5C0}"
733                    } else {
734                        options.row_icon
735                    };
736                    row.set_selected(self.row_highlight(entry, options.current));
737                    let prefix = options.hit_prefix;
738                    let (name_rect, _) = row.col(|ui| {
739                        crate::icon_text::IconText::new(format!("{icon} {}", entry.name))
740                            .selectable(false)
741                            .truncate()
742                            .show(ui);
743                    });
744                    out.hits.push((format!("{prefix}:{}", entry.name), name_rect));
745                    let cells = [
746                        ("type", entry_kind(entry)),
747                        ("size", fmt_size(entry.size)),
748                        ("date", fmt_date(entry.modified)),
749                    ];
750                    for (slug, text) in cells {
751                        let (rect, _) = row.col(|ui| {
752                            ui.add(egui::Label::new(egui::RichText::new(text).weak()).selectable(false));
753                        });
754                        out.hits.push((format!("{prefix}:cell:{slug}:{}", entry.name), rect));
755                    }
756                    // The row's click is read BEFORE the delete cell joins the
757                    // union: a click on the delete button is the button's alone.
758                    let clicked_row = row.response();
759                    row.col(|ui| {
760                        if options.allow_delete && !entry.is_dir {
761                            let del = {
762                                let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
763                                ui.add(b)
764                            };
765                            out.hits.push((format!("del:{}", entry.name), del.rect));
766                            if del.clicked() {
767                                out.remove = Some(entry.identity.clone());
768                            }
769                        }
770                    });
771                    self.row_clicked(&clicked_row, entry, out);
772                });
773            });
774        });
775        if let Some(col) = clicked_sort {
776            if self.sort_key == col {
777                self.sort_desc = !self.sort_desc;
778            } else {
779                self.sort_key = col;
780                self.sort_desc = false;
781            }
782        }
783    }
784
785    /// Whether `entry`'s row shows highlighted: the selected file or folder;
786    /// before the user picks a row, the caller's `current` document.
787    fn row_highlight(&self, entry: &BrowserEntry, current: Option<&str>) -> bool {
788        let id = entry.identity.as_str();
789        if entry.is_dir {
790            self.selected_dir.as_deref() == Some(id)
791        } else {
792            match &self.selected {
793                Some(sel) => sel == id,
794                None => self.selected_dir.is_none() && current == Some(id),
795            }
796        }
797    }
798
799    /// A row's click: a double click activates (opens a file, enters a
800    /// folder), a single click only selects. The double-click test comes
801    /// first because its second press also reports `clicked()`.
802    fn row_clicked(&mut self, response: &egui::Response, entry: &BrowserEntry, out: &mut FileExplorerOutput) {
803        if response.double_clicked() {
804            self.activate(&entry.identity, entry.is_dir, out);
805        } else if response.clicked() {
806            self.select(&entry.identity, entry.is_dir);
807            if !entry.is_dir {
808                out.picked = Some(entry.identity.clone());
809            }
810        }
811    }
812
813    /// Keyboard navigation over the visible rows: ↑/↓ move the selection
814    /// (folders and files alike), Enter activates it (opens the file, enters
815    /// the folder). Active only when the caller offers a confirm action and no
816    /// text field (filter / name / path) holds focus, so typing is never
817    /// hijacked. Not in hosts without one (Save As, step-parts): their name
818    /// field submits on Enter as it loses focus, the same frame this would see
819    /// the key, and an explorer Enter there would overwrite the typed name or
820    /// walk into a folder before the save.
821    fn handle_keys(
822        &mut self,
823        ui: &egui::Ui,
824        options: FileExplorerOptions<'_>,
825        out: &mut FileExplorerOutput,
826    ) {
827        if options.confirm_label.is_none() || ui.ctx().egui_wants_keyboard_input() {
828            return;
829        }
830        if self.nav_rows.is_empty() {
831            return;
832        }
833        let (down, up, enter) = ui.input(|i| {
834            (
835                i.key_pressed(egui::Key::ArrowDown),
836                i.key_pressed(egui::Key::ArrowUp),
837                i.key_pressed(egui::Key::Enter),
838            )
839        });
840        if down || up {
841            let held = self.selected.as_deref().or(self.selected_dir.as_deref());
842            let current = held.and_then(|s| self.nav_rows.iter().position(|(id, _)| id == s));
843            let next = match current {
844                Some(i) if down => (i + 1).min(self.nav_rows.len() - 1),
845                Some(i) => i.saturating_sub(1),
846                None => 0,
847            };
848            let (id, is_dir) = self.nav_rows[next].clone();
849            self.select(&id, is_dir);
850            if !is_dir {
851                out.picked = Some(id);
852            }
853        } else if enter {
854            if let Some(dir) = self.selected_dir.clone() {
855                self.enter_dir = Some(dir);
856            } else if let Some(sel) = &self.selected {
857                out.activated = Some(sel.clone());
858            }
859        }
860    }
861
862    fn show_footer(
863        &mut self,
864        ui: &mut egui::Ui,
865        options: FileExplorerOptions<'_>,
866        out: &mut FileExplorerOutput,
867    ) {
868        ui.separator();
869        ui.horizontal(|ui| {
870            if let Some(label) = options.confirm_label {
871                let any = self.selected.is_some() || self.selected_dir.is_some();
872                let confirm = ui.add_enabled(any, egui::Button::new(label));
873                out.hits
874                    .push((format!("{}:confirm", options.hit_prefix), confirm.rect));
875                if confirm.clicked() {
876                    // With a folder selected the confirm button walks into it.
877                    if let Some(dir) = self.selected_dir.clone() {
878                        self.enter_dir = Some(dir);
879                    } else {
880                        out.activated = self.selected.clone();
881                    }
882                }
883            }
884            if options.allow_import {
885                let import = {
886                let label = format!("\u{2B06} {}", options.import_label);
887                let b = crate::icon_text::icon_button(ui, &label);
888                ui.add(b)
889            };
890                out.hits.push((options.import_hit.into(), import.rect));
891                out.import = import.clicked();
892            }
893            if options.show_cancel {
894                let cancel = ui.button("Cancel");
895                out.hits.push(("cancel".into(), cancel.rect));
896                out.cancel = cancel.clicked();
897            }
898            // Selection preview (bare file name), right-aligned.
899            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
900                if let Some(sel) = self.selected.as_ref().or(self.selected_dir.as_ref()) {
901                    let name = sel.rsplit(['/', '\\']).next().unwrap_or(sel);
902                    // Truncated: the preview is the LAST thing on the footer row,
903                    // so a long file name laid out at its natural width runs left
904                    // across the Import / Cancel buttons it is meant to sit beside.
905                    ui.add(
906                        egui::Label::new(egui::RichText::new(name).weak()).truncate(),
907                    );
908                }
909            });
910        });
911    }
912
913}
914
915/// Wrap a file dialog's WHOLE body — heading, browser, footer and all — in the
916/// shared resizable frame. The drag grip therefore lands at the dialog WINDOW's
917/// bottom-right corner instead of around the file table, and dragging it grows
918/// the dialog itself in both axes, capped to the viewport so it can never grow
919/// off-screen. One shared id means resizing any file dialog resizes them all.
920///
921/// Only for MODAL hosts: an [`egui::Window`] already carries its own corner
922/// grip, and a second frame inside it would put back exactly the handle this
923/// removes.
924pub fn dialog_body<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
925    let screen = ui.ctx().content_rect().size();
926    let compact = crate::viewport::touch::compact(ui.ctx());
927    let max = if compact { (screen - egui::Vec2::splat(24.0)).max(egui::Vec2::splat(80.0)) }
928        else { egui::vec2((screen.x - 40.0).max(320.0), (screen.y - 80.0).max(240.0)) };
929    egui::Resize::default()
930        .id_salt(if compact { "brep-file-dialog-size-mobile" } else { "brep-file-dialog-size" })
931        // The modal frame already draws the dialog's border; the resize region
932        // fills it exactly, so its own stroke would only double it up.
933        .with_stroke(false)
934        .min_size(egui::vec2(460.0_f32.min(max.x), 300.0_f32.min(max.y)))
935        .max_size(max)
936        .default_size(egui::vec2(620.0_f32.min(max.x), 520.0_f32.min(max.y)))
937        .show(ui, add_contents)
938}
939
940/// Pin a dialog's own trailing widgets — a status line, a name field, the
941/// action buttons — to the BOTTOM of the dialog. Call it BEFORE
942/// [`FileExplorer::show_store`]: the explorer then fills the gap that is left,
943/// which is what keeps the buttons still while the file list scrolls. `salt`
944/// distinguishes one dialog's footer from another's (two can be on screen at
945/// once), and the widgets inside are drawn top-down in the order written.
946pub fn dialog_footer<R>(
947    ui: &mut egui::Ui,
948    salt: &str,
949    add_contents: impl FnOnce(&mut egui::Ui) -> R,
950) -> R {
951    bottom_panel(ui, "brep-file-dialog-footer", salt, add_contents)
952}
953
954/// The one bottom-pinned strip both footers use: no frame and no separator line
955/// of its own, so it reads as part of the dialog rather than as a panel, and it
956/// takes exactly the height its contents need.
957fn bottom_panel<R>(
958    ui: &mut egui::Ui,
959    base: &str,
960    salt: &str,
961    add_contents: impl FnOnce(&mut egui::Ui) -> R,
962) -> R {
963    egui::containers::panel::Panel::bottom(egui::Id::new((base, salt)))
964        .frame(egui::Frame::NONE)
965        .show_separator_line(false)
966        .show(ui, add_contents)
967        .inner
968}
969
970/// Order two optional timestamps, sorting `None` (unknown, e.g. web) last.
971fn cmp_opt(a: Option<f64>, b: Option<f64>) -> Ordering {
972    match (a, b) {
973        (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal),
974        (Some(_), None) => Ordering::Less,
975        (None, Some(_)) => Ordering::Greater,
976        (None, None) => Ordering::Equal,
977    }
978}
979
980/// The Type column text for an entry (Folder / BREP model / extension / File).
981fn entry_kind(entry: &BrowserEntry) -> String {
982    if entry.is_dir {
983        return "Folder".into();
984    }
985    let lower = entry.name.to_ascii_lowercase();
986    if lower.ends_with(".nbrep") {
987        return "BREP model".into();
988    }
989    match entry.name.rsplit_once('.') {
990        Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => ext.to_uppercase(),
991        _ => "File".into(),
992    }
993}
994
995/// Stable slug for a sort column's hit key.
996fn sort_slug(key: SortKey) -> &'static str {
997    match key {
998        SortKey::Name => "name",
999        SortKey::Kind => "type",
1000        SortKey::Size => "size",
1001        SortKey::Date => "date",
1002    }
1003}
1004
1005/// Human-readable byte size, or an em-dash when the backend cannot report it.
1006fn fmt_size(size: Option<u64>) -> String {
1007    match size {
1008        None => "\u{2014}".into(),
1009        Some(bytes) => {
1010            let b = bytes as f64;
1011            if bytes < 1024 {
1012                format!("{bytes} B")
1013            } else if b < 1024.0 * 1024.0 {
1014                format!("{:.1} KB", b / 1024.0)
1015            } else if b < 1024.0 * 1024.0 * 1024.0 {
1016                format!("{:.1} MB", b / (1024.0 * 1024.0))
1017            } else {
1018                format!("{:.1} GB", b / (1024.0 * 1024.0 * 1024.0))
1019            }
1020        }
1021    }
1022}
1023
1024/// `YYYY-MM-DD HH:MM` (UTC) from whole Unix seconds, or an em-dash when unknown.
1025fn fmt_date(modified: Option<f64>) -> String {
1026    let Some(secs) = modified else {
1027        return "\u{2014}".into();
1028    };
1029    let days = (secs / 86_400.0).floor() as i64;
1030    let (y, m, d) = civil_from_days(days);
1031    let sod = ((secs as i64) % 86_400 + 86_400) % 86_400;
1032    format!("{y:04}-{m:02}-{d:02} {:02}:{:02}", sod / 3600, (sod % 3600) / 60)
1033}
1034
1035/// Gregorian `(year, month, day)` from a day count since the Unix epoch
1036/// (Howard Hinnant's `civil_from_days`) — pure integer arithmetic, so it is
1037/// wasm-safe and never touches `SystemTime`.
1038use brep_render::sheets::frame::civil_from_days;
1039
1040/// Split a POSIX-ish location into `(label, navigable-path)` breadcrumb segments,
1041/// starting at the root. e.g. `/home/me/models` →
1042/// `[("/", "/"), ("home", "/home"), ("me", "/home/me"), ("models", "/home/me/models")]`.
1043fn breadcrumb_segments(location: &str) -> Vec<(String, String)> {
1044    let mut out = vec![("/".to_string(), "/".to_string())];
1045    let mut acc = String::new();
1046    for comp in location.split('/').filter(|s| !s.is_empty()) {
1047        acc.push('/');
1048        acc.push_str(comp);
1049        out.push((comp.to_string(), acc.clone()));
1050    }
1051    out
1052}
1053
1054/// The glyph a pinned folder's row draws: the Open command's folder artwork.
1055const PIN_GLYPH: &str = "\u{E011}";
1056
1057/// The glyph a sidebar place draws for its category — catalogued artwork
1058/// (`icons.rs`), drawn by [`sidebar_row`]. The plain characters these used to
1059/// be were partly missing from the UI font (🗀 and 📌 drew as empty boxes), and
1060/// Root drew "/" beside its label "/" (lane U audit item 12).
1061fn place_glyph(kind: PlaceKind) -> &'static str {
1062    match kind {
1063        PlaceKind::Home => "\u{2302}",      // ⌂ — the font draws it
1064        PlaceKind::Documents => "\u{1F5CE}", // 🗎 catalogued
1065        PlaceKind::Downloads => "\u{2B07}",  // ⬇ catalogued
1066        PlaceKind::Models | PlaceKind::Root => PIN_GLYPH,
1067    }
1068}
1069
1070/// A Places / Pinned row: the leading catalogued glyph as artwork, framed only
1071/// on hover — what `selectable_label(false, …)` drew, with the icon.
1072fn sidebar_row<'a>(ui: &egui::Ui, caption: &'a str) -> egui::Button<'a> {
1073    crate::icon_text::icon_button(ui, caption).frame_when_inactive(false)
1074}
1075