Skip to main content

egui_pop_api/files/
places.rs

1//! The system's places the in-app picker lists beside home: its folders
2//! (Desktop, Documents, Downloads, Pictures, Music, Videos) and the volumes
3//! mounted, removable cards among them, the first place of a photo import.
4//!
5//! [`system_places`] reads them from the system: on Linux and the BSDs the
6//! XDG user directories (`user-dirs.dirs`) and the mount points under
7//! `/run/media/<user>`, `/media` and `/mnt`; on macOS the folders in home
8//! and `/Volumes`; on Windows the folders in the user's profile and the
9//! drives. They are read when a picker opens, not each frame. An
10//! application gives its own with [`Files::set_system_places`] (a demo, a
11//! sandbox, tests).
12//!
13//! Beside them, an application adds **sections of its own** (a photo
14//! import's cards, services and history): a [`PlaceProvider`] registered on
15//! the files service ([`Files::place_providers`], [`FilesPlugin::places`])
16//! gives [`PlaceSection`]s of [`PlaceItem`]s. The in-app picker lists them
17//! under its own places, and a [`PlacesPanel`] draws all of them anywhere
18//! (an import window's sources column). An item is a name, an icon, a
19//! detail, a badge and, for a folder, its path; egui-pop knows nothing more
20//! of it: an item without a path (an account of a service) is the
21//! application's to act on.
22//!
23//! A panel goes further than the picker's list, each part opt-in: a section
24//! that folds ([`PlaceSection::foldable`]), says what it lacks
25//! ([`PlaceSection::empty`]) or has no heading ([`PlaceSection::untitled`]); an item with a line shown under its name
26//! ([`PlaceItem::line`]), a badge in a tone ([`PlaceItem::badge_tone`]) and
27//! a toggle of the application's (a pin, [`PlaceToggle`]); and room under
28//! an item or a section for the application's own content
29//! ([`PlacesPanel::under_item`], [`PlacesPanel::under_section`]). What the
30//! user did comes back in [`PlacesOutput`]: the application keeps the
31//! state and acts.
32//!
33//! [`Files::set_system_places`]: super::Files::set_system_places
34//! [`Files::place_providers`]: super::Files::place_providers
35//! [`FilesPlugin::places`]: super::FilesPlugin::places
36
37use 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/// A folder of the system's, by what it is for.
56#[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    /// In the order the picker lists them.
68    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    /// Its name in the picker, translated.
78    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    /// Its key in `user-dirs.dirs` (`XDG_<key>_DIR`).
90    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    /// Its usual folder in home, where the system names none (macOS,
102    /// Windows, Linux without `user-dirs.dirs`).
103    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/// A volume mounted: its name and where it is.
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct Volume {
119    pub name: String,
120    pub path: PathBuf,
121}
122
123/// The system's places, as the picker lists them.
124#[derive(Clone, Debug, Default, PartialEq, Eq)]
125pub struct SystemPlaces {
126    /// The system's folders that exist, home's own excluded.
127    pub folders: Vec<(SystemFolder, PathBuf)>,
128    /// The volumes mounted, the system's own excluded.
129    pub volumes: Vec<Volume>,
130}
131
132/// The system's places, read from the system (see the module).
133pub 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/// One place of a [`PlaceSection`]: a folder, a volume, or an application's
168/// own (a card, an account of a service). Made with [`PlaceItem::new`] or
169/// [`PlaceItem::folder`] and its builders.
170#[derive(Clone, Debug, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct PlaceItem {
173    /// Its id, unique in its section: what a panel says was chosen.
174    pub id: String,
175    /// Its name, shown and said.
176    pub name: String,
177    /// The folder it opens, if it is one: the picker lists only those.
178    pub path: Option<PathBuf>,
179    /// An icon of the icon registry (`phosphor:sd-card`), before its name:
180    /// what kind of place it is.
181    pub icon: Option<String>,
182    /// The icon's tooltip, said in the item's description (`Network
183    /// node`).
184    pub icon_tip: Option<String>,
185    /// A second, smaller icon on the corner of [`PlaceItem::icon`]: the
186    /// place's state (a struck cloud for an offline node), its tooltip
187    /// said in the item's description ([`PlaceItem::badge_icon`]).
188    pub badge_icon: Option<PlaceBadgeIcon>,
189    /// An image in the icon's place (a detected camera's photo), drawn at
190    /// the icon's size; the icon stands in while it loads or if it fails
191    /// ([`PlaceItem::image`]).
192    pub image: Option<PlaceImage>,
193    /// A line about it, in its tip (a card's free space); its path when none.
194    pub detail: Option<String>,
195    /// A short mark after its name (a count, "new"), said with it.
196    pub badge: Option<String>,
197    /// The badge's tone (a warning ▲ on an account to reconnect); plain
198    /// small text when none.
199    pub badge_tone: Option<Tone>,
200    /// A line shown under its name, always visible (a path, a card's free
201    /// space, "needs reconnecting"): why in a word, on the item itself.
202    /// Said as the item's description.
203    pub line: Option<String>,
204    /// A toggle of the application's at the item's end (a pin):
205    /// [`PlacesOutput::toggled`] says it was clicked.
206    pub toggle: Option<PlaceToggle>,
207    /// The items nested under it (a folder's subfolders, a keyword's
208    /// narrower ones), shown indented under it while it is open: a panel
209    /// then draws its section as a tree ([`PlaceItem::children`]).
210    pub children: Vec<PlaceItem>,
211    /// Whether it is open the first time it is shown, when it has
212    /// children (no by default).
213    pub open_at_first: bool,
214    /// Whether it is open, when the application keeps the state: the
215    /// panel follows it ([`PlacesOutput::expanded`] says the user asked to
216    /// change it). Kept in egui's memory when none.
217    pub open: Option<bool>,
218    /// Drawn muted (a folder of an offline volume): its name, line, badge
219    /// and icon in the muted text role, said to be unavailable. It stays
220    /// choosable, its detail still in its tip.
221    pub dimmed: bool,
222    /// Its name as a compacted chain (`a / b / c`, folders with one
223    /// child each drawn on one row): each segment its own click target,
224    /// underlined under the pointer ([`PlaceItem::segments`]). None: its
225    /// name, drawn whole.
226    pub segments: Vec<PlaceSegment>,
227}
228
229/// A segment of a [`PlaceItem`]'s compacted name ([`PlaceItem::segments`]):
230/// what it shows, the application's id for it, and what a screen reader
231/// says of it.
232#[derive(Clone, Debug, PartialEq, Eq)]
233#[non_exhaustive]
234pub struct PlaceSegment {
235    /// The application's id for it (a folder's path): what a click on it
236    /// reports ([`PlacesOutput::segment`]).
237    pub id: String,
238    /// What it shows (`b`).
239    pub label: String,
240    /// Its accessible name: the chain up to it (`a / b`) when none.
241    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    /// Its accessible name in place of the chain up to it (a full path).
254    #[must_use]
255    pub fn name(mut self, name: impl Into<String>) -> Self {
256        self.name = Some(name.into());
257        self
258    }
259}
260
261/// The separator egui-pop draws between a [`PlaceItem`]'s segments.
262pub const SEGMENT_SEPARATOR: &str = " / ";
263
264/// A click on one segment of an item's compacted name
265/// ([`PlacesOutput::segment`]).
266#[derive(Clone, Debug, PartialEq, Eq)]
267#[non_exhaustive]
268pub struct PlaceSegmentClick {
269    /// The item's section, by id.
270    pub section: String,
271    /// The item whose segment was clicked.
272    pub item: PlaceItem,
273    /// The segment's place in the chain, 0 for the first.
274    pub index: usize,
275    /// The segment's id ([`PlaceSegment::id`]).
276    pub id: String,
277}
278
279/// A state badge on a [`PlaceItem`]'s icon ([`PlaceItem::badge_icon`]).
280#[derive(Clone, Debug, PartialEq, Eq)]
281#[non_exhaustive]
282pub struct PlaceBadgeIcon {
283    /// An icon of the icon registry (`phosphor:cloud-slash`).
284    pub icon: String,
285    /// Its tooltip, said in the item's description (`Offline`).
286    pub tip: String,
287}
288
289/// The image of a [`PlaceItem`] ([`PlaceItem::image`]): an egui image
290/// source, two of them equal when egui would load them as one (the same
291/// URI, or the same texture at the same size).
292#[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/// A toggle at the end of a [`PlaceItem`] (a pin for the favourites): an
309/// icon on or off, named for assistive technology. The application owns
310/// its state: a click is reported ([`PlacesOutput::toggled`]), and the
311/// application gives the item again with the new state.
312#[derive(Clone, Debug, PartialEq, Eq)]
313#[non_exhaustive]
314pub struct PlaceToggle {
315    /// An icon of the icon registry (`phosphor:push-pin`).
316    pub icon: String,
317    /// Whether it is on: drawn in the accent, said as pressed.
318    pub on: bool,
319    /// Its name, said and in its tip ("Add to favourites").
320    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    /// An item that is no folder: the application acts on it.
335    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    /// A folder, its id its path.
358    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    /// The icon's tooltip (see [`PlaceItem::icon_tip`]): what kind of
379    /// place it is, in words.
380    #[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    /// A state badge on the corner of the kind icon: an icon of the icon
387    /// registry (`phosphor:cloud-slash`) and its tooltip (`Offline`), the
388    /// tooltip shown when the pointer is on the badge and said in the
389    /// item's description. The kind icon stays what the item is; the badge
390    /// says how it is. Without a kind icon the badge takes its place.
391    ///
392    /// Need (state): a place shown by its kind with its state on it (a node glyph with an offline mark).
393    #[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    /// An image in the icon's place: a texture the application loaded
403    /// (`egui::load::SizedTexture`), or a URI egui's image loaders read
404    /// (`file://`, `bytes://`, `https://`). It fills the icon's square,
405    /// cropped to its middle and rounded as the theme rounds widgets; the
406    /// item's [`icon`](PlaceItem::icon) is drawn while it loads or if it
407    /// fails. The item is still said by its name.
408    ///
409    /// Need (image): a place shown by its picture (a camera's photo) in a places list.
410    #[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    /// The badge's tone (see [`PlaceItem::badge_tone`]).
429    #[must_use]
430    pub fn badge_tone(mut self, tone: Tone) -> Self {
431        self.badge_tone = Some(tone);
432        self
433    }
434
435    /// A line under its name, always shown (see [`PlaceItem::line`]).
436    #[must_use]
437    pub fn line(mut self, line: impl Into<String>) -> Self {
438        self.line = Some(line.into());
439        self
440    }
441
442    /// A toggle at its end (see [`PlaceToggle`]).
443    #[must_use]
444    pub fn toggle(mut self, toggle: PlaceToggle) -> Self {
445        self.toggle = Some(toggle);
446        self
447    }
448
449    /// Items nested under it, after those it has: a branch of a tree
450    /// (volume, folder, subfolders; `Animals`, `Dog`). A panel indents
451    /// them by depth under a disclosure toggle named after the item ("Show
452    /// or hide Animals"); Right opens it and Left folds it while the item
453    /// has the keyboard, and Up and Down go through the rows shown. Each
454    /// item is said at its level, a branch as expanded or not.
455    ///
456    /// Need (data): a tree of places in a side panel (folders and their subfolders, nested keywords).
457    #[must_use]
458    pub fn children(mut self, children: impl IntoIterator<Item = PlaceItem>) -> Self {
459        self.children.extend(children);
460        self
461    }
462
463    /// Whether a branch is open the first time it is shown; its state is
464    /// then kept in egui's memory (see [`PlaceItem::open`]).
465    #[must_use]
466    pub fn open_at_first(mut self, open: bool) -> Self {
467        self.open_at_first = open;
468        self
469    }
470
471    /// A branch open or not as the application keeps it: the user's clicks
472    /// and arrows come back in [`PlacesOutput::expanded`].
473    #[must_use]
474    pub fn open(mut self, open: bool) -> Self {
475        self.open = Some(open);
476        self
477    }
478
479    /// Drawn muted and said to be unavailable (see [`PlaceItem::dimmed`]):
480    /// an offline volume's folders, still choosable.
481    ///
482    /// Need (state): a place shown out of reach but still choosable (a folder of an offline volume).
483    #[must_use]
484    pub fn dimmed(mut self, dimmed: bool) -> Self {
485        self.dimmed = dimmed;
486        self
487    }
488
489    /// Its name drawn as a compacted chain, `a / b / c` (egui-pop draws
490    /// the separator, [`SEGMENT_SEPARATOR`]): each segment underlined
491    /// under the pointer, its own click target and its own node for
492    /// assistive technology, named by the chain up to it (`a / b`) or
493    /// its [`PlaceSegment::name`]. A click on a segment is reported in
494    /// [`PlacesOutput::segment`], not as the item chosen: the
495    /// application decides what it does. The row keeps its selection,
496    /// hover highlight, keyboard (Enter chooses the item) and tip, and is
497    /// still said by [`PlaceItem::name`] (give it the whole chain).
498    ///
499    /// Need (data): a tree row of compacted folders (`a / b / c`) whose each folder is clickable.
500    #[must_use]
501    pub fn segments(mut self, segments: impl IntoIterator<Item = PlaceSegment>) -> Self {
502        self.segments.extend(segments);
503        self
504    }
505
506    /// What a screen reader says of it: its name, then its badge.
507    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/// A titled list of places: the system's folders, the devices, or an
516/// application's ("Cards", "Services"); or an untitled one, its rows shown
517/// without a heading ([`PlaceSection::untitled`]).
518#[derive(Clone, Debug, PartialEq, Eq)]
519#[non_exhaustive]
520pub struct PlaceSection {
521    /// Its id: unique among the sections shown.
522    pub id: String,
523    pub title: String,
524    pub items: Vec<PlaceItem>,
525    /// Whether it folds, and whether it is open the first time it is
526    /// shown; a fixed heading when none.
527    pub fold: Option<bool>,
528    /// Whether it is open, when the application keeps the state: the
529    /// panel follows it ([`PlacesOutput::folded`] says the user asked to
530    /// change it). Kept in egui's memory when none.
531    pub open: Option<bool>,
532    /// The line it shows when it has no items ("No cards"): a section
533    /// with one is shown empty, one without is left out.
534    pub empty: Option<String>,
535    /// Shown even without items or an empty line: its content comes from
536    /// [`PlacesPanel::under_section`].
537    pub keep: bool,
538    /// Drawn without a heading or a fold arrow, its rows shown directly
539    /// ([`PlaceSection::untitled`]); its title is then only the name a
540    /// screen reader gives its group.
541    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    /// A section without a heading: no title drawn and no fold arrow, its
559    /// rows shown directly (a library's top rows, "All photos", above the
560    /// titled sections). It stays one group for assistive technology,
561    /// named `name` ("Library"), which no one sees. Folding
562    /// ([`PlaceSection::foldable`], [`PlaceSection::open`]) is ignored: a
563    /// section without a band has nothing to fold by.
564    ///
565    /// Need (data): a list of places without a heading.
566    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    /// Folds under its band (egui-pop's [`Fold`]), open at first when
574    /// `open_at_first`; its state kept in egui's memory, unless the
575    /// application keeps it ([`PlaceSection::open`]).
576    #[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    /// Folds, open or not as the application keeps it: the user's clicks
583    /// come back in [`PlacesOutput::folded`].
584    #[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    /// The line shown when it has no items; it is then shown empty.
592    #[must_use]
593    pub fn empty(mut self, line: impl Into<String>) -> Self {
594        self.empty = Some(line.into());
595        self
596    }
597
598    /// Shown even without items or an empty line (its content drawn by
599    /// [`PlacesPanel::under_section`]).
600    #[must_use]
601    pub fn keep(mut self) -> Self {
602        self.keep = true;
603        self
604    }
605
606    /// Whether a panel shows it: it has items, an empty line or is kept.
607    pub fn shown(&self) -> bool {
608        !self.items.is_empty() || self.empty.is_some() || self.keep
609    }
610
611    /// Adds an item, after those it has.
612    #[must_use]
613    pub fn item(mut self, item: PlaceItem) -> Self {
614        self.items.push(item);
615        self
616    }
617
618    /// Adds items, after those it has.
619    #[must_use]
620    pub fn items(mut self, items: impl IntoIterator<Item = PlaceItem>) -> Self {
621        self.items.extend(items);
622        self
623    }
624}
625
626/// An application's sections of places ([`PlaceProviders::register`]).
627/// Asked each time a picker or a panel is drawn: it answers from what it
628/// holds (a device watch's list, a history kept in memory), never reading a
629/// disk or a network there.
630pub trait PlaceProvider: fmt::Debug + Send + Sync {
631    /// Its id: registering another with this id replaces it.
632    fn id(&self) -> &str;
633
634    /// Its sections now, in the order shown.
635    fn sections(&self) -> Vec<PlaceSection>;
636}
637
638/// The place providers declared, as a service of [`Files`](super::Files).
639#[derive(Clone, Debug, Default)]
640pub struct PlaceProviders(Arc<Mutex<Vec<Arc<dyn PlaceProvider>>>>);
641
642impl PlaceProviders {
643    /// Adds a provider, or replaces the one with its id; its sections come
644    /// after those of the ones before it. A plugin registering one takes it
645    /// back in its `disconnect`.
646    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    /// Takes a provider away; says whether it was there.
653    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    /// The ids of the providers, in their order.
661    pub fn ids(&self) -> Vec<String> {
662        lock(&self.0).iter().map(|p| p.id().to_string()).collect()
663    }
664
665    /// Every provider's sections, in order; a section without items is
666    /// left out, unless it has an empty line or is kept
667    /// ([`PlaceSection::shown`]). A provider that panics gives none, and the log says so.
668    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
683/// Paints a place's image in `square`, filling it: cropped to its middle,
684/// rounded as the theme rounds widgets (a quarter of its side at most),
685/// faded when `muted`. False while it loads or when it fails: the caller
686/// draws the icon instead.
687fn 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
707/// The part of an image of `size` that fills a square: its middle, the
708/// longer side cropped.
709fn 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
722/// A section's title, said as a heading.
723pub(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
729/// An item's row: its icon, its name and its badge, `selected` or not, its
730/// detail (else its path) in its tip; named by [`PlaceItem::said`].
731pub(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/// What a [`PlacesPanel`] did this frame.
780#[derive(Clone, Debug, Default, PartialEq, Eq)]
781#[non_exhaustive]
782pub struct PlacesOutput {
783    /// The item chosen: a click, or Enter or Space on it; its section's id
784    /// with it.
785    pub chosen: Option<(String, PlaceItem)>,
786    /// The item whose toggle was clicked ([`PlaceItem::toggle`]), its
787    /// section's id with it: the application flips its state.
788    pub toggled: Option<(String, PlaceItem)>,
789    /// The foldable section the user folded or opened, by id, and whether
790    /// it is open now.
791    pub folded: Option<(String, bool)>,
792    /// The nested item ([`PlaceItem::children`]) the user opened or
793    /// folded, by id, and whether it is open now.
794    pub expanded: Option<(String, bool)>,
795    /// The segment of an item's compacted name the user clicked
796    /// ([`PlaceItem::segments`]).
797    pub segment: Option<PlaceSegmentClick>,
798}
799
800/// What draws an item's context menu ([`PlacesPanel::menu`]), or the
801/// application's content under an item ([`PlacesPanel::under_item`]).
802type PlaceMenu<'a> = Box<dyn FnMut(&mut Ui, &PlaceSection, &PlaceItem) + 'a>;
803
804/// What draws the application's content under a section's items
805/// ([`PlacesPanel::under_section`]).
806type SectionSlot<'a> = Box<dyn FnMut(&mut Ui, &PlaceSection) + 'a>;
807
808/// What sees each item's row ([`PlacesPanel::on_row`]).
809type RowHook<'a> = Box<dyn FnMut(&mut Ui, &PlaceSection, &PlaceItem, &egui::Response) + 'a>;
810
811/// A side panel of places: sections, each a heading over its items, as the
812/// in-app picker lists them (an import window's sources column). One stop
813/// for Tab; Up and Down go from item to item across the sections (through
814/// an item's toggle, a fold's band and the application's content, in the
815/// order drawn), Enter or Space chooses. Each item is a button named by its
816/// name and badge, described by its line, selected or not; each title a
817/// heading, or a fold's band when the section folds. What a chosen item
818/// does is the caller's: [`PlacesOutput::chosen`].
819///
820/// Opt-in parts (see the module): folding sections, an empty section's
821/// line, an item's visible line, toned badge and toggle, the
822/// application's content under an item or a section, nested items
823/// ([`PlaceItem::children`]), dimmed items ([`PlaceItem::dimmed`]), a hook
824/// on each row ([`PlacesPanel::on_row`]) and a selection in several
825/// sections ([`PlacesPanel::selected_set`]). A panel using none of them
826/// looks as it always did.
827///
828/// ```
829/// use egui_pop_api::files::places::{PlaceItem, PlaceSection, PlacesPanel};
830///
831/// fn sources(ui: &mut egui::Ui, at: &mut Option<String>) {
832///     let sections = [PlaceSection::new("cards", "Cards")
833///         .item(PlaceItem::folder("EOS_DIGITAL", "/media/EOS_DIGITAL").badge("214"))];
834///     let out = PlacesPanel::new("import.sources", &sections)
835///         .selected(at.as_deref())
836///         .show(ui);
837///     if let Some((_, item)) = out.chosen {
838///         *at = Some(item.id);
839///     }
840/// }
841/// # let _ = sources;
842/// ```
843///
844/// Need (dialog): a side panel of places, with sections of an application's.
845pub 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    /// Each tree section's rows drawn this pass, for its guides.
857    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    /// A panel named `name` (its roving group's, unique in the window) of
875    /// these sections.
876    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    /// When a tree section ([`PlaceItem::children`]) draws its indent
893    /// guides, a thin line down each nesting level in the kit's
894    /// `list-guide` (`list-guide.rest.border-color`, `border-width`):
895    /// never (the default), while the pointer is over the panel, or
896    /// always, as VS Code's `renderIndentGuides`.
897    ///
898    /// Need (data): a tree of places whose levels are easy to follow (folders nested deep).
899    #[must_use]
900    pub fn indent_guides(mut self, mode: IndentGuides) -> Self {
901        self.indent_guides = mode;
902        self
903    }
904
905    /// Whether the guide of the hovered row's parent (the run of its
906    /// siblings) is highlighted, in `list-guide`'s `hover` state
907    /// (`list-guide.hover.border-color`); no by default.
908    #[must_use]
909    pub fn indent_guide_highlight(mut self, on: bool) -> Self {
910        self.guide_highlight = on;
911        self
912    }
913
914    /// The item shown selected, by id: where the caller is.
915    #[must_use]
916    pub fn selected(mut self, id: Option<&'a str>) -> Self {
917        self.selected = id;
918        self
919    }
920
921    /// The items shown selected, by id, beside [`PlacesPanel::selected`]:
922    /// one in each section where the application's scopes add up (a
923    /// folder, an album and a keyword chosen together).
924    ///
925    /// Need (data): a side panel of places with one selection in each section (scopes chosen together).
926    #[must_use]
927    pub fn selected_set(mut self, ids: &'a [&'a str]) -> Self {
928        self.selected_set = ids;
929        self
930    }
931
932    /// A hook called with each item's row and its response, after the
933    /// panel's own handling: the application attaches what the panel
934    /// knows nothing of (a drop target or a drag source through the drag
935    /// session, `bus::drag`; its own context menu; a tip). Called for
936    /// nested items too.
937    ///
938    /// Need (dialog): a side panel of places whose rows are drop targets or drag sources.
939    #[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    /// A context menu on each item, drawn by `menu` (rename, eject, forget).
949    #[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    /// The application's content under each item, drawn by `add` in the
956    /// room below it (an account's albums under the account): `add` draws
957    /// nothing for an item without any. Its widgets join the panel's
958    /// keyboard order after the item.
959    #[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    /// The application's content under each section's items, drawn by
966    /// `add` (a history's past imports, each with "Import again"), inside
967    /// the section's fold when it folds. Its widgets join the panel's
968    /// keyboard order after the section's items.
969    #[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                            // No heading: the rows, grouped and named for
989                            // assistive technology alone.
990                            ui.scope_builder(
991                                egui::UiBuilder::new()
992                                    .id_salt(("untitled", &section.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, &section.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, &section.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                                // The application keeps the state: follow it.
1013                                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    /// A section's items, its empty line, and the application's content.
1030    fn section_body(&mut self, ui: &mut Ui, section: &PlaceSection, out: &mut PlacesOutput) {
1031        if section.items.is_empty()
1032            && let Some(empty) = &section.empty
1033        {
1034            ui.meta(empty.as_str());
1035        }
1036        // A section with nested items is drawn as a tree, every row at its
1037        // depth; one without is drawn as it always was.
1038        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 &section.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", &section.id), |ui| add(ui, section));
1047        }
1048    }
1049
1050    /// Whether an item is drawn selected.
1051    fn is_selected(&self, id: &str) -> bool {
1052        self.selected == Some(id) || self.selected_set.contains(&id)
1053    }
1054
1055    /// An item's row, at `depth` in a tree section (`None` in a flat
1056    /// one), its menu, hook and content, then its children while open.
1057    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", &section.id, &item.id));
1068        ui.push_id((&section.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                        // The application keeps the state: follow it.
1083                        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                    // Right opens and Left folds a branch from its row too,
1102                    // as a tree's arrows do.
1103                    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            // Enter and Space click the item that has the keyboard.
1137            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
1173/// An item of a panel: the picker's row ([`place_row`]) when it has no
1174/// line and no toggle, as panels always drew it; else a row of one fixed
1175/// height with its line under its name and its toggle at its end. Says
1176/// whether its toggle was clicked, and which segment of its compacted
1177/// name was ([`PlaceItem::segments`]).
1178fn 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    // Its tip: its detail, else its path.
1215    let tip = item
1216        .detail
1217        .clone()
1218        .or_else(|| item.path.as_ref().map(|p| p.display().to_string()));
1219    // The icons' tooltips lead the description: what the place is, then
1220    // how it is.
1221    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        // A dimmed item says why: "Unavailable", its line, its tip (the
1232        // plain reason, "On uuid:card, unplugged"), so that a screen
1233        // reader hears what the pointer reads; egui only puts a tip into
1234        // an empty description.
1235        (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    // The toggle's room at the end, outside the row's own click; a little
1263    // below the row's middle, so that the keyboard, which goes by place,
1264    // reaches it after its item.
1265    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    // The kind icon's square, and the badge on its lower right corner.
1276    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        // The chosen row is never `hover`: the choice stays under the
1331        // pointer, as a selectable row's. The pointer on a segment is on
1332        // the row too.
1333        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                // On the kind icon, the badge sits on a disc of the row's
1379                // background, so the two shapes stay apart.
1380                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            // The chain, each segment underlined while the pointer is on
1407            // it, the separators between them.
1408            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            // The badge leads the line, as a state mark.
1438            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    // The pointer on the badge shows its tooltip, on the kind icon the
1471    // icon's; elsewhere the item's own.
1472    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
1506/// A segment of an item's compacted name laid out on its row: where it
1507/// is, its text, and the separator drawn before it.
1508struct SegmentPart {
1509    index: usize,
1510    rect: egui::Rect,
1511    galley: Arc<egui::Galley>,
1512    separator: Option<(egui::Pos2, Arc<egui::Galley>)>,
1513}
1514
1515/// Lays out an item's segments from `at` on one line, up to `right`: the
1516/// segments that start before it, the last one clipped there.
1517fn 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
1559/// The folders `user-dirs.dirs` names (`XDG_PICTURES_DIR="$HOME/Pictures"`),
1560/// in the picker's order; one set to home itself means none, as the
1561/// specification says. Whether they exist is not checked.
1562pub 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
1590/// The volumes mounted (see the module), by name.
1591fn 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    // `/media/<user>/x` is under `/media` too: once each.
1602    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/// Mount points under `/run/media/<user>`, `/media/<user>`, `/media` and
1628/// `/mnt`: a folder on another device than its parent's.
1629#[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
1659/// `/Volumes`, but the system's own volume, a link to `/`.
1660fn 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
1668/// The drives from `C:` (`A:` and `B:` are floppies, slow to ask).
1669fn 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            // No loader reads this URI: the image fails, the icon stands in.
1691            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}