1use std::fmt;
38use std::panic::{AssertUnwindSafe, catch_unwind};
39use std::path::{Path, PathBuf};
40use std::sync::{Arc, Mutex};
41
42use egui::Ui;
43pub use egui_pop_core::fold::IndentGuides;
44use egui_pop_core::fold::{Fold, GuideRow, TreeRow};
45use egui_pop_core::icon::{Size, Tone as IconTone};
46use egui_pop_core::kit::{Kit, KitCx, Part, State, Tone};
47use egui_pop_core::lock;
48use egui_pop_core::strings::StrKey;
49use egui_pop_core::theme::Tokens;
50use egui_pop_core::ui::{UiPop as _, tone_color};
51use egui_pop_core::{a11y, widgets};
52
53use crate::strings as txt;
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57pub enum SystemFolder {
58 Desktop,
59 Documents,
60 Downloads,
61 Pictures,
62 Music,
63 Videos,
64}
65
66impl SystemFolder {
67 pub const ALL: [SystemFolder; 6] = [
69 SystemFolder::Desktop,
70 SystemFolder::Documents,
71 SystemFolder::Downloads,
72 SystemFolder::Pictures,
73 SystemFolder::Music,
74 SystemFolder::Videos,
75 ];
76
77 pub fn title(self) -> &'static StrKey {
79 match self {
80 SystemFolder::Desktop => &txt::FILES_DESKTOP,
81 SystemFolder::Documents => &txt::FILES_DOCUMENTS,
82 SystemFolder::Downloads => &txt::FILES_DOWNLOADS,
83 SystemFolder::Pictures => &txt::FILES_PICTURES,
84 SystemFolder::Music => &txt::FILES_MUSIC,
85 SystemFolder::Videos => &txt::FILES_VIDEOS,
86 }
87 }
88
89 fn xdg_key(self) -> &'static str {
91 match self {
92 SystemFolder::Desktop => "DESKTOP",
93 SystemFolder::Documents => "DOCUMENTS",
94 SystemFolder::Downloads => "DOWNLOAD",
95 SystemFolder::Pictures => "PICTURES",
96 SystemFolder::Music => "MUSIC",
97 SystemFolder::Videos => "VIDEOS",
98 }
99 }
100
101 fn in_home(self) -> &'static str {
104 match self {
105 SystemFolder::Desktop => "Desktop",
106 SystemFolder::Documents => "Documents",
107 SystemFolder::Downloads => "Downloads",
108 SystemFolder::Pictures => "Pictures",
109 SystemFolder::Music => "Music",
110 SystemFolder::Videos if cfg!(target_os = "macos") => "Movies",
111 SystemFolder::Videos => "Videos",
112 }
113 }
114}
115
116#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct Volume {
119 pub name: String,
120 pub path: PathBuf,
121}
122
123#[derive(Clone, Debug, Default, PartialEq, Eq)]
125pub struct SystemPlaces {
126 pub folders: Vec<(SystemFolder, PathBuf)>,
128 pub volumes: Vec<Volume>,
130}
131
132pub fn system_places() -> SystemPlaces {
134 let Some(home) = super::home() else {
135 return SystemPlaces {
136 folders: Vec::new(),
137 volumes: volumes(),
138 };
139 };
140 let named = if cfg!(all(unix, not(target_os = "macos"))) {
141 let config = std::env::var_os("XDG_CONFIG_HOME")
142 .map(PathBuf::from)
143 .filter(|p| p.is_absolute())
144 .unwrap_or_else(|| home.join(".config"));
145 std::fs::read_to_string(config.join("user-dirs.dirs"))
146 .map(|text| xdg_user_dirs(&text, &home))
147 .ok()
148 } else {
149 None
150 };
151 let folders = named
152 .unwrap_or_else(|| {
153 SystemFolder::ALL
154 .iter()
155 .map(|f| (*f, home.join(f.in_home())))
156 .collect()
157 })
158 .into_iter()
159 .filter(|(_, p)| p != &home && p.is_dir())
160 .collect();
161 SystemPlaces {
162 folders,
163 volumes: volumes(),
164 }
165}
166
167#[derive(Clone, Debug, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct PlaceItem {
173 pub id: String,
175 pub name: String,
177 pub path: Option<PathBuf>,
179 pub icon: Option<String>,
182 pub icon_tip: Option<String>,
185 pub badge_icon: Option<PlaceBadgeIcon>,
189 pub image: Option<PlaceImage>,
193 pub detail: Option<String>,
195 pub badge: Option<String>,
197 pub badge_tone: Option<Tone>,
200 pub line: Option<String>,
204 pub toggle: Option<PlaceToggle>,
207 pub children: Vec<PlaceItem>,
211 pub open_at_first: bool,
214 pub open: Option<bool>,
218 pub dimmed: bool,
222 pub segments: Vec<PlaceSegment>,
227}
228
229#[derive(Clone, Debug, PartialEq, Eq)]
233#[non_exhaustive]
234pub struct PlaceSegment {
235 pub id: String,
238 pub label: String,
240 pub name: Option<String>,
242}
243
244impl PlaceSegment {
245 pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
246 Self {
247 id: id.into(),
248 label: label.into(),
249 name: None,
250 }
251 }
252
253 #[must_use]
255 pub fn name(mut self, name: impl Into<String>) -> Self {
256 self.name = Some(name.into());
257 self
258 }
259}
260
261pub const SEGMENT_SEPARATOR: &str = " / ";
263
264#[derive(Clone, Debug, PartialEq, Eq)]
267#[non_exhaustive]
268pub struct PlaceSegmentClick {
269 pub section: String,
271 pub item: PlaceItem,
273 pub index: usize,
275 pub id: String,
277}
278
279#[derive(Clone, Debug, PartialEq, Eq)]
281#[non_exhaustive]
282pub struct PlaceBadgeIcon {
283 pub icon: String,
285 pub tip: String,
287}
288
289#[derive(Clone, Debug)]
293pub struct PlaceImage(pub egui::ImageSource<'static>);
294
295impl PartialEq for PlaceImage {
296 fn eq(&self, other: &Self) -> bool {
297 match (&self.0, &other.0) {
298 (egui::ImageSource::Texture(a), egui::ImageSource::Texture(b)) => {
299 a.id == b.id && a.size == b.size
300 }
301 (a, b) => a.uri().is_some() && a.uri() == b.uri(),
302 }
303 }
304}
305
306impl Eq for PlaceImage {}
307
308#[derive(Clone, Debug, PartialEq, Eq)]
313#[non_exhaustive]
314pub struct PlaceToggle {
315 pub icon: String,
317 pub on: bool,
319 pub name: String,
321}
322
323impl PlaceToggle {
324 pub fn new(icon: impl Into<String>, on: bool, name: impl Into<String>) -> Self {
325 Self {
326 icon: icon.into(),
327 on,
328 name: name.into(),
329 }
330 }
331}
332
333impl PlaceItem {
334 pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
336 Self {
337 id: id.into(),
338 name: name.into(),
339 path: None,
340 icon: None,
341 icon_tip: None,
342 badge_icon: None,
343 image: None,
344 detail: None,
345 badge: None,
346 badge_tone: None,
347 line: None,
348 toggle: None,
349 children: Vec::new(),
350 open_at_first: false,
351 open: None,
352 dimmed: false,
353 segments: Vec::new(),
354 }
355 }
356
357 pub fn folder(name: impl Into<String>, path: impl Into<PathBuf>) -> Self {
359 let path = path.into();
360 Self {
361 path: Some(path.clone()),
362 ..Self::new(path.display().to_string(), name)
363 }
364 }
365
366 #[must_use]
367 pub fn path(mut self, path: impl Into<PathBuf>) -> Self {
368 self.path = Some(path.into());
369 self
370 }
371
372 #[must_use]
373 pub fn icon(mut self, icon: impl Into<String>) -> Self {
374 self.icon = Some(icon.into());
375 self
376 }
377
378 #[must_use]
381 pub fn icon_tip(mut self, tip: impl Into<String>) -> Self {
382 self.icon_tip = Some(tip.into());
383 self
384 }
385
386 #[must_use]
394 pub fn badge_icon(mut self, icon: impl Into<String>, tip: impl Into<String>) -> Self {
395 self.badge_icon = Some(PlaceBadgeIcon {
396 icon: icon.into(),
397 tip: tip.into(),
398 });
399 self
400 }
401
402 #[must_use]
411 pub fn image(mut self, image: impl Into<egui::ImageSource<'static>>) -> Self {
412 self.image = Some(PlaceImage(image.into()));
413 self
414 }
415
416 #[must_use]
417 pub fn detail(mut self, detail: impl Into<String>) -> Self {
418 self.detail = Some(detail.into());
419 self
420 }
421
422 #[must_use]
423 pub fn badge(mut self, badge: impl Into<String>) -> Self {
424 self.badge = Some(badge.into());
425 self
426 }
427
428 #[must_use]
430 pub fn badge_tone(mut self, tone: Tone) -> Self {
431 self.badge_tone = Some(tone);
432 self
433 }
434
435 #[must_use]
437 pub fn line(mut self, line: impl Into<String>) -> Self {
438 self.line = Some(line.into());
439 self
440 }
441
442 #[must_use]
444 pub fn toggle(mut self, toggle: PlaceToggle) -> Self {
445 self.toggle = Some(toggle);
446 self
447 }
448
449 #[must_use]
458 pub fn children(mut self, children: impl IntoIterator<Item = PlaceItem>) -> Self {
459 self.children.extend(children);
460 self
461 }
462
463 #[must_use]
466 pub fn open_at_first(mut self, open: bool) -> Self {
467 self.open_at_first = open;
468 self
469 }
470
471 #[must_use]
474 pub fn open(mut self, open: bool) -> Self {
475 self.open = Some(open);
476 self
477 }
478
479 #[must_use]
484 pub fn dimmed(mut self, dimmed: bool) -> Self {
485 self.dimmed = dimmed;
486 self
487 }
488
489 #[must_use]
501 pub fn segments(mut self, segments: impl IntoIterator<Item = PlaceSegment>) -> Self {
502 self.segments.extend(segments);
503 self
504 }
505
506 pub fn said(&self) -> String {
508 match &self.badge {
509 Some(b) => format!("{}, {b}", self.name),
510 None => self.name.clone(),
511 }
512 }
513}
514
515#[derive(Clone, Debug, PartialEq, Eq)]
519#[non_exhaustive]
520pub struct PlaceSection {
521 pub id: String,
523 pub title: String,
524 pub items: Vec<PlaceItem>,
525 pub fold: Option<bool>,
528 pub open: Option<bool>,
532 pub empty: Option<String>,
535 pub keep: bool,
538 pub untitled: bool,
542}
543
544impl PlaceSection {
545 pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
546 Self {
547 id: id.into(),
548 title: title.into(),
549 items: Vec::new(),
550 fold: None,
551 open: None,
552 empty: None,
553 keep: false,
554 untitled: false,
555 }
556 }
557
558 pub fn untitled(id: impl Into<String>, name: impl Into<String>) -> Self {
567 Self {
568 untitled: true,
569 ..Self::new(id, name)
570 }
571 }
572
573 #[must_use]
577 pub fn foldable(mut self, open_at_first: bool) -> Self {
578 self.fold = Some(open_at_first);
579 self
580 }
581
582 #[must_use]
585 pub fn open(mut self, open: bool) -> Self {
586 self.fold.get_or_insert(open);
587 self.open = Some(open);
588 self
589 }
590
591 #[must_use]
593 pub fn empty(mut self, line: impl Into<String>) -> Self {
594 self.empty = Some(line.into());
595 self
596 }
597
598 #[must_use]
601 pub fn keep(mut self) -> Self {
602 self.keep = true;
603 self
604 }
605
606 pub fn shown(&self) -> bool {
608 !self.items.is_empty() || self.empty.is_some() || self.keep
609 }
610
611 #[must_use]
613 pub fn item(mut self, item: PlaceItem) -> Self {
614 self.items.push(item);
615 self
616 }
617
618 #[must_use]
620 pub fn items(mut self, items: impl IntoIterator<Item = PlaceItem>) -> Self {
621 self.items.extend(items);
622 self
623 }
624}
625
626pub trait PlaceProvider: fmt::Debug + Send + Sync {
631 fn id(&self) -> &str;
633
634 fn sections(&self) -> Vec<PlaceSection>;
636}
637
638#[derive(Clone, Debug, Default)]
640pub struct PlaceProviders(Arc<Mutex<Vec<Arc<dyn PlaceProvider>>>>);
641
642impl PlaceProviders {
643 pub fn register(&self, provider: Arc<dyn PlaceProvider>) {
647 let mut list = lock(&self.0);
648 list.retain(|p| p.id() != provider.id());
649 list.push(provider);
650 }
651
652 pub fn unregister(&self, id: &str) -> bool {
654 let mut list = lock(&self.0);
655 let before = list.len();
656 list.retain(|p| p.id() != id);
657 list.len() != before
658 }
659
660 pub fn ids(&self) -> Vec<String> {
662 lock(&self.0).iter().map(|p| p.id().to_string()).collect()
663 }
664
665 pub fn sections(&self) -> Vec<PlaceSection> {
669 let list = lock(&self.0).clone();
670 let mut out = Vec::new();
671 for provider in list {
672 match catch_unwind(AssertUnwindSafe(|| provider.sections())) {
673 Ok(sections) => out.extend(sections.into_iter().filter(PlaceSection::shown)),
674 Err(_) => {
675 log::warn!(target: "egui_pop", "files: the place provider {} panicked", provider.id());
676 }
677 }
678 }
679 out
680 }
681}
682
683fn paint_image(ui: &Ui, image: &PlaceImage, square: egui::Rect, muted: bool) -> bool {
688 let poll = egui::Image::new(image.0.clone()).load_for_size(ui.ctx(), square.size());
689 let Ok(egui::load::TexturePoll::Ready { texture }) = poll else {
690 return false;
691 };
692 let t = Tokens::of(ui.ctx());
693 let radius = t.radius.widget.min(square.width() / 4.0).max(0.0);
694 let tint = if muted {
695 egui::Color32::WHITE.gamma_multiply(0.5)
696 } else {
697 egui::Color32::WHITE
698 };
699 egui::Image::from_texture(texture)
700 .uv(cover_uv(texture.size))
701 .corner_radius(egui::CornerRadius::same(radius.round() as u8))
702 .tint(tint)
703 .paint_at(ui, square);
704 true
705}
706
707fn cover_uv(size: egui::Vec2) -> egui::Rect {
710 let full = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0));
711 if size.x <= 0.0 || size.y <= 0.0 {
712 return full;
713 }
714 let (w, h) = if size.x > size.y {
715 (size.y / size.x, 1.0)
716 } else {
717 (1.0, size.x / size.y)
718 };
719 egui::Rect::from_center_size(egui::pos2(0.5, 0.5), egui::vec2(w, h))
720}
721
722pub(crate) fn section_title(ui: &mut Ui, title: &str) -> egui::Response {
724 let r = ui.weak(title);
725 a11y::name(&r, egui::Role::Heading, title);
726 r
727}
728
729pub(crate) fn place_row(ui: &mut Ui, item: &PlaceItem, selected: bool) -> egui::Response {
732 let icon = item
733 .icon
734 .as_deref()
735 .map(|name| egui_pop_core::icon::registry::resolve(name, "files.places"));
736 let row = |ui: &mut Ui| match &item.badge {
737 Some(badge) => ui.add(
738 widgets::SelectableRow::new(
739 selected,
740 (
741 item.name.as_str(),
742 egui::RichText::new(badge.as_str()).small().weak(),
743 ),
744 )
745 .name(item.said()),
746 ),
747 None => widgets::selectable_label(ui, selected, item.name.as_str()),
748 };
749 let r = if icon.is_some() || item.image.is_some() {
750 ui.horizontal(|ui| {
751 let side = ui.spacing().interact_size.y;
752 let (rect, _) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());
753 let colour = ui.visuals().text_color();
754 let at = rect.shrink(side * 0.2);
755 let drawn = item
756 .image
757 .as_ref()
758 .is_some_and(|image| paint_image(ui, image, at, false));
759 if !drawn && let Some(icon) = icon {
760 icon.unwrap_or(egui_pop_core::icon::PLACEHOLDER)
761 .paint(ui.painter(), at, colour);
762 }
763 row(ui)
764 })
765 .inner
766 } else {
767 row(ui)
768 };
769 let tip = item
770 .detail
771 .clone()
772 .or_else(|| item.path.as_ref().map(|p| p.display().to_string()));
773 match tip {
774 Some(tip) => r.on_hover_text(tip),
775 None => r,
776 }
777}
778
779#[derive(Clone, Debug, Default, PartialEq, Eq)]
781#[non_exhaustive]
782pub struct PlacesOutput {
783 pub chosen: Option<(String, PlaceItem)>,
786 pub toggled: Option<(String, PlaceItem)>,
789 pub folded: Option<(String, bool)>,
792 pub expanded: Option<(String, bool)>,
795 pub segment: Option<PlaceSegmentClick>,
798}
799
800type PlaceMenu<'a> = Box<dyn FnMut(&mut Ui, &PlaceSection, &PlaceItem) + 'a>;
803
804type SectionSlot<'a> = Box<dyn FnMut(&mut Ui, &PlaceSection) + 'a>;
807
808type RowHook<'a> = Box<dyn FnMut(&mut Ui, &PlaceSection, &PlaceItem, &egui::Response) + 'a>;
810
811pub struct PlacesPanel<'a> {
846 name: String,
847 sections: &'a [PlaceSection],
848 selected: Option<&'a str>,
849 selected_set: &'a [&'a str],
850 menu: Option<PlaceMenu<'a>>,
851 under_item: Option<PlaceMenu<'a>>,
852 under_section: Option<SectionSlot<'a>>,
853 on_row: Option<RowHook<'a>>,
854 indent_guides: IndentGuides,
855 guide_highlight: bool,
856 guide_rows: Vec<Vec<GuideRow>>,
858}
859
860impl fmt::Debug for PlacesPanel<'_> {
861 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
862 f.debug_struct("PlacesPanel")
863 .field("name", &self.name)
864 .field("sections", &self.sections.len())
865 .field("selected", &self.selected)
866 .field("selected_set", &self.selected_set)
867 .field("indent_guides", &self.indent_guides)
868 .field("guide_highlight", &self.guide_highlight)
869 .finish_non_exhaustive()
870 }
871}
872
873impl<'a> PlacesPanel<'a> {
874 pub fn new(name: impl Into<String>, sections: &'a [PlaceSection]) -> Self {
877 Self {
878 name: name.into(),
879 sections,
880 selected: None,
881 selected_set: &[],
882 menu: None,
883 under_item: None,
884 under_section: None,
885 on_row: None,
886 indent_guides: IndentGuides::Never,
887 guide_highlight: false,
888 guide_rows: Vec::new(),
889 }
890 }
891
892 #[must_use]
900 pub fn indent_guides(mut self, mode: IndentGuides) -> Self {
901 self.indent_guides = mode;
902 self
903 }
904
905 #[must_use]
909 pub fn indent_guide_highlight(mut self, on: bool) -> Self {
910 self.guide_highlight = on;
911 self
912 }
913
914 #[must_use]
916 pub fn selected(mut self, id: Option<&'a str>) -> Self {
917 self.selected = id;
918 self
919 }
920
921 #[must_use]
927 pub fn selected_set(mut self, ids: &'a [&'a str]) -> Self {
928 self.selected_set = ids;
929 self
930 }
931
932 #[must_use]
940 pub fn on_row(
941 mut self,
942 hook: impl FnMut(&mut Ui, &PlaceSection, &PlaceItem, &egui::Response) + 'a,
943 ) -> Self {
944 self.on_row = Some(Box::new(hook));
945 self
946 }
947
948 #[must_use]
950 pub fn menu(mut self, menu: impl FnMut(&mut Ui, &PlaceSection, &PlaceItem) + 'a) -> Self {
951 self.menu = Some(Box::new(menu));
952 self
953 }
954
955 #[must_use]
960 pub fn under_item(mut self, add: impl FnMut(&mut Ui, &PlaceSection, &PlaceItem) + 'a) -> Self {
961 self.under_item = Some(Box::new(add));
962 self
963 }
964
965 #[must_use]
970 pub fn under_section(mut self, add: impl FnMut(&mut Ui, &PlaceSection) + 'a) -> Self {
971 self.under_section = Some(Box::new(add));
972 self
973 }
974
975 pub fn show(mut self, ui: &mut Ui) -> PlacesOutput {
976 let mut out = PlacesOutput::default();
977 let t = Tokens::of(ui.ctx());
978 let sections = self.sections;
979 let name = self.name.clone();
980 egui_pop_core::tab::roving(ui, &name, egui_pop_core::tab::Axis::Vertical, |ui| {
981 let panel = ui.vertical(|ui| {
982 for (n, section) in sections.iter().filter(|s| s.shown()).enumerate() {
983 if n > 0 {
984 ui.add_space(t.space.s);
985 }
986 match section.fold {
987 _ if section.untitled => {
988 ui.scope_builder(
991 egui::UiBuilder::new()
992 .id_salt(("untitled", §ion.id))
993 .accessibility_role(egui::accesskit::Role::Group)
994 .accessibility_label(section.title.clone()),
995 |ui| self.section_body(ui, section, &mut out),
996 );
997 }
998 None => {
999 section_title(ui, §ion.title);
1000 self.section_body(ui, section, &mut out);
1001 }
1002 Some(at_first) => {
1003 let open_wanted = section.open;
1004 let fold = Fold::new((&name, §ion.id), section.title.as_str())
1005 .default_open(open_wanted.unwrap_or(at_first))
1006 .show(ui, |ui| self.section_body(ui, section, &mut out));
1007 if fold.toggled {
1008 out.folded = Some((section.id.clone(), fold.open));
1009 } else if let Some(want) = open_wanted
1010 && want != fold.open
1011 {
1012 egui_pop_core::fold::set_open(ui.ctx(), fold.id, want);
1014 }
1015 }
1016 }
1017 }
1018 });
1019 if self.indent_guides != IndentGuides::Never {
1020 for rows in std::mem::take(&mut self.guide_rows) {
1021 self.indent_guides
1022 .paint(ui, panel.response.rect, &rows, self.guide_highlight);
1023 }
1024 }
1025 });
1026 out
1027 }
1028
1029 fn section_body(&mut self, ui: &mut Ui, section: &PlaceSection, out: &mut PlacesOutput) {
1031 if section.items.is_empty()
1032 && let Some(empty) = §ion.empty
1033 {
1034 ui.meta(empty.as_str());
1035 }
1036 let tree = section.items.iter().any(|i| !i.children.is_empty());
1039 if tree {
1040 self.guide_rows.push(Vec::new());
1041 }
1042 for item in §ion.items {
1043 self.item(ui, section, item, tree.then_some(0), out);
1044 }
1045 if let Some(add) = self.under_section.as_mut() {
1046 ui.push_id(("under", §ion.id), |ui| add(ui, section));
1047 }
1048 }
1049
1050 fn is_selected(&self, id: &str) -> bool {
1052 self.selected == Some(id) || self.selected_set.contains(&id)
1053 }
1054
1055 fn item(
1058 &mut self,
1059 ui: &mut Ui,
1060 section: &PlaceSection,
1061 item: &PlaceItem,
1062 depth: Option<usize>,
1063 out: &mut PlacesOutput,
1064 ) {
1065 let on = self.is_selected(&item.id);
1066 let ctx = ui.ctx().clone();
1067 let open_id = ui.make_persistent_id(("place.open", §ion.id, &item.id));
1068 ui.push_id((§ion.id, &item.id), |ui| {
1069 let segment;
1070 let (r, toggled, open) = match depth {
1071 None => {
1072 let (r, toggled, clicked) = item_row(ui, item, on);
1073 segment = clicked;
1074 (r, toggled, false)
1075 }
1076 Some(depth) => {
1077 let branch = !item.children.is_empty();
1078 if let Some(want) = item.open
1079 && branch
1080 && egui_pop_core::fold::is_open(&ctx, open_id) != Some(want)
1081 {
1082 egui_pop_core::fold::set_open(&ctx, open_id, want);
1084 }
1085 let shown = TreeRow::new(open_id, item.name.clone())
1086 .depth(depth)
1087 .leaf(!branch)
1088 .default_open(item.open.unwrap_or(item.open_at_first))
1089 .show(ui, |ui| item_row(ui, item, on));
1090 let (r, toggled, clicked) = shown.row.inner.clone();
1091 segment = clicked;
1092 if let Some(rows) = self.guide_rows.last_mut() {
1093 rows.push(GuideRow {
1094 depth,
1095 rect: shown.row.response.rect,
1096 });
1097 }
1098 let mut open = shown.open;
1099 let mut expanded = shown.toggled;
1100 shown.keep(&ctx);
1101 if branch && r.has_focus() {
1104 ui.memory_mut(|m| {
1105 m.set_focus_lock_filter(
1106 r.id,
1107 egui::EventFilter {
1108 horizontal_arrows: true,
1109 ..Default::default()
1110 },
1111 );
1112 });
1113 let key = if open {
1114 egui::Key::ArrowLeft
1115 } else {
1116 egui::Key::ArrowRight
1117 };
1118 if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key)) {
1119 open = !open;
1120 expanded = true;
1121 egui_pop_core::fold::set_open(&ctx, open_id, open);
1122 }
1123 }
1124 ctx.accesskit_node_builder(r.id, |node| {
1125 node.set_level(depth + 1);
1126 if branch {
1127 node.set_expanded(open);
1128 }
1129 });
1130 if expanded {
1131 out.expanded = Some((item.id.clone(), open));
1132 }
1133 (r, toggled, open)
1134 }
1135 };
1136 if r.clicked() {
1138 out.chosen = Some((section.id.clone(), item.clone()));
1139 }
1140 if toggled {
1141 out.toggled = Some((section.id.clone(), item.clone()));
1142 }
1143 if let Some(index) = segment
1144 && let Some(s) = item.segments.get(index)
1145 {
1146 out.segment = Some(PlaceSegmentClick {
1147 section: section.id.clone(),
1148 item: item.clone(),
1149 index,
1150 id: s.id.clone(),
1151 });
1152 }
1153 if let Some(menu) = self.menu.as_mut() {
1154 egui_pop_core::pointer::claim::context_menu(&r, |ui| {
1155 menu(ui, section, item);
1156 });
1157 }
1158 if let Some(hook) = self.on_row.as_mut() {
1159 hook(ui, section, item, &r);
1160 }
1161 if let Some(add) = self.under_item.as_mut() {
1162 add(ui, section, item);
1163 }
1164 if open && let Some(depth) = depth {
1165 for child in &item.children {
1166 self.item(ui, section, child, Some(depth + 1), out);
1167 }
1168 }
1169 });
1170 }
1171}
1172
1173fn item_row(
1179 ui: &mut Ui,
1180 item: &PlaceItem,
1181 selected: bool,
1182) -> (egui::Response, bool, Option<usize>) {
1183 if item.line.is_none()
1184 && item.toggle.is_none()
1185 && !item.dimmed
1186 && item.badge_icon.is_none()
1187 && item.icon_tip.is_none()
1188 && item.segments.is_empty()
1189 {
1190 return (place_row(ui, item, selected), false, None);
1191 }
1192 let ctx = ui.ctx().clone();
1193 let t = Tokens::of(&ctx);
1194 let kit = Kit::of(&ctx);
1195 let component = &kit.selectable_row;
1196 let body = egui::TextStyle::Body.resolve(ui.style());
1197 let small = egui::FontId::proportional(t.text_role.meta.size.max(4.0));
1198 let room = component.border_room(ctx.pixels_per_point());
1199 let pad = ui.spacing().button_padding.max(egui::Vec2::splat(room));
1200 let gap = ui.spacing().item_spacing.x;
1201 let line_h = if item.line.is_some() {
1202 ui.fonts_mut(|f| f.row_height(&small))
1203 } else {
1204 0.0
1205 };
1206 let height = (ui.fonts_mut(|f| f.row_height(&body)) + line_h + 2.0 * pad.y)
1207 .max(ui.spacing().interact_size.y);
1208 let toggle_side = Size::Inline.points(&t) + 2.0 * room;
1209 let width = ui.available_width().max(toggle_side * 3.0);
1210 let (rect, r) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::click());
1211 let enabled = ui.is_enabled();
1212 let said = item.said();
1213 r.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, selected, &said));
1214 let tip = item
1216 .detail
1217 .clone()
1218 .or_else(|| item.path.as_ref().map(|p| p.display().to_string()));
1219 let icon_tips = [
1222 item.icon_tip.clone(),
1223 item.badge_icon.as_ref().map(|b| b.tip.clone()),
1224 ]
1225 .into_iter()
1226 .flatten()
1227 .filter(|tip| !tip.is_empty())
1228 .collect::<Vec<_>>();
1229 let description = match (&item.line, item.dimmed) {
1230 (Some(line), false) => Some(line.clone()),
1231 (line, true) => {
1236 let word = egui_pop_core::strings::tr(&ctx, &txt::FILES_PLACE_DIMMED);
1237 let said = [Some(word), line.clone(), tip.clone()]
1238 .into_iter()
1239 .flatten()
1240 .filter(|part| !part.is_empty())
1241 .collect::<Vec<_>>();
1242 Some(said.join(", "))
1243 }
1244 (None, false) => None,
1245 };
1246 let description = (!icon_tips.is_empty() || description.is_some()).then(|| {
1247 icon_tips
1248 .iter()
1249 .cloned()
1250 .chain(description)
1251 .collect::<Vec<_>>()
1252 .join(", ")
1253 });
1254 if let Some(description) = description {
1255 ctx.accesskit_node_builder(r.id, |node| node.set_description(description));
1256 }
1257 if let Some(cursor) = ui.visuals().interact_cursor
1258 && r.hovered()
1259 {
1260 ctx.set_cursor_icon(cursor);
1261 }
1262 let icon_side = Size::Inline.points(&t);
1266 let toggle_rect = item.toggle.as_ref().map(|_| {
1267 egui::Rect::from_center_size(
1268 egui::pos2(
1269 rect.right() - pad.x - toggle_side / 2.0,
1270 rect.center().y + (pad.y / 2.0).max(1.0),
1271 ),
1272 egui::Vec2::splat(icon_side),
1273 )
1274 });
1275 let has_icon = item.icon.is_some() || item.image.is_some() || item.badge_icon.is_some();
1277 let icon_at = has_icon.then(|| {
1278 let side = ui.spacing().interact_size.y;
1279 egui::Rect::from_min_size(
1280 egui::pos2(rect.left() + pad.x, rect.center().y - side / 2.0),
1281 egui::Vec2::splat(side),
1282 )
1283 });
1284 let badge_at = match (&item.badge_icon, icon_at) {
1285 (Some(_), Some(at)) if item.icon.is_some() || item.image.is_some() => {
1286 let side = at.width() * 0.5;
1287 Some(egui::Rect::from_min_size(
1288 at.max - egui::Vec2::splat(side + at.width() * 0.04),
1289 egui::Vec2::splat(side),
1290 ))
1291 }
1292 (Some(_), Some(at)) => Some(at.shrink(at.width() * 0.2)),
1293 _ => None,
1294 };
1295 let text_left = icon_at.map_or(rect.left() + pad.x, |at| at.right() + gap);
1296 let text_right = toggle_rect.map_or(rect.right() - pad.x, |_| {
1297 rect.right() - pad.x - toggle_side - gap
1298 });
1299 let text_top = rect.top() + pad.y;
1300 let segments = segment_parts(ui, item, &body, egui::pos2(text_left, text_top), text_right);
1301 let mut segment_clicked = None;
1302 let mut segment_hovered = false;
1303 let mut chain = String::new();
1304 let segment_responses = segments
1305 .iter()
1306 .map(|part| {
1307 let seg = &item.segments[part.index];
1308 if part.index > 0 {
1309 chain.push_str(SEGMENT_SEPARATOR);
1310 }
1311 chain.push_str(&seg.label);
1312 let s = ui.interact(
1313 part.rect,
1314 r.id.with(("segment", part.index)),
1315 egui::Sense::CLICK,
1316 );
1317 let name = seg.name.clone().unwrap_or_else(|| chain.clone());
1318 s.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Link, enabled, &name));
1319 if s.clicked() {
1320 segment_clicked = Some(part.index);
1321 }
1322 segment_hovered |= s.hovered();
1323 s
1324 })
1325 .collect::<Vec<_>>();
1326 if segment_hovered && let Some(cursor) = ui.visuals().interact_cursor {
1327 ctx.set_cursor_icon(cursor);
1328 }
1329 if ui.is_rect_visible(rect) {
1330 let state = State::from_response(&r)
1334 .with(State::HOVER, r.hovered() || segment_hovered)
1335 .with(State::SELECTED, selected)
1336 .with(State::DISABLED, !enabled);
1337 let state = if selected {
1338 state.without(State::HOVER)
1339 } else {
1340 state
1341 };
1342 let cx = KitCx {
1343 painter: ui.painter(),
1344 ppp: ctx.pixels_per_point(),
1345 };
1346 component.paint(
1347 &cx,
1348 &Part {
1349 rect,
1350 room: rect,
1351 state,
1352 label: None,
1353 },
1354 );
1355 let muted = item.dimmed && !selected;
1356 let text = if muted {
1357 t.text_role.muted.color
1358 } else {
1359 ui.visuals()
1360 .override_text_color
1361 .unwrap_or(component.style(state).text)
1362 };
1363 let painter = ui.painter_at(rect);
1364 let left = text_left;
1365 let right = text_right;
1366 if let Some(at) = icon_at {
1367 let side = at.width();
1368 let drawn = item
1369 .image
1370 .as_ref()
1371 .is_some_and(|image| paint_image(ui, image, at.shrink(side * 0.2), muted));
1372 if !drawn && let Some(name) = &item.icon {
1373 egui_pop_core::icon::registry::resolve(name, "files.places")
1374 .unwrap_or(egui_pop_core::icon::PLACEHOLDER)
1375 .paint(&painter, at.shrink(side * 0.2), text);
1376 }
1377 if let (Some(badge), Some(b)) = (&item.badge_icon, badge_at) {
1378 if item.icon.is_some() || item.image.is_some() {
1381 let fill = component.style(state).fill;
1382 let behind = if fill.a() == 255 {
1383 fill
1384 } else {
1385 ui.visuals().panel_fill
1386 };
1387 painter.circle_filled(b.center(), b.width() * 0.62, behind);
1388 }
1389 egui_pop_core::icon::registry::resolve(&badge.icon, "files.places")
1390 .unwrap_or(egui_pop_core::icon::PLACEHOLDER)
1391 .paint(&painter, b, text);
1392 }
1393 }
1394 let one_line = |s: &str, font: egui::FontId, colour: egui::Color32, max: f32| {
1395 let mut job = egui::text::LayoutJob::simple_singleline(s.to_owned(), font, colour);
1396 job.wrap = egui::text::TextWrapping::truncate_at_width(max.max(0.0));
1397 ui.fonts_mut(|f| f.layout_job(job))
1398 };
1399 let top = text_top;
1400 let (name_w, name_h) = if segments.is_empty() {
1401 let name = one_line(&item.name, body.clone(), text, right - left);
1402 let size = name.size();
1403 painter.galley(egui::pos2(left, top), name, text);
1404 (size.x, size.y)
1405 } else {
1406 let clip = ui.painter_at(egui::Rect::from_x_y_ranges(left..=right, rect.y_range()));
1409 let mut end = left;
1410 let mut height = 0.0_f32;
1411 for (part, s) in segments.iter().zip(&segment_responses) {
1412 if let Some((at, sep)) = &part.separator {
1413 clip.galley(*at, sep.clone(), text);
1414 }
1415 clip.galley(part.rect.min, part.galley.clone(), text);
1416 if s.hovered() {
1417 let y = part.rect.bottom() - 1.0;
1418 clip.hline(part.rect.x_range(), y, egui::Stroke::new(1.0, text));
1419 }
1420 end = part.rect.right();
1421 height = height.max(part.rect.height());
1422 }
1423 (end - left, height)
1424 };
1425 let badge_colour = |tone: Option<Tone>| match tone {
1426 _ if muted => text,
1427 Some(tone) => tone_color(&t, tone),
1428 None if selected => text,
1429 None => t.text_role.meta.color,
1430 };
1431 let line_colour = if selected || muted {
1432 text
1433 } else {
1434 t.text_role.meta.color
1435 };
1436 match &item.line {
1437 Some(line) => {
1439 let y = top + name_h;
1440 let mut x = left;
1441 if let Some(badge) = &item.badge {
1442 let g = one_line(
1443 badge,
1444 small.clone(),
1445 badge_colour(item.badge_tone),
1446 right - x,
1447 );
1448 let w = g.size().x;
1449 painter.galley(egui::pos2(x, y), g, text);
1450 x += w + gap;
1451 }
1452 let g = one_line(line, small.clone(), line_colour, right - x);
1453 painter.galley(egui::pos2(x, y), g, text);
1454 }
1455 None => {
1456 if let Some(badge) = &item.badge {
1457 let x = left + name_w + gap;
1458 let g = one_line(
1459 badge,
1460 small.clone(),
1461 badge_colour(item.badge_tone),
1462 right - x,
1463 );
1464 let y = top + (name_h - g.size().y) / 2.0;
1465 painter.galley(egui::pos2(x, y), g, text);
1466 }
1467 }
1468 }
1469 }
1470 let pointer = r.hover_pos();
1473 let on = |at: Option<egui::Rect>| at.zip(pointer).is_some_and(|(a, p)| a.contains(p));
1474 let tip = if on(badge_at) {
1475 item.badge_icon.as_ref().map(|b| b.tip.clone())
1476 } else if on(icon_at) && item.icon_tip.is_some() {
1477 item.icon_tip.clone()
1478 } else {
1479 tip
1480 };
1481 let r = match tip {
1482 Some(tip) => r.on_hover_text(tip),
1483 None => r,
1484 };
1485 let mut toggled = false;
1486 if let (Some(toggle), Some(at)) = (&item.toggle, toggle_rect) {
1487 let icon = egui_pop_core::icon::registry::resolve(&toggle.icon, "files.places")
1488 .unwrap_or(egui_pop_core::icon::PLACEHOLDER);
1489 let tone = if toggle.on {
1490 IconTone::Accent
1491 } else {
1492 IconTone::Muted
1493 };
1494 let b = ui.put(
1495 at,
1496 icon.size(Size::Inline)
1497 .tone(tone)
1498 .label(&toggle.name)
1499 .selected(toggle.on),
1500 );
1501 toggled = b.clicked();
1502 }
1503 (r, toggled, segment_clicked)
1504}
1505
1506struct SegmentPart {
1509 index: usize,
1510 rect: egui::Rect,
1511 galley: Arc<egui::Galley>,
1512 separator: Option<(egui::Pos2, Arc<egui::Galley>)>,
1513}
1514
1515fn segment_parts(
1518 ui: &Ui,
1519 item: &PlaceItem,
1520 font: &egui::FontId,
1521 at: egui::Pos2,
1522 right: f32,
1523) -> Vec<SegmentPart> {
1524 let lay = |s: &str| {
1525 let job = egui::text::LayoutJob::simple_singleline(
1526 s.to_owned(),
1527 font.clone(),
1528 egui::Color32::PLACEHOLDER,
1529 );
1530 ui.fonts_mut(|f| f.layout_job(job))
1531 };
1532 let mut x = at.x;
1533 let mut out = Vec::new();
1534 for (index, seg) in item.segments.iter().enumerate() {
1535 let separator = (index > 0).then(|| {
1536 let g = lay(SEGMENT_SEPARATOR);
1537 let pos = egui::pos2(x, at.y);
1538 x += g.size().x;
1539 (pos, g)
1540 });
1541 if x >= right {
1542 break;
1543 }
1544 let galley = lay(&seg.label);
1545 let size = galley.size();
1546 let rect = egui::Rect::from_min_size(egui::pos2(x, at.y), size);
1547 let rect = rect.with_max_x(rect.right().min(right));
1548 x += size.x;
1549 out.push(SegmentPart {
1550 index,
1551 rect,
1552 galley,
1553 separator,
1554 });
1555 }
1556 out
1557}
1558
1559pub fn xdg_user_dirs(text: &str, home: &Path) -> Vec<(SystemFolder, PathBuf)> {
1563 let value = |key: &str| {
1564 text.lines().find_map(|line| {
1565 let rest = line.trim().strip_prefix("XDG_")?.strip_prefix(key)?;
1566 let quoted = rest.strip_prefix("_DIR=")?.trim();
1567 let v = quoted.strip_prefix('"')?.strip_suffix('"')?;
1568 let path = if let Some(r) = v.strip_prefix("$HOME") {
1569 let r = r.trim_start_matches('/');
1570 if r.is_empty() {
1571 home.to_path_buf()
1572 } else {
1573 home.join(r)
1574 }
1575 } else if v.starts_with('/') {
1576 PathBuf::from(v)
1577 } else {
1578 return None;
1579 };
1580 Some(path)
1581 })
1582 };
1583 SystemFolder::ALL
1584 .iter()
1585 .filter_map(|f| value(f.xdg_key()).map(|p| (*f, p)))
1586 .filter(|(_, p)| p != home)
1587 .collect()
1588}
1589
1590fn volumes() -> Vec<Volume> {
1592 let mut out = if cfg!(target_os = "macos") {
1593 mac_volumes()
1594 } else if cfg!(windows) {
1595 drives()
1596 } else if cfg!(unix) {
1597 unix_volumes()
1598 } else {
1599 Vec::new()
1600 };
1601 let mut seen = std::collections::HashSet::new();
1603 out.retain(|v| seen.insert(v.path.clone()));
1604 out.sort_by_key(|v| v.name.to_lowercase());
1605 out
1606}
1607
1608fn named(path: PathBuf) -> Volume {
1609 let name = path
1610 .file_name()
1611 .map(|n| n.to_string_lossy().into_owned())
1612 .unwrap_or_else(|| path.display().to_string());
1613 Volume { name, path }
1614}
1615
1616fn subfolders(dir: &Path) -> Vec<PathBuf> {
1617 std::fs::read_dir(dir)
1618 .map(|r| {
1619 r.filter_map(Result::ok)
1620 .map(|e| e.path())
1621 .filter(|p| p.is_dir())
1622 .collect()
1623 })
1624 .unwrap_or_default()
1625}
1626
1627#[cfg(unix)]
1630fn unix_volumes() -> Vec<Volume> {
1631 use std::os::unix::fs::MetadataExt as _;
1632 let user = std::env::var("USER").unwrap_or_default();
1633 let mut bases = Vec::new();
1634 if !user.is_empty() {
1635 bases.push(Path::new("/run/media").join(&user));
1636 bases.push(Path::new("/media").join(&user));
1637 }
1638 bases.push(PathBuf::from("/media"));
1639 bases.push(PathBuf::from("/mnt"));
1640 let mut out = Vec::new();
1641 for base in bases {
1642 let Ok(parent) = std::fs::metadata(&base) else {
1643 continue;
1644 };
1645 for p in subfolders(&base) {
1646 if std::fs::metadata(&p).is_ok_and(|m| m.dev() != parent.dev()) {
1647 out.push(named(p));
1648 }
1649 }
1650 }
1651 out
1652}
1653
1654#[cfg(not(unix))]
1655fn unix_volumes() -> Vec<Volume> {
1656 Vec::new()
1657}
1658
1659fn mac_volumes() -> Vec<Volume> {
1661 subfolders(Path::new("/Volumes"))
1662 .into_iter()
1663 .filter(|p| !std::fs::read_link(p).is_ok_and(|to| to == Path::new("/")))
1664 .map(named)
1665 .collect()
1666}
1667
1668fn drives() -> Vec<Volume> {
1670 (b'C'..=b'Z')
1671 .map(|l| PathBuf::from(format!("{}:\\", l as char)))
1672 .filter(|p| p.is_dir())
1673 .map(|path| Volume {
1674 name: path.display().to_string().trim_end_matches('\\').to_owned(),
1675 path,
1676 })
1677 .collect()
1678}
1679
1680#[cfg(test)]
1681mod tests {
1682 use super::*;
1683
1684 #[test]
1685 fn an_image_that_does_not_load_leaves_the_icon_to_draw() {
1686 let ctx = egui::Context::default();
1687 let square = egui::Rect::from_min_size(egui::pos2(4.0, 4.0), egui::Vec2::splat(16.0));
1688 let mut drawn = (true, false);
1689 let mut out = ctx.run_ui(Default::default(), |ui| {
1690 let missing = PlaceImage(egui::ImageSource::Uri("bytes://missing.png".into()));
1692 drawn.0 = paint_image(ui, &missing, square, false);
1693 let texture = ui.ctx().load_texture(
1694 "places.test",
1695 egui::ColorImage::filled([8, 4], egui::Color32::RED),
1696 egui::TextureOptions::LINEAR,
1697 );
1698 let loaded = PlaceImage(egui::ImageSource::Texture((&texture).into()));
1699 drawn.1 = paint_image(ui, &loaded, square, false);
1700 });
1701 out.textures_delta.clear();
1702 assert_eq!(drawn, (false, true));
1703 }
1704
1705 #[test]
1706 fn an_image_fills_its_square_cropped_to_its_middle() {
1707 let wide = cover_uv(egui::vec2(200.0, 100.0));
1708 assert_eq!(
1709 wide,
1710 egui::Rect::from_min_max(egui::pos2(0.25, 0.0), egui::pos2(0.75, 1.0))
1711 );
1712 let tall = cover_uv(egui::vec2(100.0, 400.0));
1713 assert_eq!(
1714 tall,
1715 egui::Rect::from_min_max(egui::pos2(0.0, 0.375), egui::pos2(1.0, 0.625))
1716 );
1717 assert_eq!(
1718 cover_uv(egui::Vec2::ZERO),
1719 egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0))
1720 );
1721 }
1722
1723 #[test]
1724 fn two_images_are_equal_when_egui_loads_them_as_one() {
1725 let a = PlaceItem::new("cam", "Camera")
1726 .icon("phosphor:camera")
1727 .image("bytes://camera.png");
1728 let b = PlaceItem::new("cam", "Camera")
1729 .icon("phosphor:camera")
1730 .image("bytes://camera.png");
1731 assert_eq!(a, b);
1732 assert_ne!(a, b.clone().image("bytes://other.png"));
1733 assert_ne!(a, PlaceItem::new("cam", "Camera").icon("phosphor:camera"));
1734 }
1735
1736 #[test]
1737 fn user_dirs_read_home_relative_and_absolute_and_skip_home_itself() {
1738 let home = Path::new("/home/ana");
1739 let text = r#"
1740# This file is written by xdg-user-dirs-update
1741XDG_DESKTOP_DIR="$HOME/Bureau"
1742XDG_DOWNLOAD_DIR="$HOME/Téléchargements"
1743XDG_TEMPLATES_DIR="$HOME/Modèles"
1744XDG_MUSIC_DIR="$HOME"
1745XDG_PICTURES_DIR="/data/photos"
1746XDG_VIDEOS_DIR=relative/not/allowed
1747"#;
1748 assert_eq!(
1749 xdg_user_dirs(text, home),
1750 vec![
1751 (SystemFolder::Desktop, home.join("Bureau")),
1752 (SystemFolder::Downloads, home.join("Téléchargements")),
1753 (SystemFolder::Pictures, PathBuf::from("/data/photos")),
1754 ]
1755 );
1756 }
1757}