1use 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 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
66pub 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; under a finger one tap enters a folder and selects a file, which open:confirm opens), 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 pub activated: Option<String>,
92 pub selected: Option<String>,
97 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#[derive(Clone, Copy, PartialEq, Eq, Default)]
109enum SortKey {
110 #[default]
111 Name,
112 Kind,
113 Size,
114 Date,
115}
116
117#[derive(Default)]
120pub struct FileExplorer {
121 query: String,
122 new_folder: String,
123 error: String,
124 selected: Option<String>,
129 selected_dir: Option<String>,
135 enter_dir: Option<String>,
139 selected_at: String,
142 history: Vec<String>,
144 forward: Vec<String>,
145 editing_path: Option<String>,
147 path_focus: bool,
149 nav_rows: Vec<(String, bool)>,
152 touch_nav_at: Option<f64>,
157 last_press_at: Option<f64>,
160 sort_key: SortKey,
162 sort_desc: bool,
163 show_hidden: bool,
166}
167
168impl FileExplorer {
169 pub fn new() -> Self {
170 Self::default()
171 }
172
173 pub fn selected(&self) -> Option<&str> {
177 self.selected.as_deref()
178 }
179
180 pub fn clear_selection(&mut self) {
186 self.selected = None;
187 self.selected_dir = None;
188 }
189
190 pub fn selected_folder(&self) -> Option<&str> {
193 self.selected_dir.as_deref()
194 }
195
196 fn select(&mut self, identity: &str, is_dir: bool) {
199 if is_dir {
200 self.selected = None;
201 self.selected_dir = Some(identity.to_string());
202 } else {
203 self.selected_dir = None;
204 self.selected = Some(identity.to_string());
205 }
206 }
207
208 fn activate(&mut self, identity: &str, is_dir: bool, out: &mut FileExplorerOutput) {
211 self.select(identity, is_dir);
212 if is_dir {
213 self.enter_dir = Some(identity.to_string());
214 } else {
215 out.activated = Some(identity.to_string());
216 }
217 }
218
219 pub fn show_store(
221 &mut self,
222 ui: &mut egui::Ui,
223 store: &dyn ModelStore,
224 options: FileExplorerOptions<'_>,
225 ) -> FileExplorerOutput {
226 let entries = store.browser_entries(options.extensions);
227 let location = store.browser_location();
228 if location != self.selected_at {
229 self.selected = None;
230 self.selected_dir = None;
231 self.selected_at = location.clone();
232 }
233 let places = store.browser_places();
234 let pins = Self::read_pins(store);
235 let mut out = FileExplorerOutput::default();
236
237 let selected_before = (self.selected.clone(), self.selected_dir.clone());
238 if let Some(now) = ui.input(|i| i.pointer.any_pressed().then_some(i.time)) {
239 self.last_press_at = Some(now);
240 }
241 let compact = crate::viewport::touch::compact(ui.ctx());
242 if compact {
243 ui.horizontal_wrapped(|ui| {
244 let places_menu = ui.menu_button("Places", |ui| {
245 ui.set_height((ui.ctx().content_rect().height() - 100.0).clamp(80.0, 300.0));
246 self.show_sidebar(ui, store, &places, &pins, &location, options, &mut out);
247 });
248 out.hits.push((format!("{}:places-menu", options.hit_prefix), places_menu.response.rect));
249 let up = ui.add(crate::ui_kit::Button::new("Up"));
250 out.hits.push((format!("{}:up", options.hit_prefix), up.rect));
251 if up.clicked() { self.nav(store, || store.browser_up()); }
252 let folder = ui.menu_button("Folder", |ui| {
253 self.show_nav_bar(ui, store, &location, options, &mut out);
254 let hidden = crate::ui_kit::checkbox(ui, &mut self.show_hidden, "Show hidden files");
255 out.hits.push((format!("{}:hidden-toggle", options.hit_prefix), hidden.rect));
256 });
257 out.hits.push((format!("{}:folder-menu", options.hit_prefix), folder.response.rect));
258 let filter_width = ui.available_width().clamp(60.0, 150.0);
259 let filter = crate::ui_kit::text_input(&mut self.query).placeholder("Filter files").width(filter_width).show(ui).framed();
260 out.hits.push((format!("{}:filter", options.hit_prefix), filter.rect));
261 });
262 } else { self.show_nav_bar(ui, store, &location, options, &mut out); }
263 if !self.error.is_empty() {
264 ui.colored_label(ui.visuals().error_fg_color, &self.error);
265 }
266 ui.add_space(2.0);
267 ui.separator();
268
269 bottom_panel(ui, "brep-file-explorer-footer", options.hit_prefix, |ui| {
276 self.show_footer(ui, options, &mut out)
277 });
278 if compact {
279 self.show_list(ui, &entries, options, &mut out);
280 } else { ui.horizontal_top(|ui| {
281 if !places.is_empty() {
282 ui.vertical(|ui| {
283 self.show_sidebar(ui, store, &places, &pins, &location, options, &mut out);
284 });
285 ui.separator();
286 }
287 ui.vertical(|ui| {
288 self.show_list(ui, &entries, options, &mut out);
289 });
290 }); }
291
292 self.handle_keys(ui, options, &mut out);
293 if let Some(dir) = self.enter_dir.take() {
296 self.nav(store, || store.browser_enter(&dir));
297 ui.ctx().request_repaint();
298 }
299 out.selected = self.selected.clone();
300 if out.picked.is_some() || (self.selected.clone(), self.selected_dir.clone()) != selected_before {
305 ui.ctx().request_repaint();
306 }
307 out
308 }
309
310 fn nav<F: FnOnce() -> Result<(), String>>(&mut self, store: &dyn ModelStore, action: F) {
316 let before = store.browser_location();
317 match action() {
318 Ok(()) => {
319 let after = store.browser_location();
320 if after != before {
321 self.history.push(before);
322 self.forward.clear();
323 }
324 self.error.clear();
325 self.selected = None;
326 self.selected_dir = None;
327 }
328 Err(error) => self.error = error,
329 }
330 }
331
332 fn back(&mut self, store: &dyn ModelStore) {
335 if let Some(prev) = self.history.pop() {
336 let current = store.browser_location();
337 if store.browser_navigate(&prev).is_ok() {
338 self.forward.push(current);
339 self.selected = None;
340 self.selected_dir = None;
341 self.error.clear();
342 } else {
343 self.history.push(prev);
344 }
345 }
346 }
347
348 fn forward_go(&mut self, store: &dyn ModelStore) {
349 if let Some(next) = self.forward.pop() {
350 let current = store.browser_location();
351 if store.browser_navigate(&next).is_ok() {
352 self.history.push(current);
353 self.selected = None;
354 self.selected_dir = None;
355 self.error.clear();
356 } else {
357 self.forward.push(next);
358 }
359 }
360 }
361
362 fn show_nav_bar(
365 &mut self,
366 ui: &mut egui::Ui,
367 store: &dyn ModelStore,
368 location: &str,
369 options: FileExplorerOptions<'_>,
370 out: &mut FileExplorerOutput,
371 ) {
372 ui.horizontal(|ui| {
373 let back = ui.add(crate::ui_kit::Button::ghost("\u{25C0}").size(crate::ui_kit::Size::Sm).enabled(!self.history.is_empty()));
374 out.hits.push((format!("{}:back", options.hit_prefix), back.rect));
375 if back.clicked() {
376 self.back(store);
377 }
378 let fwd = {
379 let b = crate::icon_text::icon_button(ui, "\u{25B6}").small()
380 .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO));
381 ui.add_enabled(!self.forward.is_empty(), b)
382 };
383 out.hits.push((format!("{}:forward", options.hit_prefix), fwd.rect));
384 if fwd.clicked() {
385 self.forward_go(store);
386 }
387 let up = ui.add(crate::ui_kit::Button::ghost("\u{2191}").size(crate::ui_kit::Size::Sm));
388 out.hits.push((format!("{}:up", options.hit_prefix), up.rect));
389 if up.clicked() {
390 self.nav(store, || store.browser_up());
391 }
392 ui.separator();
393 self.show_breadcrumb(ui, store, location, options, out);
394 });
395 ui.horizontal(|ui| {
396 let create = ui.add(crate::ui_kit::Button::new("+ Folder").size(crate::ui_kit::Size::Sm));
397 out.hits
398 .push((format!("{}:new-folder", options.hit_prefix), create.rect));
399 let field = crate::ui_kit::text_input(&mut self.new_folder).placeholder("New folder").width(140.0).show(ui).framed();
400 out.hits
401 .push((format!("{}:new-folder-name", options.hit_prefix), field.rect));
402 let submit = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
403 if (create.clicked() || submit) && !self.new_folder.trim().is_empty() {
404 match store.browser_create_dir(self.new_folder.trim()) {
405 Ok(()) => {
406 self.new_folder.clear();
407 self.error.clear();
408 }
409 Err(error) => self.error = error,
410 }
411 }
412 });
413 }
414
415 fn show_breadcrumb(
418 &mut self,
419 ui: &mut egui::Ui,
420 store: &dyn ModelStore,
421 location: &str,
422 options: FileExplorerOptions<'_>,
423 out: &mut FileExplorerOutput,
424 ) {
425 if self.editing_path.is_some() {
426 let mut buf = self.editing_path.take().unwrap();
427 let resp = crate::ui_kit::text_input(&mut buf).placeholder("type a path, Enter to go").width(300.0).show(ui).framed();
428 out.hits
429 .push((format!("{}:path-edit", options.hit_prefix), resp.rect));
430 if self.path_focus {
431 resp.request_focus();
432 self.path_focus = false;
433 }
434 let go = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
435 if go {
436 self.nav(store, || store.browser_navigate(&buf));
437 } else if !resp.lost_focus() {
438 self.editing_path = Some(buf); }
440 return;
442 }
443 let edit = ui.add(crate::icon_text::icon_button(ui, "\u{270E}").small()
447 .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO))); out.hits
449 .push((format!("{}:path-edit-toggle", options.hit_prefix), edit.rect));
450 if edit.on_hover_text("Type a path").clicked() {
451 self.editing_path = Some(location.to_string());
452 self.path_focus = true;
453 }
454 let avail = ui.available_width();
455 egui::ScrollArea::horizontal()
456 .id_salt(format!("{}-crumbs", options.hit_prefix))
457 .max_width(avail)
458 .auto_shrink([false, true])
462 .stick_to_right(true)
465 .show(ui, |ui| {
466 ui.horizontal(|ui| {
467 for (i, (label, path)) in breadcrumb_segments(location).into_iter().enumerate() {
468 if i > 0 {
469 ui.weak("\u{203A}"); }
471 let seg = ui.add(crate::ui_kit::Button::ghost(&label).size(crate::ui_kit::Size::Sm));
472 out.hits
473 .push((format!("{}:crumb:{i}", options.hit_prefix), seg.rect));
474 if seg.clicked() {
475 self.nav(store, || store.browser_navigate(&path));
476 }
477 }
478 });
479 });
480 }
481
482 #[allow(clippy::too_many_arguments)]
485 fn show_sidebar(
486 &mut self,
487 ui: &mut egui::Ui,
488 store: &dyn ModelStore,
489 places: &[BrowserPlace],
490 pins: &[String],
491 location: &str,
492 options: FileExplorerOptions<'_>,
493 out: &mut FileExplorerOutput,
494 ) {
495 ui.set_min_width(132.0);
496 ui.set_max_width(152.0);
497 egui::ScrollArea::vertical()
498 .id_salt(format!("{}-sidebar", options.hit_prefix))
499 .auto_shrink([false, false])
500 .show(ui, |ui| {
501 ui.weak("Places");
502 for place in places {
503 let caption = format!("{} {}", place_glyph(place.kind), place.label);
504 let resp = ui.add(sidebar_row(ui, &caption));
505 out.hits
506 .push((format!("{}:place:{}", options.hit_prefix, place.label), resp.rect));
507 if resp.clicked() {
508 let loc = place.location.clone();
509 self.nav(store, || store.browser_navigate(&loc));
510 self.after_touch_place(ui);
511 }
512 }
513 if !pins.is_empty() {
514 ui.add_space(6.0);
515 ui.weak("Pinned");
516 for pin in pins {
517 ui.horizontal(|ui| {
518 let label = pin.rsplit(['/', '\\']).find(|s| !s.is_empty()).unwrap_or(pin);
519 let caption = format!("{PIN_GLYPH} {label}");
520 let resp = ui.add(sidebar_row(ui, &caption));
521 out.hits
522 .push((format!("{}:pin:{label}", options.hit_prefix), resp.rect));
523 if resp.clicked() {
524 let loc = pin.clone();
525 self.nav(store, || store.browser_navigate(&loc));
526 self.after_touch_place(ui);
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 fn after_touch_place(&mut self, ui: &egui::Ui) {
557 if crate::viewport::touch::enabled(ui.ctx()) {
558 self.touch_nav_at = Some(ui.input(|i| i.time));
559 if crate::viewport::touch::compact(ui.ctx()) {
560 ui.close();
561 }
562 }
563 }
564
565 fn read_pins(store: &dyn ModelStore) -> Vec<String> {
567 store
568 .read(PINNED_KEY)
569 .and_then(|raw| serde_json::from_str::<Vec<String>>(&raw).ok())
570 .unwrap_or_default()
571 }
572
573 fn set_pin(store: &dyn ModelStore, location: &str, want: bool) {
575 let mut pins = Self::read_pins(store);
576 let has = pins.iter().any(|p| p == location);
577 if want && !has {
578 pins.push(location.to_string());
579 } else if !want && has {
580 pins.retain(|p| p != location);
581 } else {
582 return;
583 }
584 let _ = store.write(
585 PINNED_KEY,
586 &serde_json::to_string(&pins).unwrap_or_else(|_| "[]".into()),
587 );
588 }
589
590 fn show_list(
593 &mut self,
594 ui: &mut egui::Ui,
595 entries: &[BrowserEntry],
596 options: FileExplorerOptions<'_>,
597 out: &mut FileExplorerOutput,
598 ) {
599 if !crate::viewport::touch::compact(ui.ctx()) { ui.horizontal(|ui| {
601 let hidden = crate::ui_kit::checkbox(ui, &mut self.show_hidden, "Hidden");
602 out.hits
603 .push((format!("{}:hidden-toggle", options.hit_prefix), hidden.rect));
604 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
605 let search = crate::ui_kit::text_input(&mut self.query).placeholder("Filter files").width(150.0).show(ui).framed();
606 out.hits
607 .push((format!("{}:filter", options.hit_prefix), search.rect));
608 });
609 }); }
610
611 let query = self.query.trim().to_ascii_lowercase();
612 let mut named: Vec<(String, &BrowserEntry)> = entries
616 .iter()
617 .filter_map(|entry| {
618 let hidden = entry.name.starts_with('.');
620 let lower = entry.name.to_ascii_lowercase();
621 ((self.show_hidden || !hidden) && (entry.is_dir || query.is_empty() || lower.contains(&query))).then_some((lower, entry))
622 })
623 .collect();
624 let (key, desc) = (self.sort_key, self.sort_desc);
626 named.sort_by(|(a_name, a), (b_name, b)| {
627 b.is_dir.cmp(&a.is_dir).then_with(|| {
628 let by_name = || a_name.cmp(b_name);
629 let ord = match key {
630 SortKey::Name => by_name(),
631 SortKey::Kind => entry_kind(a).cmp(&entry_kind(b)).then_with(by_name),
632 SortKey::Size => a.size.unwrap_or(0).cmp(&b.size.unwrap_or(0)).then_with(by_name),
633 SortKey::Date => cmp_opt(a.modified, b.modified).then_with(by_name),
634 };
635 if desc { ord.reverse() } else { ord }
636 })
637 });
638 let visible: Vec<&BrowserEntry> = named.into_iter().map(|(_, entry)| entry).collect();
639 self.nav_rows = visible
640 .iter()
641 .map(|entry| (entry.identity.clone(), entry.is_dir))
642 .collect();
643
644 if visible.is_empty() {
645 ui.separator();
646 ui.weak(options.empty_label);
647 return;
648 }
649
650 if crate::viewport::touch::compact(ui.ctx()) {
651 let sort = ui.menu_button("Sort", |ui| {
652 for (label, key) in [("Name", SortKey::Name), ("Type", SortKey::Kind), ("Size", SortKey::Size), ("Date", SortKey::Date)] {
653 if ui.selectable_label(self.sort_key == key, label).clicked() {
654 if self.sort_key == key { self.sort_desc = !self.sort_desc; }
655 else { self.sort_key = key; self.sort_desc = false; }
656 ui.close();
657 }
658 }
659 });
660 out.hits.push((format!("{}:sort-menu", options.hit_prefix), sort.response.rect));
661 let row_h = crate::viewport::touch::target_size(ui.ctx(), egui::vec2(0.0, egui::TextStyle::Body.resolve(ui.style()).size + 6.0)).y;
662 egui::ScrollArea::vertical().id_salt(format!("{}-compact-list", options.hit_prefix)).show(ui, |ui| {
663 for entry in visible {
664 ui.horizontal(|ui| {
665 let icon = if entry.is_dir { "\u{1F5C0}" } else { options.row_icon };
666 let highlight = self.row_highlight(entry, options.current);
667 let deletable = options.allow_delete && !entry.is_dir;
668 let width = (ui.available_width() - if deletable { 44.0 + ui.spacing().item_spacing.x } else { 0.0 }).max(44.0);
669 let text = format!("{icon} {}", entry.name);
670 let r = ui.add_sized([width, row_h], crate::icon_text::icon_button(ui, &text).selected(highlight).truncate());
671 out.hits.push((format!("{}:{}", options.hit_prefix, entry.name), r.rect));
672 self.row_clicked(&r, entry, out);
673 if deletable {
674 let delete = ui.add(crate::icon_text::icon_button(ui, "\u{2715}").small()
675 .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
676 out.hits.push((format!("del:{}", entry.name), delete.rect));
677 if delete.clicked() { out.remove = Some(entry.identity.clone()); }
678 }
679 });
680 }
681 });
682 return;
683 }
684
685 let row_h = egui::TextStyle::Body.resolve(ui.style()).size + 6.0;
689 let mut clicked_sort: Option<SortKey> = None;
690 ui.scope(|ui| {
696 ui.style_mut().interaction.selectable_labels = false;
697 TableBuilder::new(ui)
698 .id_salt(format!("{}-table", options.hit_prefix))
699 .striped(true)
700 .sense(egui::Sense::click())
701 .cell_layout(egui::Layout::left_to_right(egui::Align::Center))
702 .column(Column::remainder().at_least(150.0).clip(true)) .column(Column::auto().at_least(72.0)) .column(Column::auto().at_least(66.0)) .column(Column::auto().at_least(120.0)) .column(Column::auto().at_least(20.0)) .header(row_h, |mut header| {
708 for (label, col) in [
709 ("Name", SortKey::Name),
710 ("Type", SortKey::Kind),
711 ("Size", SortKey::Size),
712 ("Date", SortKey::Date),
713 ] {
714 header.col(|ui| {
715 let arrow = if key == col {
716 if desc {
717 " \u{25BE}"
718 } else {
719 " \u{25B4}"
720 }
721 } else {
722 ""
723 };
724 let btn =
725 ui.add(crate::ui_kit::Button::ghost(&format!("{label}{arrow}")));
726 out.hits.push((
727 format!("{}:sort:{}", options.hit_prefix, sort_slug(col)),
728 btn.rect,
729 ));
730 if btn.clicked() {
731 clicked_sort = Some(col);
732 }
733 });
734 }
735 header.col(|_ui| {});
736 })
737 .body(|body| {
738 body.rows(row_h, visible.len(), |mut row| {
739 let entry = visible[row.index()];
740 let icon = if entry.is_dir {
741 "\u{1F5C0}"
742 } else {
743 options.row_icon
744 };
745 row.set_selected(self.row_highlight(entry, options.current));
746 let prefix = options.hit_prefix;
747 let (name_rect, _) = row.col(|ui| {
748 crate::ui_kit::surface::icon_name_cell(ui, &format!("{icon} {}", entry.name));
749 });
750 out.hits.push((format!("{prefix}:{}", entry.name), name_rect));
751 let cells = [
752 ("type", entry_kind(entry)),
753 ("size", fmt_size(entry.size)),
754 ("date", fmt_date(entry.modified)),
755 ];
756 for (slug, text) in cells {
757 let (rect, _) = row.col(|ui| {
758 ui.add(egui::Label::new(egui::RichText::new(text).weak()).selectable(false));
759 });
760 out.hits.push((format!("{prefix}:cell:{slug}:{}", entry.name), rect));
761 }
762 let clicked_row = row.response();
765 row.col(|ui| {
766 if options.allow_delete && !entry.is_dir {
767 let del = {
768 let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
769 ui.add(b)
770 };
771 out.hits.push((format!("del:{}", entry.name), del.rect));
772 if del.clicked() {
773 out.remove = Some(entry.identity.clone());
774 }
775 }
776 });
777 self.row_clicked(&clicked_row, entry, out);
778 });
779 });
780 });
781 if let Some(col) = clicked_sort {
782 if self.sort_key == col {
783 self.sort_desc = !self.sort_desc;
784 } else {
785 self.sort_key = col;
786 self.sort_desc = false;
787 }
788 }
789 }
790
791 fn row_highlight(&self, entry: &BrowserEntry, current: Option<&str>) -> bool {
794 let id = entry.identity.as_str();
795 if entry.is_dir {
796 self.selected_dir.as_deref() == Some(id)
797 } else {
798 match &self.selected {
799 Some(sel) => sel == id,
800 None => self.selected_dir.is_none() && current == Some(id),
801 }
802 }
803 }
804
805 fn row_clicked(&mut self, response: &egui::Response, entry: &BrowserEntry, out: &mut FileExplorerOutput) {
816 if crate::viewport::touch::enabled(&response.ctx) {
817 if !response.clicked() {
818 return;
819 }
820 let now = response.ctx.input(|i| i.time);
821 if double_tap_twin(&response.ctx, self.touch_nav_at, self.last_press_at) {
822 return;
823 }
824 if entry.is_dir {
825 self.activate(&entry.identity, true, out);
826 self.touch_nav_at = Some(now);
827 } else if response.double_clicked() && self.selected.as_deref() == Some(entry.identity.as_str()) {
828 self.activate(&entry.identity, false, out);
829 } else {
830 self.select(&entry.identity, false);
831 out.picked = Some(entry.identity.clone());
832 }
833 return;
834 }
835 if response.double_clicked() {
836 self.activate(&entry.identity, entry.is_dir, out);
837 } else if response.clicked() {
838 self.select(&entry.identity, entry.is_dir);
839 if !entry.is_dir {
840 out.picked = Some(entry.identity.clone());
841 }
842 }
843 }
844
845 fn handle_keys(
854 &mut self,
855 ui: &egui::Ui,
856 options: FileExplorerOptions<'_>,
857 out: &mut FileExplorerOutput,
858 ) {
859 if options.confirm_label.is_none() || ui.ctx().egui_wants_keyboard_input() {
860 return;
861 }
862 if self.nav_rows.is_empty() {
863 return;
864 }
865 let (down, up, enter) = ui.input(|i| {
866 (
867 i.key_pressed(egui::Key::ArrowDown),
868 i.key_pressed(egui::Key::ArrowUp),
869 i.key_pressed(egui::Key::Enter),
870 )
871 });
872 if down || up {
873 let held = self.selected.as_deref().or(self.selected_dir.as_deref());
874 let current = held.and_then(|s| self.nav_rows.iter().position(|(id, _)| id == s));
875 let next = match current {
876 Some(i) if down => (i + 1).min(self.nav_rows.len() - 1),
877 Some(i) => i.saturating_sub(1),
878 None => 0,
879 };
880 let (id, is_dir) = self.nav_rows[next].clone();
881 self.select(&id, is_dir);
882 if !is_dir {
883 out.picked = Some(id);
884 }
885 } else if enter {
886 if let Some(dir) = self.selected_dir.clone() {
887 self.enter_dir = Some(dir);
888 } else if let Some(sel) = &self.selected {
889 out.activated = Some(sel.clone());
890 }
891 }
892 }
893
894 fn show_footer(
895 &mut self,
896 ui: &mut egui::Ui,
897 options: FileExplorerOptions<'_>,
898 out: &mut FileExplorerOutput,
899 ) {
900 ui.separator();
901 ui.horizontal(|ui| {
902 if let Some(label) = options.confirm_label {
903 let any = self.selected.is_some() || self.selected_dir.is_some();
904 let confirm = ui.add(crate::ui_kit::Button::primary(label).enabled(any));
907 out.hits
908 .push((format!("{}:confirm", options.hit_prefix), confirm.rect));
909 if confirm.clicked() {
910 if let Some(dir) = self.selected_dir.clone() {
912 self.enter_dir = Some(dir);
913 } else {
914 out.activated = self.selected.clone();
915 }
916 }
917 }
918 if options.allow_import {
919 let import = {
920 let label = format!("\u{2B06} {}", options.import_label);
921 let b = crate::icon_text::icon_button(ui, &label);
922 ui.add(b)
923 };
924 out.hits.push((options.import_hit.into(), import.rect));
925 out.import = import.clicked();
926 }
927 if options.show_cancel {
928 let cancel = ui.add(crate::ui_kit::Button::new("Cancel"));
929 out.hits.push(("cancel".into(), cancel.rect));
930 out.cancel = cancel.clicked();
931 }
932 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
934 if let Some(sel) = self.selected.as_ref().or(self.selected_dir.as_ref()) {
935 let name = sel.rsplit(['/', '\\']).next().unwrap_or(sel);
936 ui.add(
940 egui::Label::new(egui::RichText::new(name).weak()).truncate(),
941 );
942 }
943 });
944 });
945 }
946
947}
948
949pub fn dialog_body<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
959 let screen = ui.ctx().content_rect().size();
960 let compact = crate::viewport::touch::compact(ui.ctx());
961 let max = if compact { (screen - egui::Vec2::splat(24.0)).max(egui::Vec2::splat(80.0)) }
962 else { egui::vec2((screen.x - 40.0).max(320.0), (screen.y - 80.0).max(240.0)) };
963 egui::Resize::default()
964 .id_salt(if compact { "brep-file-dialog-size-mobile" } else { "brep-file-dialog-size" })
965 .with_stroke(false)
968 .min_size(egui::vec2(460.0_f32.min(max.x), 300.0_f32.min(max.y)))
969 .max_size(max)
970 .default_size(egui::vec2(620.0_f32.min(max.x), 520.0_f32.min(max.y)))
971 .show(ui, add_contents)
972}
973
974pub fn dialog_footer<R>(
981 ui: &mut egui::Ui,
982 salt: &str,
983 add_contents: impl FnOnce(&mut egui::Ui) -> R,
984) -> R {
985 bottom_panel(ui, "brep-file-dialog-footer", salt, add_contents)
986}
987
988fn bottom_panel<R>(
992 ui: &mut egui::Ui,
993 base: &str,
994 salt: &str,
995 add_contents: impl FnOnce(&mut egui::Ui) -> R,
996) -> R {
997 egui::containers::panel::Panel::bottom(egui::Id::new((base, salt)))
998 .frame(egui::Frame::NONE)
999 .show_separator_line(false)
1000 .show(ui, add_contents)
1001 .inner
1002}
1003
1004fn cmp_opt(a: Option<f64>, b: Option<f64>) -> Ordering {
1006 match (a, b) {
1007 (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal),
1008 (Some(_), None) => Ordering::Less,
1009 (None, Some(_)) => Ordering::Greater,
1010 (None, None) => Ordering::Equal,
1011 }
1012}
1013
1014fn entry_kind(entry: &BrowserEntry) -> String {
1016 if entry.is_dir {
1017 return "Folder".into();
1018 }
1019 let lower = entry.name.to_ascii_lowercase();
1020 if lower.ends_with(".nbrep") {
1021 return "BREP model".into();
1022 }
1023 match entry.name.rsplit_once('.') {
1024 Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => ext.to_uppercase(),
1025 _ => "File".into(),
1026 }
1027}
1028
1029fn sort_slug(key: SortKey) -> &'static str {
1031 match key {
1032 SortKey::Name => "name",
1033 SortKey::Kind => "type",
1034 SortKey::Size => "size",
1035 SortKey::Date => "date",
1036 }
1037}
1038
1039fn fmt_size(size: Option<u64>) -> String {
1041 match size {
1042 None => "\u{2014}".into(),
1043 Some(bytes) => {
1044 let b = bytes as f64;
1045 if bytes < 1024 {
1046 format!("{bytes} B")
1047 } else if b < 1024.0 * 1024.0 {
1048 format!("{:.1} KB", b / 1024.0)
1049 } else if b < 1024.0 * 1024.0 * 1024.0 {
1050 format!("{:.1} MB", b / (1024.0 * 1024.0))
1051 } else {
1052 format!("{:.1} GB", b / (1024.0 * 1024.0 * 1024.0))
1053 }
1054 }
1055 }
1056}
1057
1058fn fmt_date(modified: Option<f64>) -> String {
1060 let Some(secs) = modified else {
1061 return "\u{2014}".into();
1062 };
1063 let days = (secs / 86_400.0).floor() as i64;
1064 let (y, m, d) = civil_from_days(days);
1065 let sod = ((secs as i64) % 86_400 + 86_400) % 86_400;
1066 format!("{y:04}-{m:02}-{d:02} {:02}:{:02}", sod / 3600, (sod % 3600) / 60)
1067}
1068
1069use brep_render::sheets::frame::civil_from_days;
1073
1074fn breadcrumb_segments(location: &str) -> Vec<(String, String)> {
1078 let mut out = vec![("/".to_string(), "/".to_string())];
1079 let mut acc = String::new();
1080 for comp in location.split('/').filter(|s| !s.is_empty()) {
1081 acc.push('/');
1082 acc.push_str(comp);
1083 out.push((comp.to_string(), acc.clone()));
1084 }
1085 out
1086}
1087
1088pub(crate) fn double_tap_twin(ctx: &egui::Context, nav_at: Option<f64>, pressed_at: Option<f64>) -> bool {
1093 let delay = ctx.options(|o| o.input_options.max_double_click_delay);
1094 match (nav_at, pressed_at) {
1095 (Some(nav), Some(press)) => press >= nav && press - nav <= delay,
1096 _ => false,
1097 }
1098}
1099
1100const PIN_GLYPH: &str = "\u{E011}";
1102
1103fn place_glyph(kind: PlaceKind) -> &'static str {
1108 match kind {
1109 PlaceKind::Home => "\u{2302}", PlaceKind::Documents => "\u{1F5CE}", PlaceKind::Downloads => "\u{2B07}", PlaceKind::Models | PlaceKind::Root => PIN_GLYPH,
1113 }
1114}
1115
1116fn sidebar_row<'a>(ui: &egui::Ui, caption: &'a str) -> egui::Button<'a> {
1119 crate::icon_text::icon_button(ui, caption).frame_when_inactive(false)
1120}
1121