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.scope(|ui| { crate::theme::data_rows(ui); ui.add(sidebar_row(ui, &caption)) }).inner;
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.scope(|ui| { crate::theme::data_rows(ui); ui.add(sidebar_row(ui, &caption)) }).inner;
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 crate::theme::data_rows(ui);
666 let icon = if entry.is_dir { "\u{1F5C0}" } else { options.row_icon };
667 let highlight = self.row_highlight(entry, options.current);
668 let deletable = options.allow_delete && !entry.is_dir;
669 let width = (ui.available_width() - if deletable { 44.0 + ui.spacing().item_spacing.x } else { 0.0 }).max(44.0);
670 let text = format!("{icon} {}", entry.name);
671 let r = ui.add_sized([width, row_h], crate::icon_text::icon_button(ui, &text).selected(highlight).truncate());
672 out.hits.push((format!("{}:{}", options.hit_prefix, entry.name), r.rect));
673 self.row_clicked(&r, entry, out);
674 if deletable {
675 let delete = ui.add(crate::icon_text::icon_button(ui, "\u{2715}").small()
676 .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)));
677 out.hits.push((format!("del:{}", entry.name), delete.rect));
678 if delete.clicked() { out.remove = Some(entry.identity.clone()); }
679 }
680 });
681 }
682 });
683 return;
684 }
685
686 let row_h = egui::TextStyle::Body.resolve(ui.style()).size + 6.0;
690 let mut clicked_sort: Option<SortKey> = None;
691 ui.scope(|ui| {
697 ui.style_mut().interaction.selectable_labels = false;
698 TableBuilder::new(ui)
699 .id_salt(format!("{}-table", options.hit_prefix))
700 .striped(true)
701 .sense(egui::Sense::click())
702 .cell_layout(egui::Layout::left_to_right(egui::Align::Center))
703 .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| {
709 for (label, col) in [
710 ("Name", SortKey::Name),
711 ("Type", SortKey::Kind),
712 ("Size", SortKey::Size),
713 ("Date", SortKey::Date),
714 ] {
715 header.col(|ui| {
716 let arrow = if key == col {
717 if desc {
718 " \u{25BE}"
719 } else {
720 " \u{25B4}"
721 }
722 } else {
723 ""
724 };
725 let btn =
726 ui.add(crate::ui_kit::Button::ghost(&format!("{label}{arrow}")));
727 out.hits.push((
728 format!("{}:sort:{}", options.hit_prefix, sort_slug(col)),
729 btn.rect,
730 ));
731 if btn.clicked() {
732 clicked_sort = Some(col);
733 }
734 });
735 }
736 header.col(|_ui| {});
737 })
738 .body(|body| {
739 body.rows(row_h, visible.len(), |mut row| {
740 let entry = visible[row.index()];
741 let icon = if entry.is_dir {
742 "\u{1F5C0}"
743 } else {
744 options.row_icon
745 };
746 row.set_selected(self.row_highlight(entry, options.current));
747 let prefix = options.hit_prefix;
748 let (name_rect, _) = row.col(|ui| {
749 crate::ui_kit::surface::icon_name_cell(ui, &format!("{icon} {}", entry.name));
750 });
751 out.hits.push((format!("{prefix}:{}", entry.name), name_rect));
752 let cells = [
753 ("type", entry_kind(entry)),
754 ("size", fmt_size(entry.size)),
755 ("date", fmt_date(entry.modified)),
756 ];
757 for (slug, text) in cells {
758 let (rect, _) = row.col(|ui| {
759 ui.add(egui::Label::new(crate::theme::data(text).weak()).selectable(false));
760 });
761 out.hits.push((format!("{prefix}:cell:{slug}:{}", entry.name), rect));
762 }
763 let clicked_row = row.response();
766 row.col(|ui| {
767 if options.allow_delete && !entry.is_dir {
768 let del = {
769 let b = crate::icon_text::icon_button(ui, "\u{2715}").small();
770 ui.add(b)
771 };
772 out.hits.push((format!("del:{}", entry.name), del.rect));
773 if del.clicked() {
774 out.remove = Some(entry.identity.clone());
775 }
776 }
777 });
778 self.row_clicked(&clicked_row, entry, out);
779 });
780 });
781 });
782 if let Some(col) = clicked_sort {
783 if self.sort_key == col {
784 self.sort_desc = !self.sort_desc;
785 } else {
786 self.sort_key = col;
787 self.sort_desc = false;
788 }
789 }
790 }
791
792 fn row_highlight(&self, entry: &BrowserEntry, current: Option<&str>) -> bool {
795 let id = entry.identity.as_str();
796 if entry.is_dir {
797 self.selected_dir.as_deref() == Some(id)
798 } else {
799 match &self.selected {
800 Some(sel) => sel == id,
801 None => self.selected_dir.is_none() && current == Some(id),
802 }
803 }
804 }
805
806 fn row_clicked(&mut self, response: &egui::Response, entry: &BrowserEntry, out: &mut FileExplorerOutput) {
817 if crate::viewport::touch::enabled(&response.ctx) {
818 if !response.clicked() {
819 return;
820 }
821 let now = response.ctx.input(|i| i.time);
822 if double_tap_twin(&response.ctx, self.touch_nav_at, self.last_press_at) {
823 return;
824 }
825 if entry.is_dir {
826 self.activate(&entry.identity, true, out);
827 self.touch_nav_at = Some(now);
828 } else if response.double_clicked() && self.selected.as_deref() == Some(entry.identity.as_str()) {
829 self.activate(&entry.identity, false, out);
830 } else {
831 self.select(&entry.identity, false);
832 out.picked = Some(entry.identity.clone());
833 }
834 return;
835 }
836 if response.double_clicked() {
837 self.activate(&entry.identity, entry.is_dir, out);
838 } else if response.clicked() {
839 self.select(&entry.identity, entry.is_dir);
840 if !entry.is_dir {
841 out.picked = Some(entry.identity.clone());
842 }
843 }
844 }
845
846 fn handle_keys(
855 &mut self,
856 ui: &egui::Ui,
857 options: FileExplorerOptions<'_>,
858 out: &mut FileExplorerOutput,
859 ) {
860 if options.confirm_label.is_none() || ui.ctx().egui_wants_keyboard_input() {
861 return;
862 }
863 if self.nav_rows.is_empty() {
864 return;
865 }
866 let (down, up, enter) = ui.input(|i| {
867 (
868 i.key_pressed(egui::Key::ArrowDown),
869 i.key_pressed(egui::Key::ArrowUp),
870 i.key_pressed(egui::Key::Enter),
871 )
872 });
873 if down || up {
874 let held = self.selected.as_deref().or(self.selected_dir.as_deref());
875 let current = held.and_then(|s| self.nav_rows.iter().position(|(id, _)| id == s));
876 let next = match current {
877 Some(i) if down => (i + 1).min(self.nav_rows.len() - 1),
878 Some(i) => i.saturating_sub(1),
879 None => 0,
880 };
881 let (id, is_dir) = self.nav_rows[next].clone();
882 self.select(&id, is_dir);
883 if !is_dir {
884 out.picked = Some(id);
885 }
886 } else if enter {
887 if let Some(dir) = self.selected_dir.clone() {
888 self.enter_dir = Some(dir);
889 } else if let Some(sel) = &self.selected {
890 out.activated = Some(sel.clone());
891 }
892 }
893 }
894
895 fn show_footer(
896 &mut self,
897 ui: &mut egui::Ui,
898 options: FileExplorerOptions<'_>,
899 out: &mut FileExplorerOutput,
900 ) {
901 ui.separator();
902 ui.horizontal(|ui| {
903 if let Some(label) = options.confirm_label {
904 let any = self.selected.is_some() || self.selected_dir.is_some();
905 let confirm = ui.add(crate::ui_kit::Button::primary(label).enabled(any));
908 out.hits
909 .push((format!("{}:confirm", options.hit_prefix), confirm.rect));
910 if confirm.clicked() {
911 if let Some(dir) = self.selected_dir.clone() {
913 self.enter_dir = Some(dir);
914 } else {
915 out.activated = self.selected.clone();
916 }
917 }
918 }
919 if options.allow_import {
920 let import = {
921 let label = format!("\u{2B06} {}", options.import_label);
922 let b = crate::icon_text::icon_button(ui, &label);
923 ui.add(b)
924 };
925 out.hits.push((options.import_hit.into(), import.rect));
926 out.import = import.clicked();
927 }
928 if options.show_cancel {
929 let cancel = ui.add(crate::ui_kit::Button::new("Cancel"));
930 out.hits.push(("cancel".into(), cancel.rect));
931 out.cancel = cancel.clicked();
932 }
933 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
935 if let Some(sel) = self.selected.as_ref().or(self.selected_dir.as_ref()) {
936 let name = sel.rsplit(['/', '\\']).next().unwrap_or(sel);
937 ui.add(
941 egui::Label::new(egui::RichText::new(name).weak()).truncate(),
942 );
943 }
944 });
945 });
946 }
947
948}
949
950pub fn dialog_body<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
960 let screen = ui.ctx().content_rect().size();
961 let compact = crate::viewport::touch::compact(ui.ctx());
962 let max = if compact { (screen - egui::Vec2::splat(24.0)).max(egui::Vec2::splat(80.0)) }
963 else { egui::vec2((screen.x - 40.0).max(320.0), (screen.y - 80.0).max(240.0)) };
964 egui::Resize::default()
965 .id_salt(if compact { "brep-file-dialog-size-mobile" } else { "brep-file-dialog-size" })
966 .with_stroke(false)
969 .min_size(egui::vec2(460.0_f32.min(max.x), 300.0_f32.min(max.y)))
970 .max_size(max)
971 .default_size(egui::vec2(620.0_f32.min(max.x), 520.0_f32.min(max.y)))
972 .show(ui, add_contents)
973}
974
975pub fn dialog_footer<R>(
982 ui: &mut egui::Ui,
983 salt: &str,
984 add_contents: impl FnOnce(&mut egui::Ui) -> R,
985) -> R {
986 bottom_panel(ui, "brep-file-dialog-footer", salt, add_contents)
987}
988
989fn bottom_panel<R>(
993 ui: &mut egui::Ui,
994 base: &str,
995 salt: &str,
996 add_contents: impl FnOnce(&mut egui::Ui) -> R,
997) -> R {
998 egui::containers::panel::Panel::bottom(egui::Id::new((base, salt)))
999 .frame(egui::Frame::NONE)
1000 .show_separator_line(false)
1001 .show(ui, add_contents)
1002 .inner
1003}
1004
1005fn cmp_opt(a: Option<f64>, b: Option<f64>) -> Ordering {
1007 match (a, b) {
1008 (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal),
1009 (Some(_), None) => Ordering::Less,
1010 (None, Some(_)) => Ordering::Greater,
1011 (None, None) => Ordering::Equal,
1012 }
1013}
1014
1015fn entry_kind(entry: &BrowserEntry) -> String {
1017 if entry.is_dir {
1018 return "Folder".into();
1019 }
1020 let lower = entry.name.to_ascii_lowercase();
1021 if lower.ends_with(".nbrep") {
1022 return "BREP model".into();
1023 }
1024 match entry.name.rsplit_once('.') {
1025 Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => ext.to_uppercase(),
1026 _ => "File".into(),
1027 }
1028}
1029
1030fn sort_slug(key: SortKey) -> &'static str {
1032 match key {
1033 SortKey::Name => "name",
1034 SortKey::Kind => "type",
1035 SortKey::Size => "size",
1036 SortKey::Date => "date",
1037 }
1038}
1039
1040fn fmt_size(size: Option<u64>) -> String {
1042 match size {
1043 None => "\u{2014}".into(),
1044 Some(bytes) => {
1045 let b = bytes as f64;
1046 if bytes < 1024 {
1047 format!("{bytes} B")
1048 } else if b < 1024.0 * 1024.0 {
1049 format!("{:.1} KB", b / 1024.0)
1050 } else if b < 1024.0 * 1024.0 * 1024.0 {
1051 format!("{:.1} MB", b / (1024.0 * 1024.0))
1052 } else {
1053 format!("{:.1} GB", b / (1024.0 * 1024.0 * 1024.0))
1054 }
1055 }
1056 }
1057}
1058
1059fn fmt_date(modified: Option<f64>) -> String {
1061 let Some(secs) = modified else {
1062 return "\u{2014}".into();
1063 };
1064 let days = (secs / 86_400.0).floor() as i64;
1065 let (y, m, d) = civil_from_days(days);
1066 let sod = ((secs as i64) % 86_400 + 86_400) % 86_400;
1067 format!("{y:04}-{m:02}-{d:02} {:02}:{:02}", sod / 3600, (sod % 3600) / 60)
1068}
1069
1070use brep_render::sheets::frame::civil_from_days;
1074
1075fn breadcrumb_segments(location: &str) -> Vec<(String, String)> {
1079 let mut out = vec![("/".to_string(), "/".to_string())];
1080 let mut acc = String::new();
1081 for comp in location.split('/').filter(|s| !s.is_empty()) {
1082 acc.push('/');
1083 acc.push_str(comp);
1084 out.push((comp.to_string(), acc.clone()));
1085 }
1086 out
1087}
1088
1089pub(crate) fn double_tap_twin(ctx: &egui::Context, nav_at: Option<f64>, pressed_at: Option<f64>) -> bool {
1094 let delay = ctx.options(|o| o.input_options.max_double_click_delay);
1095 match (nav_at, pressed_at) {
1096 (Some(nav), Some(press)) => press >= nav && press - nav <= delay,
1097 _ => false,
1098 }
1099}
1100
1101const PIN_GLYPH: &str = "\u{E011}";
1103
1104fn place_glyph(kind: PlaceKind) -> &'static str {
1109 match kind {
1110 PlaceKind::Home => "\u{2302}", PlaceKind::Documents => "\u{1F5CE}", PlaceKind::Downloads => "\u{2B07}", PlaceKind::Models | PlaceKind::Root => PIN_GLYPH,
1114 }
1115}
1116
1117fn sidebar_row<'a>(ui: &egui::Ui, caption: &'a str) -> egui::Button<'a> {
1121 crate::icon_text::icon_button(ui, caption).frame_when_inactive(false)
1122}
1123