Skip to main content

egui_pop_api/
files.rs

1//! Choosing files, as a plugin ([`FilesPlugin`], in `DefaultPlugins`):
2//! egui-pop's in-app picker, or, as a fallback an application allows, the
3//! system's chooser off the interface thread.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! [`Files::choose`] returns a [`Pending`] (the host contract's, ADR
9//! 0010): the frame never waits. In-app pickers open in a modal of their
10//! own, or inside the caller's dialog ([`Files::choose_inline`], as a
11//! form's path field does). The result is `{ "paths": [...] }`, or
12//! `null` when the person cancelled; [`chosen`] reads it. A choice
13//! belongs to the window it was asked from ([`Files::owner`]): its
14//! in-app picker's modal is drawn over that application window and blocks
15//! it alone; the window closed, the choice is cancelled.
16//!
17//! A choice under way is on the bus (ADR 0029): started, it asks its
18//! `pop.popup.open` (`file:<id>`, owned by this plugin, its parent the window
19//! it was asked from), or, for the system's chooser, the `pop.window.open` of
20//! a native window; ended, their close. Its window closing closes it
21//! (`parent-closed`), and this plugin's listener ([`CHOICE_LISTENER`])
22//! cancels the choice in that call.
23//!
24//! - **The system's chooser** (feature `native-dialogs`, through `rfd`):
25//!   a fallback kept in case an application cannot do with the in-app
26//!   picker, off at build time and at run time. Used only when the feature
27//!   is compiled in *and* the application allows it
28//!   (`AppBuilder::system_file_chooser`) *and* the person's `files.native`
29//!   setting is on *and* a portal answers; never under tests
30//!   ([`system_chooser_refused`]). The xdg desktop portal on Linux, the
31//!   common dialogs on Windows, the open and save panels on macOS. It is
32//!   created on the interface thread and awaited on a thread of its own.
33//!   It is attached to the window it was asked from (the portal's parent
34//!   window, the owner window on Windows, a sheet on macOS) when that
35//!   window's handle is known ([`set_parent_window`]; the main window's
36//!   is recorded by `AppBuilder::run_native`); else to none, never to
37//!   another window.
38//! - **The in-app picker** ([`FilePicker`]), in every other case: a
39//!   click selects and a double click or Enter opens, keyboard navigation
40//!   (arrows, Enter, Backspace or `Alt+Up` for the parent folder,
41//!   `Ctrl+Enter` to choose the folder or the selection,
42//!   `Ctrl+D` to bookmark), several files selected with `Ctrl` or `Shift`
43//!   and a click, `Shift` and the arrows, `Ctrl+Space` and `Ctrl+A`
44//!   ([`CMD_TOGGLE_SELECTION`], [`CMD_SELECT_ALL`]), a typed path with
45//!   completion (`Tab`), the fuzzy filter of the choice dialog,
46//!   the request's filters, the system's folders and volumes ([`places`]),
47//!   recent places and bookmarks (renamed and moved from their menu) kept in
48//!   the host store (`settings/files.recent`, `settings/files.bookmarks`), and the
49//!   last folder per purpose (`settings/files.last_folders`).
50//!   Saving, it appends the filter's extension to a name without one and
51//!   follows the filter when it changes, selects the name's stem, asks
52//!   before replacing a file ([`FileRequest::confirm_overwrite`], through
53//!   the dialogs plugin), and makes folders ([`CMD_NEW_FOLDER`]).
54//!   It reads through a [`fs::FileSystem`]: the system's by default, or a
55//!   folder held in memory ([`fs::MemoryFs`]; the web build has no file
56//!   system), given with [`FilesPlugin::file_system`] or
57//!   [`Files::set_file_system`].
58//! - **Previews** come from pluggable providers ([`preview`]): plugins
59//!   register theirs with [`Files::previews`]; they are made off the
60//!   interface thread, cancelled when the highlight moves, and cached.
61//!   The in-app picker shows the highlighted entry's preview and facts in
62//!   a pane beside the list (`Alt+P` shows or hides it; the
63//!   `files.preview` setting remembers). Built in ([`providers`]):
64//!   images (PNG and JPEG, feature `image-previews`), text and code,
65//!   Markdown drawn simply, folders with their first images.
66//! - **The in-app picker's size** is the person's: its modal is resized
67//!   by its edges and corners, a splitter sets the pane's width, and
68//!   both are kept in the host store ([`DIALOG_SIZE`], [`PANE_WIDTH`]).
69//! - **The in-app picker's order**: a click on a column's header sorts by it
70//!   ([`sort`]), in the list and the grid alike; it is kept in the host store
71//!   ([`SORT`]), and [`SETTING_FOLDERS_FIRST`] keeps folders first.
72//! - **The in-app picker's view**, with previews: a list, or a grid of
73//!   thumbnails from the same providers ([`PickerView`]), whose zoom (how
74//!   many thumbnails fill a row, one across at most, kept through a
75//!   resize) is a slider, `Ctrl` and the wheel, or `Ctrl` and `+` or `-`; only the cells
76//!   in view ask for a thumbnail ([`Previews::want`]), a placeholder stands
77//!   in until it is made, and the arrows move in two dimensions. Both are
78//!   kept in the host store ([`VIEW`], [`THUMBNAILS_PER_ROW`]).
79//! - **The in-app picker's folder** reads as breadcrumbs: each segment opens its
80//!   folder, the chevron after it lists its subfolders, and with too little room
81//!   the start collapses behind a menu, the deepest segments staying.
82//!   [`CMD_EDIT_PATH`] (Ctrl+L), or typing `/` or `~` on an entry, puts a path
83//!   into the field, which takes both.
84//! - **Grouped files** ([`groups`]): with a grouping declared by the application
85//!   ([`FilesPlugin::grouping`], [`Files::groupings`]), files that go together are
86//!   one entry of the in-app picker, a RAW with its sidecars, with a badge
87//!   (`+XMP`). Choosing it gives the main file, and [`chosen_groups`] the others.
88//! - **The application's options** ([`FileRequest::choice`],
89//!   [`FileRequest::check`]): combo boxes and check boxes above the in-app
90//!   picker's buttons, in the desktop portal's shape; the choice gives their
91//!   values back ([`chosen_choices`]). `rfd` cannot show them, so a request
92//!   with choices opens the in-app picker.
93//!
94//! Steps (ADR 0011):
95//!
96//! | Step | Arguments | Default |
97//! |---|---|---|
98//! | `file.choose` | `{ "id", "request" }` | opens the system's chooser or the in-app picker |
99//! | `file.chosen` | `{ "id", "request", "paths", "origin" }`, `"groups"` when some are, `"choices"` when the request has some | remembers the places, gives the paths, their groups and the choices |
100//!
101//! A run-hook on `file.choose` replaces the whole chooser: it answers
102//! `{ "paths": [...] }` or `{ "cancelled": true }` at once, or anything
103//! else and later [`Files::deliver`]. A before-hook on `file.chosen` may
104//! veto the choice (the result is the reason, as an error) or redirect
105//! it to other paths. The journal says `file.cancelled` when the choice
106//! is cancelled, from whoever cancelled it. The debug bridge's `files`
107//! collector shows the choices open and answers them (`answer`, the
108//! user's unless offered to agents), as its caller: the result carries
109//! the origin ([`chosen_origin`]), and so does `file.chosen` (`origin`,
110//! as the journal writes it), so a hook may refuse a choice no person
111//! made. The `file.preview`
112//! command gives agents a path's preview metadata ([`preview_metadata`]).
113//!
114//! The question before replacing a file is the in-app picker's own: the
115//! system's choosers ask theirs, a run-hook on `file.choose` and
116//! [`Files::deliver`] answer for themselves, and none of them is asked
117//! again.
118//!
119//! ```
120//! use egui_pop_api::files::{self, FileRequest, FilesPlugin, FILES};
121//! use egui_pop_api::App;
122//!
123//! let app = App::builder().plugin(FilesPlugin::in_app()).build(&egui::Context::default()).unwrap();
124//! let h = app.handle();
125//! let f = h.service(&FILES).unwrap();
126//! let pending = f.choose(&h, FileRequest::open("Open an image").filter("Images", &["png", "jpg"]));
127//! // Nothing yet: the picker is open, the frame goes on.
128//! assert!(pending.take().is_none());
129//! assert_eq!(f.describe()["open"][0]["via"], "in_app");
130//! ```
131
132use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
133use std::path::{Path, PathBuf};
134use std::sync::{Arc, Mutex};
135
136use egui::{EventFilter, Key, Modifiers, Ui, pos2, vec2};
137use egui_pop_core::a11y::{self, Politeness};
138use egui_pop_core::debug::FnCollector;
139use egui_pop_core::focus;
140use egui_pop_core::icon::Icon;
141use egui_pop_core::lock;
142use egui_pop_core::overlay::{self, Kind, OverlaySpec};
143use egui_pop_core::slider::Slider;
144use egui_pop_core::strings::{self, Arg, CANCEL};
145use egui_pop_core::theme::Tokens;
146use egui_pop_core::thumbnail::Band;
147use egui_pop_core::ui::{Stock, Tone, UiPop as _};
148use egui_pop_core::widgets;
149use egui_pop_model::commands::{CommandSpec, Origin};
150use egui_pop_model::ids::{BlockId, CommandId, OwnerId, PluginId, SettingId, StepId};
151use egui_pop_model::keymap::BindOptions;
152use egui_pop_model::values::{Change, Descriptor, Set, Value};
153use serde::{Deserialize, Serialize};
154use serde_json::{Value as Json, json};
155
156use bus_contract::{HookError, ListenOpts, Point as _};
157
158use crate::app::AppHandle;
159use crate::bus::{
160    CHILDREN, FOCUS, PopupClose, REGISTRY, Reason, WindowClose, WindowKind, WindowRequest,
161};
162use crate::dialogs::{Confirm, DIALOGS};
163use crate::host::{self, Pending, Resolver};
164use crate::services::ServiceToken;
165use crate::steps::{Outcome, StepSpec};
166use crate::strings as txt;
167use crate::zones::{self, Block};
168use crate::{Ctx, Plugin, PluginError};
169
170use self::sort::{PickerSort, SortColumn};
171
172pub mod browser;
173pub mod fs;
174pub mod groups;
175pub mod places;
176pub mod preview;
177pub mod providers;
178pub mod sort;
179
180use browser::ThumbnailProvider as _;
181use browser::ViewMode as _;
182use fs::SharedFs;
183use groups::{FileGroup, FileGrouping, Groupings};
184use places::{PlaceProvider, PlaceProviders, PlaceSection, SystemPlaces};
185use preview::Previews;
186
187/// The file chooser, as a service.
188pub const FILES: ServiceToken<Files> = ServiceToken::new("app.files");
189
190/// A choice starts: the system's chooser or the in-app picker opens.
191pub const STEP_CHOOSE: StepId = StepId::from_static("file.choose");
192/// Paths were chosen.
193pub const STEP_CHOSEN: StepId = StepId::from_static("file.chosen");
194
195/// A path's preview metadata, for agents (`{ "path" }`).
196pub const CMD_PREVIEW: CommandId = CommandId::from_static("file.preview");
197/// A new folder in the open in-app picker (Ctrl+Shift+N): asks its name,
198/// or makes it at once with `{ "name" }`.
199pub const CMD_NEW_FOLDER: CommandId = CommandId::from_static("file.new_folder");
200/// The answer to the question before replacing a file: the choice ends
201/// with that file (`{ "id", "path" }`).
202pub const CMD_REPLACE: CommandId = CommandId::from_static("file.replace");
203/// Every file shown in the open in-app picker is selected (Ctrl+A, choosing
204/// several files, unless the field holds a path: the key is then the field's).
205pub const CMD_SELECT_ALL: CommandId = CommandId::from_static("file.select_all");
206/// The highlighted entry of the open in-app picker is selected or unselected
207/// (Ctrl+Space, choosing several files or a folder).
208pub const CMD_TOGGLE_SELECTION: CommandId = CommandId::from_static("file.toggle_selection");
209/// The open in-app picker's folder goes into its field, as a path to edit
210/// (Ctrl+L). Saving, the name stays at its end.
211pub const CMD_EDIT_PATH: CommandId = CommandId::from_static("file.edit_path");
212/// The open in-app picker shows or hides hidden files (Ctrl+H, as GTK and KDE).
213pub const CMD_TOGGLE_HIDDEN: CommandId = CommandId::from_static("file.toggle_hidden");
214/// The open in-app picker reads its folder again (F5).
215pub const CMD_RELOAD: CommandId = CommandId::from_static("file.reload");
216/// The open in-app picker goes back to the folder it showed before (Alt+Left).
217pub const CMD_BACK: CommandId = CommandId::from_static("file.back");
218/// The open in-app picker goes forward again after going back (Alt+Right).
219pub const CMD_FORWARD: CommandId = CommandId::from_static("file.forward");
220/// The in-app picker's preview pane is shown or hidden (Alt+P, as the Windows
221/// file explorer's), and kept so.
222pub const CMD_TOGGLE_PREVIEW: CommandId = CommandId::from_static("file.toggle_preview");
223
224/// The context key: an open in-app picker can be asked for a new folder
225/// (saving, or choosing a folder).
226const WHEN_NEW_FOLDER: &str = "filePickerNewFolder";
227/// The context key: an open in-app picker selects all its files on request.
228const WHEN_SELECT_ALL: &str = "filePickerSelectAll";
229/// The context key: an open in-app picker selects apart from its highlight.
230const WHEN_SELECTS: &str = "filePickerSelects";
231/// The context key: an in-app picker is open, and not waiting for an answer.
232const WHEN_EDIT_PATH: &str = "filePickerEditPath";
233/// That, in a modal (as the picker's own and a dialog are): where `Alt+Left` is
234/// not the context stack's back (`nav.back`).
235const WHEN_IN_MODAL: &str = "modalOpen && filePickerEditPath";
236/// A file browser holds the keyboard (an in-app picker with previews open,
237/// or a [`browser::FileBrowser`]'s entries): the mode keys work.
238pub const WHEN_BROWSER: &str = "fileBrowserFocused";
239/// The prefix of the mode keys' commands: `file.view.mode1` (`Ctrl+1`) to
240/// `file.view.mode9`.
241pub const CMD_VIEW_MODE: &str = "file.view.mode";
242
243/// The setting: use the system's chooser when there is one. Declared only
244/// when the application allows that chooser
245/// (`AppBuilder::system_file_chooser`); on by default there.
246pub const SETTING_NATIVE: SettingId = SettingId::from_static("files.native");
247/// The setting: the in-app picker shows its preview pane.
248pub const SETTING_PREVIEW: SettingId = SettingId::from_static("files.preview");
249/// Whether the in-app picker keeps folders before files in every order.
250pub const SETTING_FOLDERS_FIRST: SettingId = SettingId::from_static("files.folders_first");
251
252/// Where recent places are kept (a JSON list of folders, newest first).
253pub const RECENT: &str = "settings/files.recent";
254/// Where bookmarks are kept (a JSON list of folders).
255pub const BOOKMARKS: &str = "settings/files.bookmarks";
256/// Where the names given to bookmarks are kept (a JSON list of
257/// `[folder, name]` pairs). See [`rename_bookmark`].
258pub const BOOKMARK_NAMES: &str = "settings/files.bookmark_names";
259
260/// Where the in-app picker's size is kept (width and height of its
261/// content, in points).
262pub const DIALOG_SIZE: &str = "settings/files.dialog_size";
263/// Where the width of the in-app picker's preview pane is kept.
264pub const PANE_WIDTH: &str = "settings/files.pane_width";
265
266/// Where the in-app picker's view last used is kept: a mode id of
267/// [`browser::ViewModes`] (`details`, `thumbnails`); a dialog never seen
268/// opens in it.
269pub const VIEW: &str = "settings/files.view";
270/// The mode each dialog was last shown in, by dialog (a request's purpose,
271/// else its kind): a JSON list of pairs ([`view_for`]).
272pub const VIEWS: &str = "settings/files.views";
273/// How many dialogs' modes are kept.
274pub const VIEWS_KEPT: usize = 32;
275/// Where an older version kept the size of the in-app picker's thumbnails,
276/// in points. No longer declared: a value saved there is read until
277/// [`THUMBNAILS_PER_ROW`] is set, converted at the grid's width
278/// ([`thumbnail_zoom`]).
279pub const THUMBNAIL_SIZE: &str = "settings/files.thumbnail_size";
280/// How many thumbnails fill a row of the in-app picker's grid; 0 (the
281/// default) until the person zooms: an older size in points
282/// ([`THUMBNAIL_SIZE`]), else [`browser::ThumbZoom::DEFAULT_PER_ROW`].
283pub const THUMBNAILS_PER_ROW: &str = "settings/files.thumbnails_per_row";
284/// The size of the in-app picker's thumbnails, in points, when its grid
285/// keeps the size on a resize ([`FilesPlugin::grid_resize`] with
286/// [`browser::GridResize::FixedSize`]); 0 (the default) until the person
287/// zooms: the count per row kept ([`THUMBNAILS_PER_ROW`]) converted.
288pub const THUMBNAIL_POINTS: &str = "settings/files.thumbnail_points";
289/// Where the in-app picker's order is kept: `name`, `-name` (descending), and
290/// `size`, `modified` or `type` the same way ([`sort::PickerSort`]).
291pub const SORT: &str = "settings/files.sort";
292/// Where it is kept whether the in-app picker groups files, with groupings
293/// declared ([`groups`]). Not a setting of the settings window: without a
294/// grouping it would do nothing.
295pub const GROUPED: &str = "settings/files.grouped";
296
297/// Where the last folder of each purpose is kept (a JSON list of
298/// `[purpose, folder]` pairs, newest first). See [`FileRequest::purpose`].
299pub const LAST_FOLDERS: &str = "settings/files.last_folders";
300
301/// How many folders the in-app picker goes back through.
302const HISTORY_KEPT: usize = 64;
303/// How many recent places are kept.
304pub const RECENT_KEPT: usize = 8;
305/// How many purposes keep a last folder: the one chosen in the longest ago
306/// goes first.
307pub const LAST_FOLDERS_KEPT: usize = 32;
308
309/// What is chosen.
310#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(rename_all = "snake_case")]
312pub enum ChooseKind {
313    /// One existing file.
314    Open,
315    /// Existing files.
316    OpenMany,
317    /// A file to write (it may not exist yet).
318    Save,
319    /// A folder.
320    Folder,
321}
322
323/// Files a filter shows: a name and extensions (without the dot).
324#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
325pub struct FileFilter {
326    pub name: String,
327    pub extensions: Vec<String>,
328}
329
330impl FileFilter {
331    pub fn new(name: &str, extensions: &[&str]) -> Self {
332        Self {
333            name: name.into(),
334            extensions: extensions.iter().map(|e| e.to_lowercase()).collect(),
335        }
336    }
337
338    /// Whether a file's name has one of the extensions (any, without
339    /// extensions).
340    pub fn accepts(&self, path: &Path) -> bool {
341        browser::has_extension(&self.extensions, path)
342    }
343}
344
345/// An option of the application's, shown by the in-app picker beside its
346/// buttons and given back with the paths ([`chosen_choices`]): a combo box of
347/// values, or a check box. Its shape is the desktop portal's `choices`: an id,
348/// a label, the values offered as `(id, label)`, and the value it starts with;
349/// no values make a check box, whose value is `"true"` or `"false"`.
350#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
351pub struct FileChoice {
352    pub id: String,
353    /// What the picker says beside it, translated by the application.
354    pub label: String,
355    /// The values offered, `(id, label)`; none: a check box.
356    #[serde(default)]
357    pub options: Vec<(String, String)>,
358    /// The value it starts with: an option's id, or `"true"` or `"false"`.
359    pub default: String,
360}
361
362impl FileChoice {
363    /// A check box.
364    pub fn is_check(&self) -> bool {
365        self.options.is_empty()
366    }
367
368    /// Whether `value` is one this choice can take.
369    pub fn accepts(&self, value: &str) -> bool {
370        if self.is_check() {
371            value == "true" || value == "false"
372        } else {
373            self.options.iter().any(|(id, _)| id == value)
374        }
375    }
376}
377
378/// The application's choices as a choice ends with them: each id with its
379/// value ([`chosen_choices`]).
380pub type ChoiceValues = BTreeMap<String, String>;
381
382/// What a choice asks for. Built with its constructors ([`FileRequest::open`]
383/// and the others) and their builders: a field added later breaks nobody.
384#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
385#[non_exhaustive]
386pub struct FileRequest {
387    pub kind: ChooseKind,
388    /// The chooser's title.
389    pub title: String,
390    /// Where it starts (the last recent place, else home, by default).
391    /// With a [`purpose`](Self::purpose), only until that purpose has a
392    /// last folder, unless [`force_directory`](Self::force_directory) said
393    /// otherwise.
394    #[serde(default)]
395    pub directory: Option<PathBuf>,
396    /// The key the last folder is remembered under. See
397    /// [`FileRequest::purpose`].
398    #[serde(default)]
399    pub purpose: Option<String>,
400    /// `directory` wins over the purpose's last folder. See
401    /// [`FileRequest::force_directory`].
402    #[serde(default)]
403    pub force_directory: bool,
404    /// The name proposed when saving.
405    #[serde(default)]
406    pub file_name: Option<String>,
407    #[serde(default)]
408    pub filters: Vec<FileFilter>,
409    /// Saving: the in-app picker asks before replacing an existing file
410    /// (on by default). See [`FileRequest::confirm_overwrite`].
411    #[serde(default = "asks")]
412    pub confirm_overwrite: bool,
413    /// Opening files, the application's groupings apply (on by default). See
414    /// [`FileRequest::ungrouped`].
415    #[serde(default = "asks")]
416    pub group_files: bool,
417    /// The application's options, shown beside the in-app picker's buttons.
418    /// See [`FileRequest::choice`].
419    #[serde(default)]
420    pub choices: Vec<FileChoice>,
421}
422
423fn asks() -> bool {
424    true
425}
426
427impl FileRequest {
428    fn new(kind: ChooseKind, title: &str) -> Self {
429        Self {
430            kind,
431            title: title.into(),
432            directory: None,
433            purpose: None,
434            force_directory: false,
435            file_name: None,
436            filters: Vec::new(),
437            confirm_overwrite: true,
438            group_files: true,
439            choices: Vec::new(),
440        }
441    }
442
443    /// One existing file.
444    pub fn open(title: &str) -> Self {
445        Self::new(ChooseKind::Open, title)
446    }
447
448    /// Existing files.
449    pub fn open_many(title: &str) -> Self {
450        Self::new(ChooseKind::OpenMany, title)
451    }
452
453    /// A file to write, `name` proposed.
454    pub fn save(title: &str, name: &str) -> Self {
455        Self::new(ChooseKind::Save, title).file_name(name)
456    }
457
458    /// A folder.
459    pub fn folder(title: &str) -> Self {
460        Self::new(ChooseKind::Folder, title)
461    }
462
463    pub fn directory(mut self, dir: impl Into<PathBuf>) -> Self {
464        self.directory = Some(dir.into());
465        self
466    }
467
468    /// The choice's purpose: its last folder is remembered under this key,
469    /// so an import and an export do not share one (Windows' `SetClientGuid`,
470    /// the `identifier` of a macOS panel). The next choice of that purpose
471    /// starts there: [`directory`](Self::directory) is then the first-time
472    /// default (Windows' `SetDefaultFolder`), and the start when the last
473    /// folder is gone, before home. Recent places stay global, and a purpose
474    /// does not start in them. Without a purpose nothing is remembered per
475    /// choice and `directory` always wins.
476    pub fn purpose(mut self, key: &str) -> Self {
477        self.purpose = Some(key.into());
478        self
479    }
480
481    /// Always starts in `dir` (Windows' `SetFolder`), over the purpose's last
482    /// folder, which the choice still updates: for a request that names the
483    /// folder that matters this time, as a document's own. When `dir` is gone,
484    /// the last folder, then home.
485    pub fn force_directory(mut self, dir: impl Into<PathBuf>) -> Self {
486        self.directory = Some(dir.into());
487        self.force_directory = true;
488        self
489    }
490
491    pub fn file_name(mut self, name: &str) -> Self {
492        self.file_name = Some(name.into());
493        self
494    }
495
496    /// Adds a filter (the first is the one shown first).
497    pub fn filter(mut self, name: &str, extensions: &[&str]) -> Self {
498        self.filters.push(FileFilter::new(name, extensions));
499        self
500    }
501
502    /// Whether the in-app picker asks before replacing an existing file
503    /// (on by default, as Windows' `FOS_OVERWRITEPROMPT` and GTK 4): off
504    /// for an application that asks itself. It holds for the in-app
505    /// picker only: the system's choosers ask on their own, and `rfd`
506    /// has no way to tell them not to.
507    pub fn confirm_overwrite(mut self, ask: bool) -> Self {
508        self.confirm_overwrite = ask;
509        self
510    }
511
512    /// Every file is an entry of its own and a choice gives no groups, whatever
513    /// the application's groupings ([`groups`]): for a choice that is after a
514    /// sidecar as much as a RAW. Saving and choosing a folder never group: a name
515    /// to save under must see every file it could replace.
516    pub fn ungrouped(mut self) -> Self {
517        self.group_files = false;
518        self
519    }
520
521    /// An option of the application's, a combo box offering `options`
522    /// (`(id, label)`) and starting on `default`: the in-app picker shows it
523    /// beside its buttons, and the choice gives back the value picked
524    /// ([`chosen_choices`]), as Windows' customize interface, macOS's accessory
525    /// view and the desktop portal's `choices` do; an import's "Only new
526    /// photos", an export's format. A request with choices opens the in-app
527    /// picker even where the system's chooser is used: `rfd` cannot show them.
528    pub fn choice(
529        mut self,
530        id: &str,
531        label: &str,
532        options: &[(&str, &str)],
533        default: &str,
534    ) -> Self {
535        self.choices.push(FileChoice {
536            id: id.into(),
537            label: label.into(),
538            options: options
539                .iter()
540                .map(|(id, label)| ((*id).into(), (*label).into()))
541                .collect(),
542            default: default.into(),
543        });
544        self
545    }
546
547    /// An option of the application's as a check box, on or off at first; its
548    /// value is `"true"` or `"false"`. See [`FileRequest::choice`].
549    pub fn check(mut self, id: &str, label: &str, default: bool) -> Self {
550        self.choices.push(FileChoice {
551            id: id.into(),
552            label: label.into(),
553            options: Vec::new(),
554            default: default.to_string(),
555        });
556        self
557    }
558
559    /// Each choice with the value it starts with.
560    pub fn choice_defaults(&self) -> ChoiceValues {
561        self.choices
562            .iter()
563            .map(|c| (c.id.clone(), c.default.clone()))
564            .collect()
565    }
566
567    /// `values` over the defaults, each checked: an unknown id or a value its
568    /// choice cannot take is refused.
569    pub fn choice_values(&self, values: &ChoiceValues) -> Result<ChoiceValues, String> {
570        let mut out = self.choice_defaults();
571        for (id, value) in values {
572            let c = self
573                .choices
574                .iter()
575                .find(|c| &c.id == id)
576                .ok_or_else(|| format!("no choice `{id}` in this request"))?;
577            if !c.accepts(value) {
578                return Err(format!("`{value}` is not a value of the choice `{id}`"));
579            }
580            out.insert(id.clone(), value.clone());
581        }
582        Ok(out)
583    }
584
585    pub fn to_json(&self) -> Json {
586        serde_json::to_value(self).unwrap_or(Json::Null)
587    }
588
589    pub fn from_json(json: &Json) -> Result<FileRequest, String> {
590        serde_json::from_value(json.clone()).map_err(|e| format!("not a file request: {e}"))
591    }
592}
593
594/// How a choice ended.
595#[derive(Clone, Debug, PartialEq, Eq)]
596pub enum Chosen {
597    Paths(Vec<PathBuf>),
598    Cancelled,
599}
600
601/// Reads a choice's result (what its [`Pending`] gives).
602pub fn chosen(result: &Result<Json, String>) -> Result<Chosen, String> {
603    let json = result.as_ref().map_err(Clone::clone)?;
604    if json.is_null() || json.get("cancelled").and_then(Json::as_bool) == Some(true) {
605        return Ok(Chosen::Cancelled);
606    }
607    Ok(Chosen::Paths(paths_of(json)))
608}
609
610/// Who answered a choice, from its result: the user (the picker, the
611/// system's chooser, a plugin's) unless an agent or a script answered it
612/// through the debug bridge. A consumer that should act only on a
613/// person's choice checks it.
614pub fn chosen_origin(result: &Result<Json, String>) -> Origin {
615    result
616        .as_ref()
617        .ok()
618        .and_then(|j| j.get("origin"))
619        .and_then(|o| serde_json::from_value(o.clone()).ok())
620        .unwrap_or(Origin::User)
621}
622
623/// The groups a choice's result holds ([`groups`]): one for each path chosen
624/// that heads a group, none otherwise. [`chosen`] gives the paths, each group's
625/// main among them; the members come from here.
626pub fn chosen_groups(result: &Result<Json, String>) -> Vec<FileGroup> {
627    result
628        .as_ref()
629        .map_or_else(|_| Vec::new(), groups::from_json)
630}
631
632/// The application's choices a choice ended with ([`FileRequest::choice`]):
633/// each id with its value, empty when cancelled or without choices.
634pub fn chosen_choices(result: &Result<Json, String>) -> ChoiceValues {
635    result
636        .as_ref()
637        .ok()
638        .and_then(|j| j.get("choices"))
639        .map(choices_of)
640        .unwrap_or_default()
641}
642
643fn choices_of(json: &Json) -> ChoiceValues {
644    json.as_object()
645        .map(|m| {
646            m.iter()
647                .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned())))
648                .collect()
649        })
650        .unwrap_or_default()
651}
652
653fn paths_of(json: &Json) -> Vec<PathBuf> {
654    json.get("paths")
655        .and_then(Json::as_array)
656        .map(|a| {
657            a.iter()
658                .filter_map(Json::as_str)
659                .map(PathBuf::from)
660                .collect()
661        })
662        .unwrap_or_default()
663}
664
665fn paths_json(paths: &[PathBuf]) -> Json {
666    json!(
667        paths
668            .iter()
669            .map(|p| p.display().to_string())
670            .collect::<Vec<_>>()
671    )
672}
673
674/// Who answers a choice.
675#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
676#[serde(rename_all = "snake_case")]
677pub enum Via {
678    Native,
679    InApp,
680    /// A plugin's run-hook on `file.choose`.
681    Hook,
682}
683
684/// What a choice ends with: paths, or `None` (cancelled).
685type Answer = Option<Vec<PathBuf>>;
686
687#[derive(Debug)]
688struct Open {
689    id: u64,
690    request: FileRequest,
691    via: Via,
692    resolver: Option<Resolver>,
693    answer: Arc<Mutex<Option<Answer>>>,
694    picker: Option<FilePicker>,
695    /// Its in-app picker is drawn by the caller ([`Files::show_inline`]),
696    /// not in a modal of its own.
697    inline: bool,
698    /// Who answered it: the user (the picker, a chooser) unless
699    /// [`Files::deliver_as`] says otherwise.
700    by: Origin,
701    /// The application's choices as whoever answered set them
702    /// ([`Files::set_choices`]), over the in-app picker's.
703    choices: Option<ChoiceValues>,
704    /// The window it was asked from (the window being drawn or commanded
705    /// then, else the active one): its in-app picker is shown over that
706    /// window's group (`AppHandle::window_group`); cancelled once that
707    /// window closes.
708    owner: egui::ViewportId,
709    /// What it is on the bus, once its open was asked: a popup, or a
710    /// native window for the system's chooser.
711    on_bus: Option<WindowKind>,
712}
713
714#[derive(Debug, Default)]
715struct State {
716    next: u64,
717    open: Vec<Open>,
718    /// The last choices: id, request title, outcome.
719    last: VecDeque<Json>,
720    /// The system's chooser is used when available (the setting).
721    native: bool,
722    /// The application allows the system's chooser
723    /// (`AppBuilder::system_file_chooser`).
724    allowed: bool,
725    /// Why the system's chooser is refused, as of the last frame.
726    refused: Option<&'static str>,
727    /// Where the in-app picker reads (none: the system's file system).
728    fs: Option<SharedFs>,
729    previews: Previews,
730    groupings: Groupings,
731    /// The application's sections of places.
732    place_providers: PlaceProviders,
733    /// The system's places, as read when a picker last opened.
734    system: Option<SystemPlaces>,
735    /// Where they come from (none: the system, [`places::system_places`]).
736    system_source: Option<PlaceSource>,
737    /// What the in-app picker's zoom means on a resize
738    /// ([`FilesPlugin::grid_resize`]).
739    resize: browser::GridResize,
740}
741
742/// Where the system's places come from ([`Files::set_system_places`]).
743#[derive(Clone)]
744struct PlaceSource(Arc<dyn Fn() -> SystemPlaces + Send + Sync>);
745
746impl std::fmt::Debug for PlaceSource {
747    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748        f.write_str("PlaceSource")
749    }
750}
751
752impl State {
753    /// The in-app picker commands speak to: the one in a modal first.
754    fn active_picker(&mut self) -> Option<&mut FilePicker> {
755        self.open
756            .iter_mut()
757            .filter(|o| o.picker.is_some())
758            .min_by_key(|o| o.inline)
759            .and_then(|o| o.picker.as_mut())
760    }
761}
762
763/// The choices open, as a service.
764#[derive(Clone, Debug, Default)]
765pub struct Files(Arc<Mutex<State>>);
766
767/// A window the system's chooser can be attached to: what gives its
768/// native handles, such as winit's window (eframe's
769/// `CreationContext::winit_window`).
770#[cfg(not(target_arch = "wasm32"))]
771pub trait ParentWindow:
772    raw_window_handle::HasWindowHandle + raw_window_handle::HasDisplayHandle + Send + Sync
773{
774}
775
776#[cfg(not(target_arch = "wasm32"))]
777impl<T> ParentWindow for T where
778    T: raw_window_handle::HasWindowHandle
779        + raw_window_handle::HasDisplayHandle
780        + Send
781        + Sync
782        + ?Sized
783{
784}
785
786/// A window's native handles, per window, for the system's chooser.
787#[cfg(not(target_arch = "wasm32"))]
788#[derive(Clone)]
789#[cfg_attr(
790    not(feature = "native-dialogs"),
791    allow(
792        dead_code,
793        reason = "only the native-dialogs chooser reads the parent's handles"
794    )
795)]
796struct Parent(Arc<dyn ParentWindow>);
797
798#[cfg(not(target_arch = "wasm32"))]
799impl std::fmt::Debug for Parent {
800    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
801        f.write_str("ParentWindow")
802    }
803}
804
805#[cfg(not(target_arch = "wasm32"))]
806const PARENT_WINDOW: egui_pop_core::state::Slot<Parent> =
807    egui_pop_core::state::Slot::new("api.files.parent_window");
808
809/// Records `window`'s native handles as the window `viewport`'s: a system
810/// chooser asked from that window (or a panel detached from it) is
811/// attached to it. `AppBuilder::run_native` records the main window's
812/// (`frame::record_native_window`); an application that has another
813/// window's handles records them, and forgets them when it closes
814/// ([`forget_parent_window`]). Without a window's handles, its chooser
815/// is attached to no window, never to another one.
816#[cfg(not(target_arch = "wasm32"))]
817pub fn set_parent_window(
818    ctx: &egui::Context,
819    viewport: egui::ViewportId,
820    window: Arc<dyn ParentWindow>,
821) {
822    PARENT_WINDOW.keyed(viewport).set(ctx, Parent(window));
823}
824
825/// Forgets the handles recorded for `viewport` ([`set_parent_window`]).
826#[cfg(not(target_arch = "wasm32"))]
827pub fn forget_parent_window(ctx: &egui::Context, viewport: egui::ViewportId) {
828    PARENT_WINDOW.keyed(viewport).remove(ctx);
829}
830
831/// Whether handles are recorded for `viewport` ([`set_parent_window`]).
832pub fn has_parent_window(ctx: &egui::Context, viewport: egui::ViewportId) -> bool {
833    #[cfg(not(target_arch = "wasm32"))]
834    {
835        PARENT_WINDOW.keyed(viewport).exists(ctx)
836    }
837    #[cfg(target_arch = "wasm32")]
838    {
839        let _ = (ctx, viewport);
840        false
841    }
842}
843
844/// The window a system chooser asked from `owner` is attached to: the
845/// application window `owner` belongs to (`AppHandle::window_group`) when
846/// its handles are recorded, else none. Never the main window for a
847/// choice asked from another window: attached there, the chooser would
848/// come up over the wrong window and block it.
849pub fn chooser_parent(app: &AppHandle, owner: egui::ViewportId) -> Option<egui::ViewportId> {
850    let window = picker_window(app, owner);
851    has_parent_window(&app.egui(), window).then_some(window)
852}
853
854/// Whether the system's chooser can be used here: the feature is on and,
855/// on Linux and the BSDs, a session bus is there for the portal.
856pub fn native_available() -> bool {
857    #[cfg(all(feature = "native-dialogs", not(target_arch = "wasm32")))]
858    {
859        if cfg!(any(
860            target_os = "linux",
861            target_os = "freebsd",
862            target_os = "openbsd",
863            target_os = "netbsd",
864            target_os = "dragonfly"
865        )) {
866            return std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some()
867                || std::env::var_os("XDG_RUNTIME_DIR")
868                    .is_some_and(|d| Path::new(&d).join("bus").exists());
869        }
870        true
871    }
872    #[cfg(not(all(feature = "native-dialogs", not(target_arch = "wasm32"))))]
873    false
874}
875
876/// The environment variable that refuses the system's chooser to a process,
877/// whatever its value: for test runs that drive an application without
878/// `egui_pop_test` (egui-pop's CI sets it).
879pub const TEST_ENV: &str = "EGUI_POP_TEST";
880
881/// Refused in this process ([`refuse_system_chooser`]).
882static REFUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
883
884/// Refuses the system's chooser in this process from now on, whatever the
885/// feature, the application and the setting say: the in-app picker answers
886/// every choice. One way. `egui_pop_test`'s harnesses call it, so that an
887/// application's own tests never open a dialog on the desktop.
888pub fn refuse_system_chooser() {
889    REFUSED.store(true, std::sync::atomic::Ordering::Relaxed);
890}
891
892/// Whether the system's chooser is refused here, whatever the feature, the
893/// application and the setting say: under tests, or with no window.
894/// [`system_chooser_refusal`] says why.
895pub fn system_chooser_refused(ctx: &egui::Context) -> bool {
896    system_chooser_refusal(ctx).is_some()
897}
898
899/// Why the system's chooser is refused here, the first reason found, or
900/// `None`:
901///
902/// - `"cfg(test)"`: this crate's own unit tests;
903/// - `"test harness"`: [`refuse_system_chooser`] was called (each of
904///   `egui_pop_test`'s harnesses does);
905/// - `"EGUI_POP_TEST"`: [`TEST_ENV`] is set;
906/// - `"nextest"`: the process is a test of cargo-nextest (`NEXTEST`);
907/// - `"no window"`: the frames come with no window's focus, as with
908///   egui_kittest or a bare `Context::run`. A window of eframe or
909///   egui-winit always says whether it has the focus.
910pub fn system_chooser_refusal(ctx: &egui::Context) -> Option<&'static str> {
911    if cfg!(test) {
912        Some("cfg(test)")
913    } else if REFUSED.load(std::sync::atomic::Ordering::Relaxed) {
914        Some("test harness")
915    } else if std::env::var_os(TEST_ENV).is_some() {
916        Some(TEST_ENV)
917    } else if std::env::var_os("NEXTEST").is_some() {
918        Some("nextest")
919    } else if ctx.input(|i| i.viewport().focused.is_none()) {
920        Some("no window")
921    } else {
922        None
923    }
924}
925
926impl Files {
927    /// Where the in-app picker reads.
928    pub fn file_system(&self) -> SharedFs {
929        lock(&self.0).fs.clone().unwrap_or_else(fs::native)
930    }
931
932    /// Reads from `fs` in the in-app pickers opened from now on.
933    pub fn set_file_system(&self, fs: SharedFs) {
934        lock(&self.0).fs = Some(fs);
935    }
936
937    /// The preview providers, their cache and their worker: a plugin
938    /// registers its providers here ([`Previews::register`]).
939    pub fn previews(&self) -> Previews {
940        lock(&self.0).previews.clone()
941    }
942
943    /// The groupings of files: a plugin declares its own here
944    /// ([`Groupings::register`]).
945    pub fn groupings(&self) -> Groupings {
946        lock(&self.0).groupings.clone()
947    }
948
949    /// The application's sections of places, listed by the in-app picker
950    /// under its own and by a [`places::PlacesPanel`]: a plugin declares
951    /// its own here ([`PlaceProviders::register`]).
952    pub fn place_providers(&self) -> PlaceProviders {
953        lock(&self.0).place_providers.clone()
954    }
955
956    /// The places as the in-app picker lists them now: home, the system's
957    /// folders and volumes (read when a picker last opened), recent places,
958    /// bookmarks and the application's sections. [`Places::sections`] gives
959    /// them as one list of sections, for a [`places::PlacesPanel`].
960    pub fn places(&self, app: &AppHandle) -> Places {
961        places(app, self)
962    }
963
964    /// The groups the paths of a finished choice head: none saving, choosing a
965    /// folder, for a request that turned them off, or with the person's box off.
966    fn groups_of(
967        &self,
968        app: &AppHandle,
969        request: &FileRequest,
970        paths: &[PathBuf],
971    ) -> Vec<FileGroup> {
972        let groups = matches!(request.kind, ChooseKind::Open | ChooseKind::OpenMany)
973            && request.group_files
974            && grouped(app);
975        if !groups {
976            return Vec::new();
977        }
978        self.groupings().of_paths(&self.file_system(), paths)
979    }
980
981    /// Starts a choice; its result comes later through the [`Pending`].
982    pub fn choose(&self, app: &AppHandle, request: FileRequest) -> Pending {
983        self.start_choice(app, request, false).1
984    }
985
986    /// Starts a choice whose in-app picker the caller draws itself, in a
987    /// dialog of its own ([`Files::show_inline`]); the system's chooser,
988    /// or a plugin's, is used the same way. Gives the choice's id.
989    pub fn choose_inline(&self, app: &AppHandle, request: FileRequest) -> (u64, Pending) {
990        self.start_choice(app, request, true)
991    }
992
993    fn start_choice(&self, app: &AppHandle, request: FileRequest, inline: bool) -> (u64, Pending) {
994        let (pending, resolver) = host::pending();
995        let owner = crate::windows::current_group().unwrap_or_else(|| app.active_window());
996        let id = {
997            let mut s = lock(&self.0);
998            s.next += 1;
999            let id = s.next;
1000            s.open.push(Open {
1001                id,
1002                request: request.clone(),
1003                via: Via::Hook,
1004                resolver: Some(resolver),
1005                answer: Arc::default(),
1006                picker: None,
1007                inline,
1008                by: Origin::User,
1009                choices: None,
1010                owner,
1011                on_bus: None,
1012            });
1013            id
1014        };
1015        let me = self.clone();
1016        let args = json!({ "id": id, "request": request.to_json() });
1017        let out = app.step(&STEP_CHOOSE, args, move |app, args| {
1018            let request = FileRequest::from_json(&args["request"])?;
1019            me.start(app, id, request)
1020        });
1021        let immediate = match out {
1022            Outcome::Vetoed { reason, .. } => Some(Err(reason)),
1023            Outcome::Done(Err(e)) => Some(Err(e)),
1024            Outcome::Done(Ok(v)) => {
1025                if let Some(c) = v.get("choices")
1026                    && let Err(e) = self.set_choices(id, &choices_of(c))
1027                {
1028                    log::warn!(target: "egui_pop", "file.choose: {e}");
1029                }
1030                if v.get("paths").is_some() {
1031                    let _ = self.deliver(id, Some(paths_of(&v)));
1032                } else if v.get("cancelled").and_then(Json::as_bool) == Some(true) {
1033                    let _ = self.deliver(id, None);
1034                }
1035                None
1036            }
1037        };
1038        if let Some(r) = immediate {
1039            let mut s = lock(&self.0);
1040            if let Some(at) = s.open.iter().position(|o| o.id == id)
1041                && let Some(resolver) = s.open.remove(at).resolver
1042            {
1043                resolver.resolve(r);
1044            }
1045        } else {
1046            self.open_on_bus(app, id);
1047        }
1048        app.egui().request_repaint();
1049        (id, pending)
1050    }
1051
1052    /// Asks the open of a choice under way: its in-app picker's (or a
1053    /// plugin's) popup, or the system chooser's native window, a child of
1054    /// the window it was asked from.
1055    fn open_on_bus(&self, app: &AppHandle, id: u64) {
1056        let Some((owner, via)) = lock(&self.0)
1057            .open
1058            .iter()
1059            .find(|o| o.id == id)
1060            .map(|o| (o.owner, o.via))
1061        else {
1062            return;
1063        };
1064        let kind = if via == Via::Native {
1065            WindowKind::Native
1066        } else {
1067            WindowKind::Popup
1068        };
1069        let req = WindowRequest::new(
1070            format!("{POPUP_PREFIX}{id}"),
1071            kind,
1072            PLUGIN.as_str(),
1073            Reason::Command,
1074        )
1075        .parent(app.registry_window_of(owner));
1076        let opened = if kind == WindowKind::Native {
1077            app.request_native_open(req)
1078        } else {
1079            app.overlay_on_its_own(overlay_id(id));
1080            app.request_popup_open(req)
1081        };
1082        if opened && let Some(o) = lock(&self.0).open.iter_mut().find(|o| o.id == id) {
1083            o.on_bus = Some(kind);
1084        }
1085    }
1086
1087    /// Cancels an open choice now (its popup or native window closing):
1088    /// the journal and its result say so. Whether one was open.
1089    fn cancel_now(&self, app: &AppHandle, id: u64) -> bool {
1090        let Some(o) = ({
1091            let mut s = lock(&self.0);
1092            s.open
1093                .iter()
1094                .position(|o| o.id == id)
1095                .map(|at| s.open.remove(at))
1096        }) else {
1097            return false;
1098        };
1099        overlay::close(&app.egui(), overlay_id(id));
1100        if o.picker.is_some() {
1101            self.previews().cancel();
1102        }
1103        finish(app, self, id, &o.request, None, o.resolver, &o.by);
1104        true
1105    }
1106
1107    /// Draws the in-app picker of a choice started with
1108    /// [`Files::choose_inline`], if it has one; says whether it did.
1109    pub fn show_inline(&self, ui: &mut Ui, app: &AppHandle, id: u64) -> bool {
1110        let Some((mut picker, answer, title)) = ({
1111            let s = lock(&self.0);
1112            s.open.iter().find(|o| o.id == id).and_then(|o| {
1113                o.picker
1114                    .clone()
1115                    .map(|p| (p, o.answer.clone(), o.request.title.clone()))
1116            })
1117        }) else {
1118            return false;
1119        };
1120        // Inside another dialog, the choice's title heads its picker.
1121        if !title.is_empty() {
1122            ui.strong(title);
1123        }
1124        load_view(app, &mut picker);
1125        let out = picker.show(ui, &places(app, self));
1126        keep_view(app, &picker);
1127        settle(app, id, &mut picker, &answer, out, true);
1128        self.keep(id, picker);
1129        true
1130    }
1131
1132    /// The window a choice was asked from ([`Files::choose`] called in its
1133    /// pass, or for its command): its in-app picker shows over that
1134    /// window's group. `None` once the choice is over.
1135    pub fn owner(&self, id: u64) -> Option<egui::ViewportId> {
1136        lock(&self.0)
1137            .open
1138            .iter()
1139            .find(|o| o.id == id)
1140            .map(|o| o.owner)
1141    }
1142
1143    /// The entry highlighted in the in-app picker of a choice (the one its
1144    /// preview is of, where the arrows are): what another panel follows
1145    /// (`docs/linked-panels.md`). `None` without a picker or an entry.
1146    pub fn highlighted(&self, id: u64) -> Option<Entry> {
1147        let mut s = lock(&self.0);
1148        let picker = s.open.iter_mut().find(|o| o.id == id)?.picker.as_mut()?;
1149        picker.highlighted()
1150    }
1151
1152    fn keep(&self, id: u64, picker: FilePicker) {
1153        let mut s = lock(&self.0);
1154        if let Some(o) = s.open.iter_mut().find(|o| o.id == id) {
1155            o.picker = Some(picker);
1156        }
1157    }
1158
1159    /// The default of `file.choose`: the in-app picker, or the system's
1160    /// chooser when the application allows it, the person wants it, it is
1161    /// there and it is not refused (tests).
1162    fn start(&self, app: &AppHandle, id: u64, request: FileRequest) -> Result<Json, String> {
1163        // `rfd` cannot show the application's choices: the in-app picker does.
1164        let native = {
1165            let s = lock(&self.0);
1166            s.allowed && s.native
1167        } && request.choices.is_empty()
1168            && native_available()
1169            && !system_chooser_refused(&app.egui());
1170        let fs = self.file_system();
1171        let previews = self.previews();
1172        let groupings = self.groupings();
1173        let show_preview = preview_wanted(app);
1174        let start = start_folder(app, &request, &fs);
1175        if !native {
1176            // Volumes come and go: read when a picker opens, not each frame.
1177            self.refresh_system_places();
1178        }
1179        let mut s = lock(&self.0);
1180        let resize = s.resize;
1181        let o = s
1182            .open
1183            .iter_mut()
1184            .find(|o| o.id == id)
1185            .ok_or("the choice is gone")?;
1186        o.request = request.clone();
1187        if native {
1188            o.via = Via::Native;
1189            let answer = o.answer.clone();
1190            let owner = o.owner;
1191            drop(s);
1192            let parent = chooser_parent(app, owner);
1193            native::start(&app.egui(), &request, start, parent, answer);
1194            return Ok(json!({ "via": "native", "attached": parent.is_some() }));
1195        }
1196        o.via = Via::InApp;
1197        let at = FileRequest {
1198            directory: start,
1199            ..request
1200        };
1201        let mut picker = FilePicker::new_in(&at, fs)
1202            .with_previews(previews)
1203            .with_grouping(groupings)
1204            .with_resize(resize);
1205        picker.show_preview = show_preview;
1206        o.picker = Some(picker);
1207        Ok(json!({ "via": "in_app" }))
1208    }
1209
1210    /// Answers a choice (applied on the next frame): paths, or `None`
1211    /// for cancelled, as the user. For a run-hook replacing the chooser.
1212    pub fn deliver(&self, id: u64, answer: Option<Vec<PathBuf>>) -> Result<(), String> {
1213        self.deliver_as(id, answer, Origin::User)
1214    }
1215
1216    /// As [`Files::deliver`], answered by `origin` (an agent through the
1217    /// debug bridge): the origin goes with the choice, to the
1218    /// `file.chosen` step (`origin`), the journal and the result
1219    /// ([`chosen_origin`]).
1220    pub fn deliver_as(
1221        &self,
1222        id: u64,
1223        answer: Option<Vec<PathBuf>>,
1224        origin: Origin,
1225    ) -> Result<(), String> {
1226        let mut s = lock(&self.0);
1227        let o = s
1228            .open
1229            .iter_mut()
1230            .find(|o| o.id == id)
1231            .ok_or_else(|| format!("no choice {id} is open"))?;
1232        o.by = origin;
1233        *lock(&o.answer) = Some(answer);
1234        Ok(())
1235    }
1236
1237    /// Sets the application's choices of an open choice ([`FileRequest::choice`])
1238    /// as its answer goes: for a run-hook replacing the chooser, with
1239    /// [`Files::deliver`]. The values are checked against the request; those
1240    /// not given keep the in-app picker's, else their defaults.
1241    pub fn set_choices(&self, id: u64, values: &ChoiceValues) -> Result<(), String> {
1242        let mut s = lock(&self.0);
1243        let o = s
1244            .open
1245            .iter_mut()
1246            .find(|o| o.id == id)
1247            .ok_or_else(|| format!("no choice {id} is open"))?;
1248        let mut base = o
1249            .choices
1250            .clone()
1251            .or_else(|| o.picker.as_ref().map(|p| p.choice_values.clone()))
1252            .unwrap_or_else(|| o.request.choice_defaults());
1253        base.extend(
1254            o.request
1255                .choice_values(values)?
1256                .into_iter()
1257                .filter(|(k, _)| values.contains_key(k)),
1258        );
1259        o.choices = Some(base);
1260        Ok(())
1261    }
1262
1263    /// Gives the system's places the in-app picker lists (its folders and the
1264    /// volumes mounted) from `source` rather than from the system
1265    /// ([`places::system_places`]): a demo's, a sandbox's, a test's. It is
1266    /// asked when a picker opens.
1267    pub fn set_system_places(&self, source: Arc<dyn Fn() -> SystemPlaces + Send + Sync>) {
1268        let mut s = lock(&self.0);
1269        s.system_source = Some(PlaceSource(source));
1270        s.system = None;
1271    }
1272
1273    /// The system's places as last read, read now if never.
1274    fn system_places(&self) -> SystemPlaces {
1275        if let Some(p) = lock(&self.0).system.clone() {
1276            return p;
1277        }
1278        self.refresh_system_places()
1279    }
1280
1281    /// Reads the system's places again: when a picker opens.
1282    fn refresh_system_places(&self) -> SystemPlaces {
1283        let source = lock(&self.0).system_source.clone();
1284        let read = match source {
1285            Some(PlaceSource(f)) => f(),
1286            None if cfg!(target_arch = "wasm32") => SystemPlaces::default(),
1287            None => places::system_places(),
1288        };
1289        lock(&self.0).system = Some(read.clone());
1290        read
1291    }
1292
1293    /// The choices open, by id.
1294    pub fn open_ids(&self) -> Vec<u64> {
1295        lock(&self.0).open.iter().map(|o| o.id).collect()
1296    }
1297
1298    /// The choices open and the last ones, as the bridge shows them.
1299    pub fn describe(&self) -> Json {
1300        let s = lock(&self.0);
1301        json!({
1302            "native": s.native,
1303            "native_allowed": s.allowed,
1304            "native_available": native_available(),
1305            "native_refused": s.refused,
1306            "open": s.open.iter().map(|o| {
1307                let mut d = json!({ "id": o.id, "request": o.request.to_json(), "via": o.via });
1308                if let Some(p) = &o.picker {
1309                    d["picker"] = p.clone().describe();
1310                }
1311                d
1312            }).collect::<Vec<_>>(),
1313            "last": s.last.iter().cloned().collect::<Vec<_>>(),
1314            "previews": s.previews.describe(),
1315            "groupings": s.groupings.ids(),
1316            "place_providers": s.place_providers.ids(),
1317        })
1318    }
1319
1320    /// `file.select_all`, `file.toggle_selection` and `file.edit_path`: on the open in-app
1321    /// picker (the one in a modal first); gives how many are selected.
1322    fn select_on(
1323        &self,
1324        app: &AppHandle,
1325        select: impl FnOnce(&mut FilePicker) -> Result<(), String>,
1326    ) -> Result<Json, String> {
1327        let selected = {
1328            let mut s = lock(&self.0);
1329            let picker = s.active_picker().ok_or("no in-app file picker is open")?;
1330            select(picker)?;
1331            picker.selected.len()
1332        };
1333        app.egui().request_repaint();
1334        Ok(json!({ "selected": selected }))
1335    }
1336
1337    /// `file.new_folder`: in the open in-app picker (the one in a modal
1338    /// first), asks the new folder's name, or makes it with `name`.
1339    fn new_folder(&self, app: &AppHandle, name: Option<&str>) -> Result<Json, String> {
1340        let made = {
1341            let mut s = lock(&self.0);
1342            let picker = s.active_picker().ok_or("no in-app file picker is open")?;
1343            if picker.asking.is_some() {
1344                return Err("the picker waits for its question's answer".into());
1345            }
1346            match name {
1347                Some(name) => Some(picker.create_folder(name)?),
1348                None => {
1349                    picker.begin_new_folder()?;
1350                    None
1351                }
1352            }
1353        };
1354        app.egui().request_repaint();
1355        Ok(match made {
1356            Some(path) => {
1357                folder_created(app, &path);
1358                json!({ "path": path.display().to_string() })
1359            }
1360            None => json!({ "naming": true }),
1361        })
1362    }
1363
1364    /// The in-app picker of an open choice (tests and agents drive it).
1365    pub fn picker(&self, id: u64) -> Option<FilePicker> {
1366        lock(&self.0)
1367            .open
1368            .iter()
1369            .find(|o| o.id == id)
1370            .and_then(|o| o.picker.clone())
1371    }
1372
1373    fn note(&self, id: u64, title: &str, outcome: Json, by: &str) {
1374        let mut s = lock(&self.0);
1375        if s.last.len() == 16 {
1376            s.last.pop_front();
1377        }
1378        s.last
1379            .push_back(json!({ "id": id, "title": title, "outcome": outcome, "by": by }));
1380    }
1381}
1382
1383/// A list of paths kept in the store as JSON text.
1384fn read_list(app: &AppHandle, path: &str) -> Vec<PathBuf> {
1385    lock(&app.store())
1386        .get(path)
1387        .and_then(|e| e.value.as_text().map(str::to_string))
1388        .and_then(|t| serde_json::from_str::<Vec<String>>(&t).ok())
1389        .unwrap_or_default()
1390        .into_iter()
1391        .map(PathBuf::from)
1392        .collect()
1393}
1394
1395fn write_list(app: &AppHandle, path: &str, list: &[PathBuf]) {
1396    let text = serde_json::to_string(
1397        &list
1398            .iter()
1399            .map(|p| p.display().to_string())
1400            .collect::<Vec<_>>(),
1401    )
1402    .unwrap_or_default();
1403    write_text(app, path, text);
1404}
1405
1406fn write_text(app: &AppHandle, path: &str, text: String) {
1407    let set = Set::new(path, Change::To(Value::Text(text)), Origin::User)
1408        .by(&OwnerId::FRAMEWORK)
1409        .untracked();
1410    if let Err(e) = lock(&app.store()).set(set) {
1411        log::warn!(target: "egui_pop", "files: keeping {path}: {e:?}");
1412    }
1413}
1414
1415/// The recent places, newest first.
1416pub fn recent(app: &AppHandle) -> Vec<PathBuf> {
1417    read_list(app, RECENT)
1418}
1419
1420/// The bookmarked folders.
1421pub fn bookmarks(app: &AppHandle) -> Vec<PathBuf> {
1422    read_list(app, BOOKMARKS)
1423}
1424
1425/// Bookmarks a folder, or removes its bookmark (and the name it was given).
1426pub fn set_bookmark(app: &AppHandle, dir: &Path, on: bool) {
1427    let mut list = bookmarks(app);
1428    list.retain(|p| p != dir);
1429    if on {
1430        list.push(dir.to_path_buf());
1431    } else {
1432        rename_bookmark(app, dir, "");
1433    }
1434    write_list(app, BOOKMARKS, &list);
1435}
1436
1437/// The names given to bookmarks, by folder.
1438pub fn bookmark_names(app: &AppHandle) -> Vec<(PathBuf, String)> {
1439    lock(&app.store())
1440        .get(BOOKMARK_NAMES)
1441        .and_then(|e| e.value.as_text().map(str::to_string))
1442        .and_then(|t| serde_json::from_str(&t).ok())
1443        .unwrap_or_default()
1444}
1445
1446/// Gives a bookmark a name of its own in the picker's side bar; an empty name
1447/// (or only spaces) gives it back its folder's.
1448pub fn rename_bookmark(app: &AppHandle, dir: &Path, name: &str) {
1449    let mut names = bookmark_names(app);
1450    let before = names.len();
1451    names.retain(|(d, _)| d != dir);
1452    let name = name.trim();
1453    if name.is_empty() && names.len() == before {
1454        return;
1455    }
1456    if !name.is_empty() {
1457        names.push((dir.to_path_buf(), name.to_owned()));
1458    }
1459    // A folder whose name is not Unicode cannot be kept: the names stay as they were.
1460    if let Ok(text) = serde_json::to_string(&names) {
1461        write_text(app, BOOKMARK_NAMES, text);
1462    }
1463}
1464
1465/// Moves a bookmark to `to` in the list (clamped to its end).
1466pub fn move_bookmark(app: &AppHandle, dir: &Path, to: usize) {
1467    let mut list = bookmarks(app);
1468    let Some(at) = list.iter().position(|p| p == dir) else {
1469        return;
1470    };
1471    let d = list.remove(at);
1472    list.insert(to.min(list.len()), d);
1473    write_list(app, BOOKMARKS, &list);
1474}
1475
1476/// Remembers the folders of chosen paths as recent places.
1477pub fn remember(app: &AppHandle, paths: &[PathBuf]) {
1478    let mut list = recent(app);
1479    for p in paths.iter().rev() {
1480        let dir = if p.is_dir() {
1481            p.clone()
1482        } else {
1483            match p.parent() {
1484                Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(),
1485                _ => continue,
1486            }
1487        };
1488        list.retain(|x| *x != dir);
1489        list.insert(0, dir);
1490    }
1491    list.truncate(RECENT_KEPT);
1492    write_list(app, RECENT, &list);
1493}
1494
1495/// The last folders by purpose, newest first.
1496fn last_folders(app: &AppHandle) -> Vec<(String, PathBuf)> {
1497    lock(&app.store())
1498        .get(LAST_FOLDERS)
1499        .and_then(|e| e.value.as_text().map(str::to_string))
1500        .and_then(|t| serde_json::from_str(&t).ok())
1501        .unwrap_or_default()
1502}
1503
1504/// The last folder of a purpose ([`FileRequest::purpose`]), whether or not it
1505/// still exists.
1506pub fn last_folder(app: &AppHandle, purpose: &str) -> Option<PathBuf> {
1507    last_folders(app)
1508        .into_iter()
1509        .find_map(|(p, dir)| (p == purpose).then_some(dir))
1510}
1511
1512/// Keeps the folder of a finished choice under its purpose, if it has one: the
1513/// folder chosen, or the first path's parent.
1514fn remember_folder(app: &AppHandle, request: &FileRequest, paths: &[PathBuf]) {
1515    let (Some(purpose), Some(first)) = (&request.purpose, paths.first()) else {
1516        return;
1517    };
1518    let dir = if request.kind == ChooseKind::Folder {
1519        Some(first.as_path())
1520    } else {
1521        first.parent()
1522    };
1523    let Some(dir) = dir.filter(|d| !d.as_os_str().is_empty()) else {
1524        return;
1525    };
1526    let mut list = last_folders(app);
1527    list.retain(|(p, _)| p != purpose);
1528    list.insert(0, (purpose.clone(), dir.to_path_buf()));
1529    list.truncate(LAST_FOLDERS_KEPT);
1530    // A folder whose name is not Unicode cannot be kept: the list stays as it was.
1531    if let Ok(text) = serde_json::to_string(&list) {
1532        write_text(app, LAST_FOLDERS, text);
1533    }
1534}
1535
1536/// Where a choice starts. Without a purpose, the request's folder else the
1537/// last recent place, as given (the in-app picker checks it, the system's
1538/// chooser does its own). With one, the first that exists: its last folder,
1539/// the request's folder (the other way round when forced), home.
1540fn start_folder(app: &AppHandle, request: &FileRequest, fs: &SharedFs) -> Option<PathBuf> {
1541    let Some(purpose) = &request.purpose else {
1542        return request
1543            .directory
1544            .clone()
1545            .or_else(|| recent(app).first().cloned());
1546    };
1547    let existing = |d: Option<PathBuf>| d.filter(|d| fs.is_dir(d));
1548    let last = existing(last_folder(app, purpose));
1549    let asked = existing(request.directory.clone());
1550    let (first, second) = if request.force_directory {
1551        (asked, last)
1552    } else {
1553        (last, asked)
1554    };
1555    first.or(second).or_else(|| existing(home()))
1556}
1557
1558/// The plugin's id.
1559pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.files");
1560
1561/// The files plugin's listener on `pop.popup.close` and `pop.window.close`: the
1562/// choice of that popup or native window is cancelled, whoever asked (its
1563/// window closing, among others).
1564pub const CHOICE_LISTENER: &str = "pop.files.choice";
1565/// A choice's id in the registry: `file:<id>`.
1566pub const POPUP_PREFIX: &str = "file:";
1567
1568/// The plugin.
1569#[derive(Clone, Debug)]
1570pub struct FilesPlugin {
1571    fs: Option<SharedFs>,
1572    builtin_previews: bool,
1573    groupings: Vec<Arc<dyn FileGrouping>>,
1574    places: Vec<Arc<dyn PlaceProvider>>,
1575    resize: browser::GridResize,
1576}
1577
1578impl Default for FilesPlugin {
1579    /// The in-app picker; the system's chooser only where the application
1580    /// allows it (`AppBuilder::system_file_chooser`).
1581    fn default() -> Self {
1582        Self {
1583            fs: None,
1584            builtin_previews: true,
1585            groupings: Vec::new(),
1586            places: Vec::new(),
1587            resize: browser::GridResize::default(),
1588        }
1589    }
1590}
1591
1592impl FilesPlugin {
1593    /// The in-app picker: the same as [`FilesPlugin::default`], which no
1594    /// longer turns to the system's chooser by itself.
1595    pub fn in_app() -> Self {
1596        Self::default()
1597    }
1598
1599    /// The in-app picker reads from `fs` (a [`fs::MemoryFs`], say), not
1600    /// from the system's file system.
1601    pub fn file_system(mut self, fs: SharedFs) -> Self {
1602        self.fs = Some(fs);
1603        self
1604    }
1605
1606    /// Without the built-in preview providers ([`providers::builtin`]):
1607    /// only those plugins register.
1608    pub fn without_builtin_previews(mut self) -> Self {
1609        self.builtin_previews = false;
1610        self
1611    }
1612
1613    /// Files that go together are one entry of the in-app picker, by this
1614    /// grouping of the application's ([`groups`]). egui-pop declares none of its
1615    /// own. Several apply in the order given.
1616    pub fn grouping(mut self, grouping: Arc<dyn FileGrouping>) -> Self {
1617        self.groupings.push(grouping);
1618        self
1619    }
1620
1621    /// Sections of places of the application's, listed by the in-app picker
1622    /// under its own and by a [`places::PlacesPanel`] ([`places`]).
1623    /// Several come in the order given.
1624    pub fn places(mut self, provider: Arc<dyn PlaceProvider>) -> Self {
1625        self.places.push(provider);
1626        self
1627    }
1628
1629    /// What the in-app picker's thumbnail zoom means when its grid is
1630    /// resized ([`browser::GridResize::PerRow`] by default): a count per
1631    /// row ([`THUMBNAILS_PER_ROW`]), or a size that keeps the thumbnails'
1632    /// size and adds columns ([`THUMBNAIL_POINTS`]).
1633    pub fn grid_resize(mut self, resize: browser::GridResize) -> Self {
1634        self.resize = resize;
1635        self
1636    }
1637}
1638
1639impl Plugin for FilesPlugin {
1640    fn id(&self) -> PluginId {
1641        PLUGIN
1642    }
1643
1644    fn title(&self) -> String {
1645        "Files".into()
1646    }
1647
1648    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1649        let files = Files::default();
1650        let allowed = ctx.app().system_file_chooser();
1651        {
1652            let mut s = lock(&files.0);
1653            s.allowed = allowed;
1654            s.resize = self.resize;
1655        }
1656        if let Some(fs) = self.fs.clone() {
1657            files.set_file_system(fs);
1658        }
1659        if self.builtin_previews {
1660            for p in providers::builtin() {
1661                files.previews().register(p);
1662            }
1663        }
1664        for grouping in &self.groupings {
1665            files.groupings().register(grouping.clone());
1666        }
1667        for provider in &self.places {
1668            files.place_providers().register(provider.clone());
1669        }
1670        // Only where the application allows the system's chooser: elsewhere
1671        // the setting would change nothing.
1672        if allowed {
1673            ctx.setting(
1674                SETTING_NATIVE,
1675                Descriptor::bool("Use the system's file chooser", true).description(
1676                    "Choose files with the system's chooser when there is one; off, with egui-pop's own.",
1677                ),
1678            )?;
1679        }
1680        ctx.setting(
1681            SETTING_PREVIEW,
1682            Descriptor::bool("Previews in the file picker", true).description(
1683                "egui-pop's file picker shows the selected file's preview and facts beside the list; Alt+P shows or hides it.",
1684            ),
1685        )?;
1686        ctx.setting(
1687            SETTING_FOLDERS_FIRST,
1688            Descriptor::bool("Folders first in the file picker", true).description(
1689                "egui-pop's file picker lists folders before files in every order; off, they sort among the files.",
1690            ),
1691        )?;
1692        {
1693            let store = ctx.app().store();
1694            let mut store = lock(&store);
1695            for (path, label) in [
1696                (RECENT, "Recent places"),
1697                (BOOKMARKS, "Bookmarks"),
1698                (BOOKMARK_NAMES, "Bookmark names"),
1699                (LAST_FOLDERS, "Last folders by purpose"),
1700                (VIEWS, "File views by dialog"),
1701            ] {
1702                store
1703                    .declare(
1704                        ctx.owner(),
1705                        path,
1706                        Descriptor::text(label, "[]").capacity(16_384),
1707                    )
1708                    .map_err(|e| PluginError::Failed(format!("{path}: {e:?}")))?;
1709            }
1710            // No settings of their own in the settings window: dragged,
1711            // not typed.
1712            let size = [f64::from(PICKER_WIDTH), f64::from(PICKER_HEIGHT)];
1713            for (path, descriptor) in [
1714                (
1715                    DIALOG_SIZE,
1716                    Descriptor::floats("File picker size", 2, 0.0, MAX_LENGTH, &size),
1717                ),
1718                (
1719                    PANE_WIDTH,
1720                    Descriptor::float(
1721                        "File picker preview width",
1722                        0.0,
1723                        MAX_LENGTH,
1724                        f64::from(preview::PANE_WIDTH),
1725                    ),
1726                ),
1727                (
1728                    VIEW,
1729                    Descriptor::choice(
1730                        "File picker view",
1731                        &[
1732                            PickerView::List.as_str(),
1733                            PickerView::Grid.as_str(),
1734                            PickerView::Columns.as_str(),
1735                        ],
1736                        browser::MODE_DETAILS,
1737                    ),
1738                ),
1739                (
1740                    THUMBNAILS_PER_ROW,
1741                    Descriptor::int(
1742                        "File picker thumbnails per row",
1743                        0,
1744                        i64::from(browser::ThumbZoom::MOST),
1745                        0,
1746                    )
1747                    .description("0: as first shown, or as an older version kept it."),
1748                ),
1749                (
1750                    THUMBNAIL_POINTS,
1751                    Descriptor::float("File picker thumbnail size", 0.0, MAX_LENGTH, 0.0)
1752                        .description("0: the count per row kept, converted. Read when the grid keeps the size on a resize."),
1753                ),
1754                (
1755                    SORT,
1756                    Descriptor::text("File picker order", &PickerSort::default().as_text()),
1757                ),
1758                (GROUPED, Descriptor::bool("File picker groups files", true)),
1759            ] {
1760                store
1761                    .declare(ctx.owner(), path, descriptor)
1762                    .map_err(|e| PluginError::Failed(format!("{path}: {e:?}")))?;
1763            }
1764        }
1765        ctx.service(&FILES, files.clone())?;
1766        ctx.step(
1767            StepSpec::new(
1768                STEP_CHOOSE,
1769                "A choice of files starts; a run-hook replaces the chooser (answer `paths` or `cancelled`, and `choices` for the request's, or later through `Files::deliver`).",
1770            )
1771            .args(json!({ "id": 1, "request": FileRequest::open("Open").to_json() })),
1772        )?;
1773        ctx.step(
1774            StepSpec::new(
1775                STEP_CHOSEN,
1776                "Paths were chosen, with the request's `choices` when it has some; a veto refuses them, a redirect changes them.",
1777            )
1778            .args(json!({ "id": 1, "request": FileRequest::open("Open").to_json(), "paths": ["/tmp/a.png"] })),
1779        )?;
1780        let f = files.clone();
1781        ctx.command(
1782            CommandSpec::new(CMD_PREVIEW, "Preview a file", "File")
1783                .description("A file's or a folder's preview metadata (`path`), as the in-app picker shows it: whether it is a folder, its size and modification time, the provider, the kind of preview, dimensions, pages, a folder's counts, the provider's facts, or why there is none; no pixels and no text.")
1784                .args(json!({ "path": "/tmp/a.png" }))
1785                .hidden()
1786                .read_only(),
1787            move |call| {
1788                let path = call
1789                    .args
1790                    .get("path")
1791                    .and_then(Json::as_str)
1792                    .ok_or("`path` is missing")?;
1793                preview_metadata(&f, Path::new(path))
1794            },
1795        )?;
1796        let f = files.clone();
1797        ctx.command(
1798            CommandSpec::new(CMD_NEW_FOLDER, "New folder", "File")
1799                .description("A new folder in the open in-app file picker, which then shows it: asks its name, or makes it at once with `name`. Refused on a file system that cannot make one (the web build's, in memory), the reason shown in the picker.")
1800                .args(json!({ "name": "Exports" }))
1801                .when(WHEN_NEW_FOLDER)
1802                .key_with("Ctrl+Shift+N", BindOptions::global().through_modal()),
1803            move |call| {
1804                let name = call.args.get("name").and_then(Json::as_str);
1805                f.new_folder(call.app, name)
1806            },
1807        )?;
1808        let f = files.clone();
1809        ctx.command(
1810            CommandSpec::new(CMD_SELECT_ALL, "Select all files", "File")
1811                .description("Selects every file shown in the open in-app file picker, choosing several. Refused, the reason shown in the picker, when none is shown.")
1812                .when(WHEN_SELECT_ALL)
1813                .key_with("Ctrl+A", BindOptions::global().through_modal()),
1814            move |call| f.select_on(call.app, FilePicker::select_all),
1815        )?;
1816        let f = files.clone();
1817        ctx.command(
1818            CommandSpec::new(CMD_TOGGLE_SELECTION, "Select or unselect the entry", "File")
1819                .description("Selects or unselects the highlighted entry of the open in-app file picker, choosing several files or a folder. A folder among files is not selected: the picker says so.")
1820                .when(WHEN_SELECTS)
1821                .key_with("Ctrl+Space", BindOptions::global().through_modal()),
1822            move |call| {
1823                f.select_on(call.app, |p| {
1824                    p.toggle();
1825                    Ok(())
1826                })
1827            },
1828        )?;
1829        let f = files.clone();
1830        ctx.command(
1831            CommandSpec::new(CMD_EDIT_PATH, "Edit the folder's path", "File")
1832                .description("Puts the folder of the open in-app file picker into its field, as a path to edit; saving, the name stays at its end. A path already typed stays as it is.")
1833                .when(WHEN_EDIT_PATH)
1834                .key_with("Ctrl+L", BindOptions::global().through_modal()),
1835            move |call| {
1836                f.select_on(call.app, |p| {
1837                    p.edit_path();
1838                    Ok(())
1839                })
1840            },
1841        )?;
1842        // Literal titles and descriptions: the catalogue's extractor reads them.
1843        let keyed = |spec: CommandSpec, keys: &str, id: CommandId| {
1844            let f = files.clone();
1845            let spec = spec.key_with(keys, BindOptions::global().through_modal());
1846            (spec, move |call: &crate::app::Call<'_>| {
1847                f.select_on(call.app, |p| {
1848                    p.run_key(&id);
1849                    Ok(())
1850                })
1851            })
1852        };
1853        let (spec, run) = keyed(
1854            CommandSpec::new(CMD_TOGGLE_HIDDEN, "Show or hide hidden files", "File")
1855                .description("Shows or hides the hidden files of the open in-app file picker.")
1856                .when(WHEN_EDIT_PATH),
1857            "Ctrl+H",
1858            CMD_TOGGLE_HIDDEN,
1859        );
1860        ctx.command(spec, run)?;
1861        let (spec, run) = keyed(
1862            CommandSpec::new(CMD_RELOAD, "Reload the folder", "File")
1863                .description("Reads the folder of the open in-app file picker again.")
1864                .when(WHEN_EDIT_PATH),
1865            "F5",
1866            CMD_RELOAD,
1867        );
1868        ctx.command(spec, run)?;
1869        let (spec, run) = keyed(
1870            CommandSpec::new(CMD_BACK, "Back", "File").description(
1871                "The open in-app file picker goes back to the folder it showed before; nothing when there is none.",
1872            )
1873            // In a modal only: outside one, Alt+Left is the context stack's back.
1874            .when(WHEN_IN_MODAL),
1875            "Alt+Left",
1876            CMD_BACK,
1877        );
1878        ctx.command(spec, run)?;
1879        let (spec, run) = keyed(
1880            CommandSpec::new(CMD_FORWARD, "Forward", "File").description(
1881                "The open in-app file picker goes forward to the folder it went back from; nothing when there is none.",
1882            )
1883            .when(WHEN_IN_MODAL),
1884            "Alt+Right",
1885            CMD_FORWARD,
1886        );
1887        ctx.command(spec, run)?;
1888        for n in 1..=browser::MODE_KEYS {
1889            let f = files.clone();
1890            let id = CommandId::new(format!("{CMD_VIEW_MODE}{n}"))
1891                .map_err(|e| PluginError::Failed(format!("{CMD_VIEW_MODE}{n}: {e:?}")))?;
1892            ctx.command(
1893                CommandSpec::new(id, &format!("View mode {n}"), "File")
1894                    .description(&format!("Shows the entries of the file browser holding the keyboard (the open in-app file picker first) in its mode number {n}, in the order of its switcher; nothing when it has fewer modes."))
1895                    .when(WHEN_BROWSER)
1896                    .key_with(&format!("Ctrl+{n}"), BindOptions::global().through_modal()),
1897                move |call| {
1898                    // The picker reads its view from the store each frame:
1899                    // the change goes there.
1900                    let dialog = lock(&f.0)
1901                        .active_picker()
1902                        .map(|p| (p.dialog.clone(), p.views()))
1903                        .filter(|(_, views)| views.len() > 1);
1904                    match dialog {
1905                        Some((dialog, views)) => {
1906                            if let Some(view) = n.checked_sub(1).and_then(|i| views.get(i)) {
1907                                want_view_for(call.app, &dialog, view.as_str());
1908                            }
1909                        }
1910                        None => browser::request_mode(&call.app.egui(), n),
1911                    }
1912                    call.app.egui().request_repaint();
1913                    Ok(Json::Null)
1914                },
1915            )?;
1916        }
1917        ctx.command(
1918            CommandSpec::new(CMD_TOGGLE_PREVIEW, "Show or hide the preview", "File")
1919                .description("Shows or hides the preview pane of the in-app file picker, kept for the next one (the `files.preview` setting).")
1920                .when(WHEN_EDIT_PATH)
1921                .key_with("Alt+P", BindOptions::global().through_modal()),
1922            move |call| {
1923                want_preview(call.app, !preview_wanted(call.app));
1924                call.app.egui().request_repaint();
1925                Ok(Json::Null)
1926            },
1927        )?;
1928        let f = files.clone();
1929        ctx.command(
1930            CommandSpec::new(CMD_REPLACE, "Replace the file", "File")
1931                .description("The answer to the question before replacing a file: ends the choice `id` with `path`.")
1932                .args(json!({ "id": 1, "path": "/tmp/a.png" }))
1933                .hidden(),
1934            move |call| {
1935                let id = call.args.get("id").and_then(Json::as_u64).ok_or("`id` is missing")?;
1936                let path = call.args.get("path").and_then(Json::as_str).ok_or("`path` is missing")?;
1937                f.deliver(id, Some(vec![PathBuf::from(path)]))?;
1938                call.app.egui().request_repaint();
1939                Ok(Json::Null)
1940            },
1941        )?;
1942        let (a, b) = (files.clone(), files.clone());
1943        ctx.collector(
1944            FnCollector::new(
1945                "files",
1946                "The file choices open (request, chooser, the in-app picker's folder and entries) and the last ones (`by`: who answered); `answer` answers one as its caller.",
1947            )
1948            .snapshot(move |_| a.describe())
1949            .action_as(
1950                "answer",
1951                "Answers a choice as its caller (the origin goes with the result): `id`, and `paths` (a list) or `cancel: true`; `choices` (id to value) sets the application's options, checked against the request.",
1952                true,
1953                move |_, args, origin| {
1954                    let id = args.get("id").and_then(Json::as_u64).ok_or("`id` is missing")?;
1955                    let answer = if args.get("cancel").and_then(Json::as_bool) == Some(true) {
1956                        None
1957                    } else {
1958                        Some(paths_of(args))
1959                    };
1960                    if let Some(c) = args.get("choices") {
1961                        b.set_choices(id, &choices_of(c))?;
1962                    }
1963                    b.deliver_as(id, answer, origin.clone())?;
1964                    Ok(json!({ "queued": true }))
1965                },
1966            )
1967            .args(json!({ "id": 1, "paths": ["/tmp/a.png"] })),
1968        )?;
1969        // In every window: each in-app picker is drawn over the window it
1970        // was asked from, before the dialogs (a question over it).
1971        ctx.block(
1972            zones::WINDOW_OVERLAYS,
1973            Block::add(BlockId::from_static("egui_pop.files"), 9, frame),
1974        );
1975        listen(&ctx.app());
1976        Ok(())
1977    }
1978}
1979
1980/// The choice a popup or native window of the registry is, if any.
1981fn choice_of(req: &WindowRequest) -> Option<u64> {
1982    req.window.strip_prefix(POPUP_PREFIX)?.parse().ok()
1983}
1984
1985/// [`CHOICE_LISTENER`] on a popup or native window closing: its choice,
1986/// if still open, is cancelled in this call.
1987fn cancel_on_close(req: &WindowRequest, did: &mut Vec<String>) -> Result<(), HookError> {
1988    let Some(id) = choice_of(req) else {
1989        return Ok(());
1990    };
1991    let Some(app) = crate::bus::asking() else {
1992        return Ok(());
1993    };
1994    let Some(files) = app.service(&FILES) else {
1995        return Ok(());
1996    };
1997    if files.cancel_now(&app, id) {
1998        did.push(format!(
1999            "{CHOICE_LISTENER}: choice {id} cancelled ({})",
2000            req.reason.as_str()
2001        ));
2002    }
2003    Ok(())
2004}
2005
2006/// Registers the files plugin's listener on the bus, replacing that of an
2007/// earlier connection: [`CHOICE_LISTENER`] on `pop.popup.close` (the in-app
2008/// picker's popup) and `pop.window.close` (the system chooser's window).
2009fn listen(app: &AppHandle) {
2010    let bus = app.bus();
2011    bus.unlisten(&PopupClose::ID, CHOICE_LISTENER);
2012    bus.unlisten(&WindowClose::ID, CHOICE_LISTENER);
2013    let mine = || ListenOpts::new().owner(PLUGIN.as_str());
2014    let listened = [
2015        bus.listen::<PopupClose>(CHOICE_LISTENER, mine().before(REGISTRY), cancel_on_close),
2016        bus.listen::<WindowClose>(
2017            CHOICE_LISTENER,
2018            mine().after(CHILDREN).before(FOCUS),
2019            cancel_on_close,
2020        ),
2021    ];
2022    for l in listened {
2023        if let Err(e) = l {
2024            log::error!(target: "egui_pop", "{e}");
2025        }
2026    }
2027}
2028
2029/// Polls the choices, finishes the answered ones, draws the in-app
2030/// picker of the first one open.
2031fn frame(ui: &mut Ui, app: &AppHandle) {
2032    let Some(files) = app.service(&FILES) else {
2033        return;
2034    };
2035    let native = lock(&app.store())
2036        .get(&format!("settings/{SETTING_NATIVE}"))
2037        .and_then(|e| e.value.as_bool())
2038        .unwrap_or(false);
2039    let refused = system_chooser_refusal(ui.ctx());
2040    let browsing = browser::take_focused(ui.ctx());
2041    let (new_folder, select_all, selects, edit_path, picker_modes) = {
2042        let mut s = lock(&files.0);
2043        s.native = native;
2044        s.refused = refused;
2045        let any = |test: &dyn Fn(&FilePicker) -> bool| {
2046            s.open
2047                .iter()
2048                .filter_map(|o| o.picker.as_ref())
2049                .any(|p| p.asking.is_none() && test(p))
2050        };
2051        (
2052            any(&FilePicker::makes_folders),
2053            any(&|p| p.kind == ChooseKind::OpenMany && !p.is_path()),
2054            any(&FilePicker::selects_apart),
2055            any(&|_| true),
2056            any(&|p| p.previews.is_some()),
2057        )
2058    };
2059    let say = |on: bool| if on { "true" } else { "false" };
2060    app.set_context(WHEN_NEW_FOLDER, say(new_folder));
2061    app.set_context(WHEN_SELECT_ALL, say(select_all));
2062    app.set_context(WHEN_SELECTS, say(selects));
2063    app.set_context(WHEN_EDIT_PATH, say(edit_path));
2064    app.set_context(WHEN_BROWSER, say(picker_modes || browsing));
2065    // The choices ended: each with its answer and the application's choices.
2066    let done: Vec<(Open, Answer, ChoiceValues)> = {
2067        let here = ui.ctx().viewport_id();
2068        let mut s = lock(&files.0);
2069        let mut done = Vec::new();
2070        let mut i = 0;
2071        while i < s.open.len() {
2072            // An in-app picker's modal is its window's: the choice ends in
2073            // that window's pass, which closes it.
2074            let shown = picker_window(app, s.open[i].owner);
2075            if s.open[i].picker.is_some() && !s.open[i].inline && shown != here {
2076                if lock(&s.open[i].answer).is_some() {
2077                    ui.ctx().request_repaint_of(shown);
2078                }
2079                i += 1;
2080                continue;
2081            }
2082            let answer = lock(&s.open[i].answer).take();
2083            match answer {
2084                Some(a) => {
2085                    let mut o = s.open.remove(i);
2086                    let choices = o
2087                        .choices
2088                        .take()
2089                        .or_else(|| o.picker.take().map(|p| p.choice_values))
2090                        .unwrap_or_else(|| o.request.choice_defaults());
2091                    done.push((o, a, choices));
2092                }
2093                None => i += 1,
2094            }
2095        }
2096        done
2097    };
2098    let ctx = ui.ctx().clone();
2099    if !done.is_empty() {
2100        // Nothing to preview for them any more.
2101        files.previews().cancel();
2102    }
2103    for (o, answer, choices) in done {
2104        let Open {
2105            id,
2106            request,
2107            resolver,
2108            by,
2109            on_bus,
2110            ..
2111        } = o;
2112        overlay::close(&ctx, overlay_id(id));
2113        let answer = answer.map(|paths| (paths, choices));
2114        finish(app, &files, id, &request, answer, resolver, &by);
2115        // Ended: its popup or native window closes.
2116        let reason = if by == Origin::User {
2117            Reason::User
2118        } else {
2119            Reason::Command
2120        };
2121        let req =
2122            |kind| WindowRequest::new(format!("{POPUP_PREFIX}{id}"), kind, PLUGIN.as_str(), reason);
2123        match on_bus {
2124            Some(WindowKind::Native) => {
2125                app.request_window_close(req(WindowKind::Native));
2126            }
2127            Some(kind) => {
2128                app.request_popup_close(req(kind));
2129            }
2130            None => {}
2131        }
2132    }
2133    picker_overlay(&ctx, app, &files);
2134}
2135
2136fn overlay_id(id: u64) -> egui::Id {
2137    egui::Id::unique(("egui_pop.files", id))
2138}
2139
2140/// Ends a choice: `file.chosen` for paths (and the application's choices),
2141/// the journal for a cancel.
2142fn finish(
2143    app: &AppHandle,
2144    files: &Files,
2145    id: u64,
2146    request: &FileRequest,
2147    answer: Option<(Vec<PathBuf>, ChoiceValues)>,
2148    resolver: Option<Resolver>,
2149    by: &Origin,
2150) {
2151    let source = crate::host::source_of(by);
2152    let result = match answer {
2153        None => {
2154            app.publish(&source, None, "file.cancelled", json!({ "id": id }));
2155            files.note(id, &request.title, json!("cancelled"), &source);
2156            if *by == Origin::User {
2157                Ok(Json::Null)
2158            } else {
2159                Ok(json!({ "cancelled": true, "origin": by }))
2160            }
2161        }
2162        Some((paths, choices)) => {
2163            let found = files.groups_of(app, request, &paths);
2164            let mut args = json!({
2165                "id": id,
2166                "request": request.to_json(),
2167                "paths": paths_json(&paths),
2168                "origin": source,
2169            });
2170            if !found.is_empty() {
2171                args["groups"] = groups::to_json(&found);
2172            }
2173            if !request.choices.is_empty() {
2174                args["choices"] = json!(choices);
2175            }
2176            let out = app.step(&STEP_CHOSEN, args, |app, args| {
2177                let chosen = paths_of(args);
2178                remember(app, &chosen);
2179                remember_folder(app, request, &chosen);
2180                let mut out = json!({ "paths": paths_json(&chosen), "origin": by });
2181                // A before-hook may have changed them, as the paths.
2182                if let Some(c) = args.get("choices") {
2183                    out["choices"] = c.clone();
2184                }
2185                // A hook may have redirected the choice: its groups, then.
2186                let last = if chosen == paths {
2187                    found.clone()
2188                } else {
2189                    files.groups_of(app, request, &chosen)
2190                };
2191                if !last.is_empty() {
2192                    out["groups"] = groups::to_json(&last);
2193                }
2194                Ok(out)
2195            });
2196            let r = match out {
2197                Outcome::Done(r) => r,
2198                Outcome::Vetoed { reason, .. } => Err(reason),
2199            };
2200            files.note(
2201                id,
2202                &request.title,
2203                match &r {
2204                    Ok(v) => v.clone(),
2205                    Err(e) => json!({ "refused": e }),
2206                },
2207                &source,
2208            );
2209            r
2210        }
2211    };
2212    if let Some(r) = resolver {
2213        r.resolve(result);
2214    }
2215}
2216
2217/// What the picker answered, applied: the choice's answer, the question
2218/// before replacing a file, a bookmark, a new folder in the journal.
2219fn settle(
2220    app: &AppHandle,
2221    id: u64,
2222    picker: &mut FilePicker,
2223    answer: &Mutex<Option<Answer>>,
2224    out: Option<PickerAnswer>,
2225    open: bool,
2226) {
2227    match out {
2228        Some(PickerAnswer::Chosen(paths)) => *lock(answer) = Some(Some(paths)),
2229        Some(PickerAnswer::Cancel) => *lock(answer) = Some(None),
2230        Some(PickerAnswer::Bookmark(dir, on)) => set_bookmark(app, &dir, on),
2231        Some(PickerAnswer::RenameBookmark(dir, name)) => rename_bookmark(app, &dir, &name),
2232        Some(PickerAnswer::MoveBookmark(dir, to)) => move_bookmark(app, &dir, to),
2233        Some(PickerAnswer::Replace(path)) => picker.ask_replace(app, id, &path),
2234        Some(PickerAnswer::FolderCreated(path)) => folder_created(app, &path),
2235        None if !open => *lock(answer) = Some(None),
2236        None => {}
2237    }
2238}
2239
2240/// A folder was made: the journal says so.
2241fn folder_created(app: &AppHandle, path: &Path) {
2242    app.publish(
2243        "user",
2244        None,
2245        "file.folder_created",
2246        json!({ "path": path.display().to_string() }),
2247    );
2248}
2249
2250fn places(app: &AppHandle, files: &Files) -> Places {
2251    Places {
2252        home: home(),
2253        system: files.system_places(),
2254        recent: recent(app),
2255        bookmarks: bookmarks(app),
2256        bookmark_names: bookmark_names(app),
2257        app_sections: files.place_providers().sections(),
2258    }
2259}
2260
2261/// Whether a click came from the pointer: its press left nothing focused, where
2262/// Enter or Space leave the focus on the widget.
2263fn by_pointer(r: &egui::Response) -> bool {
2264    r.clicked_by(egui::PointerButton::Primary)
2265}
2266
2267/// The width of the in-app picker's modal at first, the preview pane
2268/// shown or not: wide enough for the places, the list with all its columns
2269/// and the full pane.
2270pub const PICKER_WIDTH: f32 = 960.0;
2271/// The height of the in-app picker's modal at first: the list has its
2272/// usual height ([`LIST_HEIGHT`]).
2273pub const PICKER_HEIGHT: f32 = 398.0;
2274/// The least size the in-app picker's modal is dragged to: the row of
2275/// its filters and buttons fits, and a few entries.
2276pub const PICKER_MIN_SIZE: egui::Vec2 = egui::vec2(640.0, 280.0);
2277/// The list's height when the picker is not given a height to fill.
2278pub const LIST_HEIGHT: f32 = 280.0;
2279/// The width of the in-app picker's side bar of places, in points.
2280const PLACES_WIDTH: f32 = 150.0;
2281/// The narrowest the picker's list gets for the preview pane: under
2282/// it, the pane shrinks instead.
2283pub const LIST_MIN_WIDTH: f32 = 240.0;
2284/// The narrowest preview pane drawn: with less room, it is not shown.
2285pub const PANE_MIN_WIDTH: f32 = 120.0;
2286/// The narrowest the name's column gets: with less room, the other columns
2287/// go, the type first and the modification time last.
2288pub const NAME_MIN_WIDTH: f32 = 140.0;
2289
2290/// The smallest thumbnails of the picker's grid, in points: its zoom shows
2291/// no more per row than fit.
2292pub const THUMBNAIL_MIN_SIZE: f32 = browser::ThumbnailsMode::MIN_SIZE;
2293/// The side previews are made at by default ([`preview::MAX_SIDE`]); the
2294/// grid's thumbnails follow its zoom, one across at most.
2295pub const THUMBNAIL_MAX_SIZE: f32 = 256.0;
2296/// The size of the picker's thumbnails an older version started at, in
2297/// points.
2298pub const THUMBNAIL_DEFAULT_SIZE: f32 = 128.0;
2299/// `Ctrl` and the wheel step the zoom once they have scaled it this much.
2300const THUMBNAIL_STEP: f32 = 1.25;
2301/// The width of the slider of the thumbnails' size.
2302const THUMBNAIL_SLIDER_WIDTH: f32 = 170.0;
2303
2304/// With less room than this beside the controls, the breadcrumbs take a row of
2305/// their own: the deepest segment would hardly show.
2306const CRUMBS_MIN_WIDTH: f32 = 160.0;
2307/// How wide a breadcrumb's menu gets: a longer name is cut.
2308const CRUMB_MENU_WIDTH: f32 = 320.0;
2309/// How high a breadcrumb's menu gets: it scrolls past that.
2310const CRUMB_MENU_HEIGHT: f32 = 320.0;
2311
2312/// More than any window: what the store accepts for a length.
2313const MAX_LENGTH: f64 = 65_536.0;
2314
2315/// Splits the room beside the places between the list and the preview
2316/// pane (when it is on, with `gap` between them): the pane takes the
2317/// width `wanted` from the list's while the list keeps `LIST_MIN_WIDTH`,
2318/// then shrinks, down to `PANE_MIN_WIDTH`, under which it is hidden.
2319fn split_list(available: f32, gap: f32, preview: bool, wanted: f32) -> (f32, Option<f32>) {
2320    if !preview {
2321        return (available, None);
2322    }
2323    let pane = (available - gap - LIST_MIN_WIDTH).min(wanted.max(PANE_MIN_WIDTH));
2324    if pane < PANE_MIN_WIDTH {
2325        (available, None)
2326    } else {
2327        (available - gap - pane, Some(pane))
2328    }
2329}
2330
2331/// The window an in-app picker asked from `owner` is drawn in: that
2332/// application window, else the main window (a detached panel's choice,
2333/// like the main window's, is shown there).
2334fn picker_window(app: &AppHandle, owner: egui::ViewportId) -> egui::ViewportId {
2335    app.window_group(owner)
2336}
2337
2338/// The in-app picker of the first choice that has one (and is not drawn
2339/// by its caller), in a modal, over the window it was asked from: drawn
2340/// in that window's pass only.
2341fn picker_overlay(ctx: &egui::Context, app: &AppHandle, files: &Files) {
2342    let here = ctx.viewport_id();
2343    let Some((id, title, mut picker, answer)) = ({
2344        let s = lock(&files.0);
2345        s.open
2346            .iter()
2347            .filter(|o| !o.inline && picker_window(app, o.owner) == here)
2348            .find_map(|o| {
2349                o.picker
2350                    .clone()
2351                    .map(|p| (o.id, o.request.title.clone(), p, o.answer.clone()))
2352            })
2353    }) else {
2354        return;
2355    };
2356    let places = places(app, files);
2357    load_view(app, &mut picker);
2358    let modal = overlay_id(id);
2359    // One size, the preview on or off: the pane takes its width from
2360    // the list's, so toggling it does not resize the dialog. The size at
2361    // opening is what the person left, read once per dialog.
2362    let size = overlay::modal_size(ctx, modal).unwrap_or_else(|| opening_size(ctx, app));
2363    let mut spec = OverlaySpec::new(("egui_pop.files", id), &title, Kind::Modal)
2364        .resizable(size, PICKER_MIN_SIZE);
2365    debug_assert_eq!(spec.id, modal);
2366    if picker.naming.is_some() || picker.renaming.is_some() {
2367        // Escape closes the row asking a new folder's name, or a bookmark's,
2368        // not the picker.
2369        spec = spec.keep_on_escape();
2370    }
2371    picker.fill = true;
2372    let mut open = true;
2373    let mut out = None;
2374    overlay::show(ctx, &spec, &mut open, None, |ui| {
2375        ui.heading(&title);
2376        out = picker.show(ui, &places);
2377    });
2378    keep_view(app, &picker);
2379    // What the person left, not what the window holds it to; a drag is
2380    // kept once it is over.
2381    if open
2382        && !overlay::modal_resizing(ctx, modal)
2383        && let Some(size) = overlay::modal_size(ctx, modal)
2384        && size != dialog_size(app)
2385    {
2386        want_dialog_size(app, size);
2387    }
2388    settle(app, id, &mut picker, &answer, out, open);
2389    files.keep(id, picker);
2390}
2391
2392/// The size the in-app picker opens at: the one kept, or back to the
2393/// default when it no longer fits the window (or makes no sense).
2394fn opening_size(ctx: &egui::Context, app: &AppHandle) -> egui::Vec2 {
2395    let size = dialog_size(app);
2396    let max = overlay::modal_max_size(ctx);
2397    let fits = size.x >= PICKER_MIN_SIZE.x
2398        && size.y >= PICKER_MIN_SIZE.y
2399        && size.x <= max.x
2400        && size.y <= max.y;
2401    if fits {
2402        return size;
2403    }
2404    let set = Set::new(DIALOG_SIZE, Change::Reset, Origin::User)
2405        .by(&OwnerId::FRAMEWORK)
2406        .untracked();
2407    if let Err(e) = lock(&app.store()).set(set) {
2408        log::warn!(target: "egui_pop", "{DIALOG_SIZE}: {e:?}");
2409    }
2410    dialog_size(app)
2411}
2412
2413/// What the kept view says, for the picker to show: the preview pane on
2414/// or off and its width (not during a drag of its splitter), the keys of
2415/// its new folder, and whether its question is still open.
2416fn load_view(app: &AppHandle, picker: &mut FilePicker) {
2417    if let Some(dialog) = picker.asking
2418        && !app.service(&DIALOGS).is_some_and(|d| d.is_open(dialog))
2419    {
2420        picker.asking = None;
2421        picker.refocus = true;
2422    }
2423    picker.new_folder_keys = app.keys_for(&CMD_NEW_FOLDER);
2424    picker.hidden_keys = app.keys_for(&CMD_TOGGLE_HIDDEN);
2425    picker.preview_keys = app.keys_for(&CMD_TOGGLE_PREVIEW);
2426    picker.declared_keys = true;
2427    picker.show_preview = preview_wanted(app);
2428    if !picker.pane_dragging {
2429        picker.pane_width = pane_width(app);
2430    }
2431    let view = view_for(app, &picker.dialog)
2432        .and_then(|m| PickerView::parse(&m))
2433        .unwrap_or_else(|| view(app));
2434    // The columns, last used choosing a folder, are not a file dialog's.
2435    picker.view = if picker.views().contains(&view) || view == PickerView::Grid {
2436        view
2437    } else {
2438        PickerView::List
2439    };
2440    if !picker.thumbnail_dragging {
2441        picker.zoom = thumbnail_zoom_under(app, picker.resize);
2442    }
2443    picker.set_sort(sort_order(app));
2444    picker.set_folders_first(folders_first(app));
2445    picker.set_grouped(grouped(app));
2446}
2447
2448/// Keeps what the person changed of the view; a drag of the splitter
2449/// once it is over.
2450fn keep_view(app: &AppHandle, picker: &FilePicker) {
2451    if picker.show_preview != preview_wanted(app) {
2452        want_preview(app, picker.show_preview);
2453    }
2454    if !picker.pane_dragging && picker.pane_width != pane_width(app) {
2455        want_pane_width(app, picker.pane_width);
2456    }
2457    if view_for(app, &picker.dialog).and_then(|m| PickerView::parse(&m)) != Some(picker.view) {
2458        want_view_for(app, &picker.dialog, picker.view.as_str());
2459    }
2460    if !picker.thumbnail_dragging {
2461        match picker.zoom {
2462            browser::ThumbZoom::Points(p)
2463                if picker.resize == browser::GridResize::FixedSize
2464                    && thumbnail_points(app) != Some(p) =>
2465            {
2466                want_thumbnail_points(app, p);
2467            }
2468            zoom => {
2469                if let Some(n) = zoom.per_row()
2470                    && thumbnail_zoom(app) != browser::ThumbZoom::PerRow(n)
2471                {
2472                    want_thumbnails_per_row(app, n);
2473                }
2474            }
2475        }
2476    }
2477    if picker.sort != sort_order(app) {
2478        want_sort_order(app, picker.sort);
2479    }
2480    if picker.folders_first != folders_first(app) {
2481        want_folders_first(app, picker.folders_first);
2482    }
2483    if picker.grouped != grouped(app) {
2484        want_grouped(app, picker.grouped);
2485    }
2486}
2487
2488/// A path's preview metadata, as `file.preview` gives it: made now
2489/// from the providers if it is not in the cache. Metadata only: no
2490/// pixels and no text.
2491pub fn preview_metadata(files: &Files, path: &Path) -> Result<Json, String> {
2492    let fs = files.file_system();
2493    let meta = fs
2494        .metadata(path)
2495        .map_err(|e| format!("{}: {e}", path.display()))?;
2496    let mut d = files.previews().compute(&fs, path).describe();
2497    d["path"] = json!(path.display().to_string());
2498    d["is_dir"] = json!(meta.is_dir);
2499    if !meta.is_dir {
2500        d["size"] = json!(meta.len);
2501    }
2502    if let Some(t) = meta.modified {
2503        if let Ok(since) = t.duration_since(std::time::SystemTime::UNIX_EPOCH) {
2504            d["modified"] = json!(since.as_secs());
2505        }
2506        d["modified_text"] = json!(preview::time_text(t));
2507    }
2508    Ok(d)
2509}
2510
2511/// Whether the in-app picker shows its preview pane (the setting).
2512pub fn preview_wanted(app: &AppHandle) -> bool {
2513    lock(&app.store())
2514        .get(&format!("settings/{SETTING_PREVIEW}"))
2515        .and_then(|e| e.value.as_bool())
2516        .unwrap_or(true)
2517}
2518
2519/// Shows or hides the in-app picker's preview pane (the setting, kept).
2520pub fn want_preview(app: &AppHandle, on: bool) {
2521    let set = Set::new(
2522        &format!("settings/{SETTING_PREVIEW}"),
2523        Change::To(Value::Bool(on)),
2524        Origin::User,
2525    )
2526    .by(&OwnerId::FRAMEWORK);
2527    if let Err(e) = lock(&app.store()).set(set) {
2528        log::warn!(target: "egui_pop", "{SETTING_PREVIEW}: {e:?}");
2529    }
2530}
2531
2532/// Writes a remembered value of the picker, outside any undo history.
2533fn keep_value(app: &AppHandle, path: &str, value: Value) {
2534    let set = Set::new(path, Change::To(value), Origin::User)
2535        .by(&OwnerId::FRAMEWORK)
2536        .untracked();
2537    if let Err(e) = lock(&app.store()).set(set) {
2538        log::warn!(target: "egui_pop", "{path}: {e:?}");
2539    }
2540}
2541
2542/// The in-app picker's size, as kept (it may not fit the window now).
2543pub fn dialog_size(app: &AppHandle) -> egui::Vec2 {
2544    let store = app.store();
2545    let store = lock(&store);
2546    match store.get(DIALOG_SIZE).map(|e| &e.value) {
2547        Some(Value::Floats(f)) if f.len() == 2 => vec2(f[0] as f32, f[1] as f32),
2548        _ => vec2(PICKER_WIDTH, PICKER_HEIGHT),
2549    }
2550}
2551
2552/// Keeps the in-app picker's size.
2553pub fn want_dialog_size(app: &AppHandle, size: egui::Vec2) {
2554    let value = Value::Floats(vec![f64::from(size.x), f64::from(size.y)]);
2555    keep_value(app, DIALOG_SIZE, value);
2556}
2557
2558/// The width of the in-app picker's preview pane, as kept (the room in
2559/// the dialog may hold it smaller).
2560pub fn pane_width(app: &AppHandle) -> f32 {
2561    lock(&app.store())
2562        .get(PANE_WIDTH)
2563        .and_then(|e| e.value.as_f64())
2564        .map_or(preview::PANE_WIDTH, |w| w as f32)
2565}
2566
2567/// Keeps the width of the in-app picker's preview pane.
2568pub fn want_pane_width(app: &AppHandle, width: f32) {
2569    keep_value(app, PANE_WIDTH, Value::Float(f64::from(width)));
2570}
2571
2572/// The in-app picker's view last used, as kept.
2573pub fn view(app: &AppHandle) -> PickerView {
2574    lock(&app.store())
2575        .get(VIEW)
2576        .and_then(|e| e.value.as_text().and_then(PickerView::parse))
2577        .unwrap_or_default()
2578}
2579
2580/// Keeps the in-app picker's view last used.
2581pub fn want_view(app: &AppHandle, view: PickerView) {
2582    keep_value(app, VIEW, Value::Choice(view.as_str().into()));
2583}
2584
2585fn views(app: &AppHandle) -> Vec<(String, String)> {
2586    lock(&app.store())
2587        .get(VIEWS)
2588        .and_then(|e| e.value.as_text().map(str::to_string))
2589        .and_then(|t| serde_json::from_str(&t).ok())
2590        .unwrap_or_default()
2591}
2592
2593/// The mode a dialog was last shown in (a mode id: `details`,
2594/// `thumbnails`), kept in the host's store; `None` for a dialog never
2595/// shown.
2596pub fn view_for(app: &AppHandle, dialog: &str) -> Option<String> {
2597    views(app)
2598        .into_iter()
2599        .find_map(|(d, mode)| (d == dialog).then_some(mode))
2600}
2601
2602/// Keeps the mode a dialog is shown in, and as the view last used.
2603pub fn want_view_for(app: &AppHandle, dialog: &str, mode: &str) {
2604    let mut list = views(app);
2605    list.retain(|(d, _)| d != dialog);
2606    list.insert(0, (dialog.to_string(), mode.to_string()));
2607    list.truncate(VIEWS_KEPT);
2608    if let Ok(text) = serde_json::to_string(&list) {
2609        write_text(app, VIEWS, text);
2610    }
2611    if let Some(view) = PickerView::parse(mode) {
2612        want_view(app, view);
2613    }
2614}
2615
2616/// The dialog a request's view is kept under: its purpose, else its kind.
2617pub fn dialog_of(request: &FileRequest) -> String {
2618    request.purpose.clone().unwrap_or_else(|| {
2619        match request.kind {
2620            ChooseKind::Open => "open",
2621            ChooseKind::OpenMany => "open_many",
2622            ChooseKind::Save => "save",
2623            ChooseKind::Folder => "folder",
2624        }
2625        .to_string()
2626    })
2627}
2628
2629/// The zoom of the in-app picker's grid, as kept: the count per row once
2630/// set ([`THUMBNAILS_PER_ROW`]); before, the size in points an older
2631/// version kept ([`THUMBNAIL_SIZE`]), which the grid converts at its
2632/// width when next drawn; else [`browser::ThumbZoom::DEFAULT_PER_ROW`].
2633pub fn thumbnail_zoom(app: &AppHandle) -> browser::ThumbZoom {
2634    let store = app.store();
2635    let store = lock(&store);
2636    match store.get(THUMBNAILS_PER_ROW).and_then(|e| e.value.as_i64()) {
2637        Some(n) if n >= 1 => browser::ThumbZoom::PerRow(n as u32),
2638        _ => store
2639            .get(THUMBNAIL_SIZE)
2640            .map(|e| e.value.to_json())
2641            .or_else(|| store.pending().get(THUMBNAIL_SIZE).cloned())
2642            .and_then(|j| j.as_f64())
2643            .map_or_else(browser::ThumbZoom::default, |p| {
2644                browser::ThumbZoom::Points(p as f32)
2645            }),
2646    }
2647}
2648
2649/// The zoom of the in-app picker's grid, as kept for `resize`: under
2650/// [`browser::GridResize::FixedSize`], the size kept
2651/// ([`THUMBNAIL_POINTS`]) once set, else [`thumbnail_zoom`] (converted
2652/// into a size at the grid's width when next drawn).
2653pub fn thumbnail_zoom_under(app: &AppHandle, resize: browser::GridResize) -> browser::ThumbZoom {
2654    match resize {
2655        browser::GridResize::FixedSize => {
2656            thumbnail_points(app).map_or_else(|| thumbnail_zoom(app), browser::ThumbZoom::Points)
2657        }
2658        browser::GridResize::PerRow => thumbnail_zoom(app),
2659    }
2660}
2661
2662/// The size of the in-app picker's thumbnails kept under
2663/// [`browser::GridResize::FixedSize`] ([`THUMBNAIL_POINTS`]), once set.
2664fn thumbnail_points(app: &AppHandle) -> Option<f32> {
2665    lock(&app.store())
2666        .get(THUMBNAIL_POINTS)
2667        .and_then(|e| e.value.to_json().as_f64())
2668        .filter(|p| p.is_finite() && *p > 0.0)
2669        .map(|p| p as f32)
2670}
2671
2672/// Keeps the size of the in-app picker's thumbnails, in points (its grid
2673/// keeping the size on a resize).
2674pub fn want_thumbnail_points(app: &AppHandle, points: f32) {
2675    let p = f64::from(points).clamp(f64::from(browser::ThumbnailsMode::MIN_SIZE), MAX_LENGTH);
2676    keep_value(app, THUMBNAIL_POINTS, Value::Float(p));
2677}
2678
2679/// Keeps the zoom of the in-app picker's grid: this many per row.
2680pub fn want_thumbnails_per_row(app: &AppHandle, per_row: u32) {
2681    let n = per_row.clamp(1, browser::ThumbZoom::MOST);
2682    keep_value(app, THUMBNAILS_PER_ROW, Value::Int(i64::from(n)));
2683}
2684
2685/// The in-app picker's order, as kept.
2686pub fn sort_order(app: &AppHandle) -> PickerSort {
2687    lock(&app.store())
2688        .get(SORT)
2689        .and_then(|e| e.value.as_text().and_then(PickerSort::parse))
2690        .unwrap_or_default()
2691}
2692
2693/// Keeps the in-app picker's order.
2694pub fn want_sort_order(app: &AppHandle, sort: PickerSort) {
2695    keep_value(app, SORT, Value::Text(sort.as_text()));
2696}
2697
2698/// Whether the in-app picker keeps folders first (the setting).
2699pub fn folders_first(app: &AppHandle) -> bool {
2700    lock(&app.store())
2701        .get(&format!("settings/{SETTING_FOLDERS_FIRST}"))
2702        .and_then(|e| e.value.as_bool())
2703        .unwrap_or(true)
2704}
2705
2706/// Keeps folders first in the in-app picker, or not (the setting).
2707pub fn want_folders_first(app: &AppHandle, on: bool) {
2708    let path = format!("settings/{SETTING_FOLDERS_FIRST}");
2709    keep_value(app, &path, Value::Bool(on));
2710}
2711
2712/// Whether the in-app picker groups files, with groupings declared.
2713pub fn grouped(app: &AppHandle) -> bool {
2714    lock(&app.store())
2715        .get(GROUPED)
2716        .and_then(|e| e.value.as_bool())
2717        .unwrap_or(true)
2718}
2719
2720/// Keeps whether the in-app picker groups files.
2721pub fn want_grouped(app: &AppHandle, on: bool) {
2722    keep_value(app, GROUPED, Value::Bool(on));
2723}
2724
2725/// The home folder, if known.
2726pub fn home() -> Option<PathBuf> {
2727    std::env::var_os("HOME")
2728        .or_else(|| std::env::var_os("USERPROFILE"))
2729        .map(PathBuf::from)
2730        .filter(|d| d.is_dir())
2731}
2732
2733/// Places the picker lists beside the folder: home, the system's folders,
2734/// the volumes mounted, recent places and bookmarks. Made with
2735/// `Places::default()` and its fields.
2736#[derive(Clone, Debug, Default, PartialEq)]
2737#[non_exhaustive]
2738pub struct Places {
2739    pub home: Option<PathBuf>,
2740    /// The system's folders and volumes ([`places::system_places`]).
2741    pub system: SystemPlaces,
2742    pub recent: Vec<PathBuf>,
2743    pub bookmarks: Vec<PathBuf>,
2744    /// The names given to bookmarks ([`rename_bookmark`]).
2745    pub bookmark_names: Vec<(PathBuf, String)>,
2746    /// The application's sections ([`Files::place_providers`]): the picker
2747    /// lists their folders under its own places.
2748    pub app_sections: Vec<PlaceSection>,
2749}
2750
2751impl Places {
2752    /// Every place as sections, the way the picker lists them: home and
2753    /// the system's folders (`files.places`), the devices (`files.devices`),
2754    /// recent places (`files.recent`), bookmarks (`files.bookmarks`), then
2755    /// the application's; empty ones left out, but an application's with
2756    /// an empty line or kept ([`PlaceSection::shown`]). For a
2757    /// [`places::PlacesPanel`].
2758    pub fn sections(&self, ctx: &egui::Context) -> Vec<PlaceSection> {
2759        use places::PlaceItem;
2760        let mut own = Vec::new();
2761        if let Some(h) = &self.home {
2762            own.push(PlaceItem::folder(strings::tr(ctx, &txt::FILES_HOME), h));
2763        }
2764        for (folder, dir) in &self.system.folders {
2765            own.push(PlaceItem::folder(strings::tr(ctx, folder.title()), dir));
2766        }
2767        let mut out = vec![
2768            PlaceSection::new("files.places", strings::tr(ctx, &txt::FILES_PLACES)).items(own),
2769            PlaceSection::new("files.devices", strings::tr(ctx, &txt::FILES_DEVICES))
2770                .items((self.system.volumes.iter()).map(|v| PlaceItem::folder(&v.name, &v.path))),
2771            PlaceSection::new("files.recent", strings::tr(ctx, &txt::FILES_RECENT)).items(
2772                self.recent
2773                    .iter()
2774                    .map(|d| PlaceItem::folder(folder_name(d), d)),
2775            ),
2776            PlaceSection::new("files.bookmarks", strings::tr(ctx, &txt::FILES_BOOKMARKS)).items(
2777                (self.bookmarks.iter()).map(|d| PlaceItem::folder(self.bookmark_name(d), d)),
2778            ),
2779        ];
2780        out.extend(self.app_sections.iter().cloned());
2781        out.retain(PlaceSection::shown);
2782        out
2783    }
2784
2785    /// A bookmark's name: the one given, else its folder's.
2786    pub fn bookmark_name(&self, dir: &Path) -> String {
2787        self.bookmark_names
2788            .iter()
2789            .find_map(|(d, n)| (d == dir).then(|| n.clone()))
2790            .unwrap_or_else(|| folder_name(dir))
2791    }
2792}
2793
2794fn folder_name(dir: &Path) -> String {
2795    dir.file_name()
2796        .map(|n| n.to_string_lossy().into_owned())
2797        .unwrap_or_else(|| dir.display().to_string())
2798}
2799
2800/// How the in-app picker shows a folder's entries: the file browser's
2801/// modes it draws ([`browser::MODE_DETAILS`], [`browser::MODE_THUMBNAILS`],
2802/// [`browser::MODE_COLUMNS`]).
2803#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2804#[non_exhaustive]
2805pub enum PickerView {
2806    /// The details mode: one entry per row, with its facts in columns.
2807    #[default]
2808    List,
2809    /// The thumbnails mode: thumbnails from the preview providers (only
2810    /// with previews, [`FilePicker::with_previews`]: details without them).
2811    Grid,
2812    /// The columns mode, Finder's: the path's folders side by side, the
2813    /// highlighted folder's subfolders after them. Only when choosing a
2814    /// folder: details elsewhere.
2815    Columns,
2816}
2817
2818impl PickerView {
2819    /// Every view, in the switcher's order; a picker offers those that fit
2820    /// it ([`FilePicker::views`]).
2821    pub const ALL: [PickerView; 3] = [PickerView::List, PickerView::Grid, PickerView::Columns];
2822
2823    /// Its mode's id, its name in the store.
2824    pub fn as_str(self) -> &'static str {
2825        match self {
2826            PickerView::List => browser::MODE_DETAILS,
2827            PickerView::Grid => browser::MODE_THUMBNAILS,
2828            PickerView::Columns => browser::MODE_COLUMNS,
2829        }
2830    }
2831
2832    /// The view of a mode's id; the names kept before the modes (`list`,
2833    /// `grid`) too.
2834    pub fn parse(name: &str) -> Option<PickerView> {
2835        match name {
2836            browser::MODE_DETAILS | "list" => Some(PickerView::List),
2837            browser::MODE_THUMBNAILS | "grid" => Some(PickerView::Grid),
2838            browser::MODE_COLUMNS => Some(PickerView::Columns),
2839            _ => None,
2840        }
2841    }
2842}
2843
2844impl SortColumn {
2845    /// Its title, as a column's header and a sort menu say it.
2846    fn title(self) -> &'static strings::StrKey {
2847        match self {
2848            SortColumn::Name => &txt::FILES_COLUMN_NAME,
2849            SortColumn::Size => &txt::FILES_COLUMN_SIZE,
2850            SortColumn::Modified => &txt::FILES_COLUMN_MODIFIED,
2851            SortColumn::Type => &txt::FILES_COLUMN_TYPE,
2852            SortColumn::Taken => &txt::FILES_COLUMN_TAKEN,
2853        }
2854    }
2855}
2856
2857/// One entry of a folder.
2858#[derive(Clone, Debug, PartialEq, Eq)]
2859pub struct Entry {
2860    pub path: PathBuf,
2861    pub name: String,
2862    pub is_dir: bool,
2863}
2864
2865/// What the picker answers.
2866#[derive(Clone, Debug, PartialEq, Eq)]
2867#[non_exhaustive]
2868pub enum PickerAnswer {
2869    Chosen(Vec<PathBuf>),
2870    Cancel,
2871    /// Bookmark this folder (`true`) or remove its bookmark.
2872    Bookmark(PathBuf, bool),
2873    /// This file was chosen and exists: ask before replacing it (only with
2874    /// [`FileRequest::confirm_overwrite`]). [`Files`] asks through the
2875    /// dialogs plugin; a caller drawing a [`FilePicker`] on its own asks
2876    /// its way, and takes the path as chosen on a yes.
2877    Replace(PathBuf),
2878    /// This folder was made, and the picker shows it.
2879    FolderCreated(PathBuf),
2880    /// Give this bookmark this name (empty: its folder's).
2881    RenameBookmark(PathBuf, String),
2882    /// Move this bookmark to this place in the list.
2883    MoveBookmark(PathBuf, usize),
2884}
2885
2886/// The keys a tip says: `Ctrl+H`, or `Ctrl+H, F8` when bound twice.
2887fn keys_tip(keys: &[String]) -> String {
2888    keys.join(", ")
2889}
2890
2891/// Where the file's own name starts in a name or a typed path.
2892fn file_part(text: &str) -> usize {
2893    text.rfind(['/', std::path::MAIN_SEPARATOR])
2894        .map_or(0, |i| i + 1)
2895}
2896
2897/// Where the dot of a name's extension is (bytes), if it has one. A
2898/// leading dot makes a hidden file rather than an extension, a trailing
2899/// one has nothing after it, and what follows a dot in `Mr. Smith` holds
2900/// a space: none of them is an extension.
2901fn extension_dot(text: &str) -> Option<usize> {
2902    let start = file_part(text);
2903    let dot = text[start..].rfind('.').filter(|d| *d > 0)? + start;
2904    let extension = &text[dot + 1..];
2905    (!extension.is_empty() && !extension.contains(char::is_whitespace)).then_some(dot)
2906}
2907
2908/// A name with `extension` added when it has none; a hidden file's name
2909/// (`.config`) stays as it is.
2910fn with_extension(text: &str, extension: &str) -> String {
2911    let file = &text[file_part(text)..];
2912    if extension_dot(text).is_some() || file.is_empty() || file.starts_with('.') {
2913        return text.to_string();
2914    }
2915    format!("{}.{extension}", text.trim_end_matches('.'))
2916}
2917
2918/// A name's stem, in characters: what typing replaces.
2919fn stem_chars(text: &str) -> (usize, usize) {
2920    let start = file_part(text);
2921    let end = extension_dot(text).unwrap_or(text.len());
2922    (text[..start].chars().count(), text[..end].chars().count())
2923}
2924
2925/// A folder on the breadcrumbs, or in one of their menus.
2926#[derive(Clone, Debug, PartialEq, Eq)]
2927struct Crumb {
2928    name: String,
2929    path: PathBuf,
2930}
2931
2932/// A path without `.`, and without `..` where the folder it leaves is named: a
2933/// typed `../` would otherwise stay in the path and read as a folder.
2934fn without_dots(path: &Path) -> PathBuf {
2935    use std::path::Component;
2936    let mut out = PathBuf::new();
2937    for part in path.components() {
2938        match part {
2939            Component::CurDir => {}
2940            Component::ParentDir => match out.components().next_back() {
2941                Some(Component::Normal(_)) => {
2942                    out.pop();
2943                }
2944                Some(Component::RootDir | Component::Prefix(_)) => {}
2945                _ => out.push(part),
2946            },
2947            _ => out.push(part),
2948        }
2949    }
2950    out
2951}
2952
2953/// The folders a folder lies in and itself, the root first.
2954fn crumbs_of(dir: &Path) -> Vec<Crumb> {
2955    let dir = without_dots(dir);
2956    let mut out: Vec<Crumb> = dir
2957        .ancestors()
2958        .filter(|p| !p.as_os_str().is_empty())
2959        .map(|p| Crumb {
2960            name: p
2961                .file_name()
2962                .map_or_else(|| root_name(p), |n| n.to_string_lossy().into_owned()),
2963            path: p.to_path_buf(),
2964        })
2965        .collect();
2966    out.reverse();
2967    out
2968}
2969
2970/// A root as a person reads it: Windows' verbatim prefixes (`\\?\C:\`, which
2971/// `canonicalize` gives) are written as the drive or share they stand for; a
2972/// root without a drive (a [`fs::MemoryFs`]'s, as `/demo`) is `/` on every
2973/// system.
2974fn root_name(root: &Path) -> String {
2975    use std::path::{Component, Prefix};
2976    let sep = std::path::MAIN_SEPARATOR;
2977    match root.components().next() {
2978        Some(Component::RootDir) => "/".into(),
2979        Some(Component::Prefix(prefix)) => match prefix.kind() {
2980            Prefix::VerbatimDisk(drive) => format!("{}:{sep}", char::from(drive)),
2981            Prefix::VerbatimUNC(server, share) => format!(
2982                "{sep}{sep}{}{sep}{}",
2983                server.to_string_lossy(),
2984                share.to_string_lossy()
2985            ),
2986            _ => root.display().to_string(),
2987        },
2988        _ => root.display().to_string(),
2989    }
2990}
2991
2992/// A path as a person reads it. One without a drive (a [`fs::MemoryFs`]'s, as
2993/// `/demo/Photos`) is written with `/` on every system, as it was given:
2994/// Windows would join its parts with `\`. Any other is the system's.
2995fn path_text(path: &Path) -> String {
2996    use std::path::Component;
2997    if matches!(path.components().next(), Some(Component::Prefix(_))) {
2998        return path.display().to_string();
2999    }
3000    let mut out = String::new();
3001    for c in path.components() {
3002        match c {
3003            Component::RootDir => out.push('/'),
3004            c => {
3005                if !out.is_empty() && !out.ends_with('/') {
3006                    out.push('/');
3007                }
3008                out.push_str(&c.as_os_str().to_string_lossy());
3009            }
3010        }
3011    }
3012    out
3013}
3014
3015/// The first crumb shown, given each one's width: all of them when they fit,
3016/// else as many of the deepest as fit beside the button standing for the others
3017/// (`collapsed` wide). The deepest stays whatever the room.
3018fn first_crumb(widths: &[f32], room: f32, collapsed: f32) -> usize {
3019    if widths.iter().sum::<f32>() <= room {
3020        return 0;
3021    }
3022    let room = room - collapsed;
3023    let mut used = 0.0;
3024    let mut first = widths.len();
3025    for (n, width) in widths.iter().enumerate().rev() {
3026        used += width;
3027        if used > room && first < widths.len() {
3028            break;
3029        }
3030        first = n;
3031    }
3032    first
3033}
3034
3035/// The file browser the picker lists through and keeps its highlight and
3036/// selection in, never drawn: made at the first listing, once the picker's
3037/// groupings are known. Shared: the picker is copied every frame it is drawn.
3038type Lister = Arc<Mutex<Listing>>;
3039
3040/// The picker's browser, and its focus and selection as the picker's public
3041/// fields last read them: a field changed since, by the application, goes
3042/// to the browser before the picker's next step.
3043#[derive(Debug, Default)]
3044struct Listing {
3045    browser: Option<browser::FileBrowser>,
3046    highlight: usize,
3047    selected: BTreeSet<PathBuf>,
3048}
3049
3050impl Listing {
3051    /// What the application wrote to the picker's fields since they were
3052    /// read goes to the browser: the highlight as the focus, the selection
3053    /// as the policy lets it.
3054    fn push(&mut self, highlight: usize, selected: &BTreeSet<PathBuf>) {
3055        let Some(b) = self.browser.as_mut() else {
3056            return;
3057        };
3058        if highlight != self.highlight {
3059            let path = b.entries().get(highlight).map(|e| e.path.clone());
3060            b.set_focus(path.as_deref());
3061        }
3062        if *selected != self.selected {
3063            b.set_selection(selected.iter().cloned());
3064        }
3065    }
3066
3067    /// The browser's focus and selection, as the picker's fields say them.
3068    fn pull(&mut self) -> (usize, BTreeSet<PathBuf>) {
3069        if let Some(b) = &self.browser {
3070            self.highlight = b.focus_index().unwrap_or(0);
3071            self.selected = b.selection().paths.clone();
3072        }
3073        (self.highlight, self.selected.clone())
3074    }
3075}
3076
3077/// The picker's thumbnails, the browser's over the previews.
3078#[derive(Clone)]
3079struct PickerThumbnails(Arc<browser::PreviewThumbnails>);
3080
3081impl std::fmt::Debug for PickerThumbnails {
3082    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3083        f.write_str("PickerThumbnails")
3084    }
3085}
3086
3087/// The subfolders the picker's columns list, by folder and whether hidden
3088/// ones are shown.
3089type ColumnCache = Arc<Mutex<browser::ColumnListings>>;
3090
3091/// The in-app picker: a folder's entries, a field that filters them
3092/// (fuzzy) or takes a typed path (with completion), places, filters.
3093/// Usable on its own: [`FilePicker::show`] in any `Ui`.
3094#[derive(Clone, Debug)]
3095pub struct FilePicker {
3096    pub kind: ChooseKind,
3097    /// The folder shown.
3098    pub dir: PathBuf,
3099    pub filters: Vec<FileFilter>,
3100    /// The filter in use (`filters.len()`: all files).
3101    pub filter_index: usize,
3102    /// The field: a filter, or a path when it holds a separator or starts
3103    /// with `~`.
3104    pub text: String,
3105    /// The entry highlighted among those shown: where the arrows are, what
3106    /// the preview is of, and what Enter acts on. The picker's browser
3107    /// focus, read after each step; set it and the browser focuses that
3108    /// entry at the next.
3109    pub highlight: usize,
3110    /// What is selected, in the folder shown: files (choosing several), or
3111    /// one folder (choosing a folder, or saving: Enter goes into it). The
3112    /// picker's browser selection, kept to its [`SelectionPolicy`](browser::SelectionPolicy)
3113    /// and read after each step; set it and the browser selects what the
3114    /// policy lets at the next.
3115    pub selected: BTreeSet<PathBuf>,
3116    pub show_hidden: bool,
3117    /// The preview pane is shown (with previews, [`FilePicker::with_previews`]).
3118    pub show_preview: bool,
3119    /// The preview pane's width, as wanted: the room in the dialog may
3120    /// hold it smaller.
3121    pub pane_width: f32,
3122    /// How the entries are shown.
3123    pub view: PickerView,
3124    /// The dialog its view is kept under ([`dialog_of`]).
3125    pub dialog: String,
3126    /// The thumbnails' side in the grid, in points, as last drawn from the
3127    /// zoom ([`FilePicker::zoom`]). Set to another size, it becomes the
3128    /// zoom at the next draw (the count per row it gives there).
3129    pub thumbnail_size: f32,
3130    /// The order of the entries, in the list and in the grid.
3131    pub sort: PickerSort,
3132    /// Folders come before files in every order.
3133    pub folders_first: bool,
3134    /// Files that go together are one entry, with groupings declared
3135    /// ([`FilePicker::with_grouping`]) and when opening files.
3136    pub grouped: bool,
3137    /// The list takes the height left in the `Ui` it is drawn in (a
3138    /// dialog of a given size), rather than [`LIST_HEIGHT`].
3139    pub fill: bool,
3140    /// Why the last Enter did nothing.
3141    pub error: Option<String>,
3142    /// The new folder's name being typed.
3143    naming: Option<String>,
3144    /// That field takes the focus.
3145    naming_focus: bool,
3146    /// The keys of the new folder command, as the button's tip says them.
3147    new_folder_keys: Vec<String>,
3148    /// The keys of the hidden files and preview commands, as their check
3149    /// boxes' tips say them.
3150    hidden_keys: Vec<String>,
3151    preview_keys: Vec<String>,
3152    /// The folders shown before, and those gone back from.
3153    back: Vec<PathBuf>,
3154    forward: Vec<PathBuf>,
3155    /// The selection's keys are commands ([`Files`] draws this picker);
3156    /// drawn on its own, it has no keymap and reads them itself.
3157    declared_keys: bool,
3158    /// What the selection line said last: a change is announced.
3159    said: Option<String>,
3160    /// The folder last announced: another one is.
3161    said_dir: Option<PathBuf>,
3162    /// The list's rows as last drawn: holding the focus, they leave the
3163    /// picker's keys to the picker.
3164    row_ids: Vec<egui::Id>,
3165    /// The name proposed when saving: back when a typed name was a folder.
3166    proposed: String,
3167    /// Asks before replacing a file.
3168    confirm_overwrite: bool,
3169    /// The bookmark being renamed, and the name typed.
3170    renaming: Option<(PathBuf, String)>,
3171    /// That field takes the focus.
3172    renaming_focus: bool,
3173    /// The dialog asking whether to replace a file: the picker waits.
3174    asking: Option<u64>,
3175    /// The question closed: the field takes the focus back, which it lost
3176    /// while disabled.
3177    refocus: bool,
3178    /// The name's stem is selected in the field at the next frame.
3179    select_stem: bool,
3180    /// The field's cursor goes to its end at the next frame.
3181    cursor_to_end: bool,
3182    /// What the open breadcrumb menu lists, read as it opened (none: the folder
3183    /// could not be read). Shared: the picker is copied every frame it is drawn.
3184    crumb_menu: Option<Arc<Option<Vec<Crumb>>>>,
3185    /// The keyboard opened that menu: its first item takes the focus, and the
3186    /// focus goes back to its button as it closes.
3187    crumb_menu_keys: bool,
3188    /// That first item is still to take the focus.
3189    crumb_menu_focus: bool,
3190    /// Where text is translated, once drawn.
3191    ctx: Option<egui::Context>,
3192    focused: bool,
3193    /// The splitter is being dragged.
3194    pane_dragging: bool,
3195    /// The height of what comes below the list, as last drawn.
3196    /// The cells in a row of the grid, as last drawn.
3197    columns: usize,
3198    /// The modes drawing the list and the grid.
3199    details: browser::DetailsMode,
3200    thumbs: browser::ThumbnailsMode,
3201    cols: browser::ColumnsMode,
3202    /// The listings of the columns beside the folder shown (its ancestors'
3203    /// subfolders, the highlighted folder's), each off the interface thread
3204    /// on the system's file system. Shared: the picker is copied every
3205    /// frame.
3206    column_cache: ColumnCache,
3207    /// The grid brings the highlighted cell into view at the next frame.
3208    reveal_cell: bool,
3209    /// The highlighted cell takes the focus when it is next drawn: the
3210    /// keyboard is moving from cell to cell.
3211    focus_cell: bool,
3212    /// The slider of the thumbnails' size is being dragged.
3213    thumbnail_dragging: bool,
3214    /// How many thumbnails fill a row of the grid, or their size
3215    /// (its [`browser::GridResize`]).
3216    zoom: browser::ThumbZoom,
3217    /// What the zoom means on a resize.
3218    resize: browser::GridResize,
3219    /// The side last drawn: [`FilePicker::thumbnail_size`] changed from
3220    /// it is a size asked in points.
3221    drawn_side: f32,
3222    /// `Ctrl` and the wheel's zoom since the last step.
3223    wheel_zoom: f32,
3224    /// The grid's room at the last draw (width, gap).
3225    grid_room: (f32, f32),
3226    /// The grid asked for thumbnails at the last frame.
3227    asked_thumbnails: bool,
3228    /// The grid's thumbnails, from the previews (shared: the picker is
3229    /// copied every frame it is drawn, and the thumbnails asked are renewed
3230    /// from frame to frame).
3231    thumbnails: Option<PickerThumbnails>,
3232    /// Lists the folder, filters, orders, groups and ranks its entries.
3233    lister: Lister,
3234    /// The folder's groups as last listed, by main file.
3235    groups: Arc<HashMap<PathBuf, FileGroup>>,
3236    /// The listing or its groups were still under way at the last look.
3237    loading: bool,
3238    /// Why the folder could not be listed, at the last look.
3239    list_error: Option<String>,
3240    /// How many entries of the folder the type filter or the field hid, at
3241    /// the last look.
3242    filtered_out: usize,
3243    /// The entry to highlight and select once the listing has it (a column
3244    /// reached, the folder come from).
3245    reach_focus: Option<PathBuf>,
3246    fs: SharedFs,
3247    previews: Option<Previews>,
3248    groupings: Option<Groupings>,
3249    /// The request leaves groups on ([`FileRequest::ungrouped`]).
3250    request_groups: bool,
3251    /// The application's options ([`FileRequest::choice`]), and their values.
3252    choices: Vec<FileChoice>,
3253    choice_values: ChoiceValues,
3254}
3255
3256/// What the in-app picker's primary button does now ([`FilePicker::primary`]).
3257#[derive(Clone, Debug, PartialEq, Eq)]
3258pub struct Primary {
3259    /// Its label, a task: "Open", "Open 3 files", "Choose “Photos”", "Save".
3260    pub label: String,
3261    /// What it takes, shown beside it: a file's name, a count, a folder's
3262    /// path, the name saved and its folder.
3263    pub readout: Option<String>,
3264    /// Why it is off (its tooltip); none: it is on.
3265    pub off: Option<String>,
3266}
3267
3268/// Why the in-app picker's list shows nothing ([`FilePicker::empty_state`]).
3269#[derive(Clone, Debug, PartialEq, Eq)]
3270#[non_exhaustive]
3271pub enum EmptyState {
3272    /// The folder holds nothing (hidden files aside).
3273    Empty,
3274    /// Choosing a folder: the folder holds files, no folder.
3275    NoFolders,
3276    /// The field's filter matches nothing: its text.
3277    NoResults(String),
3278    /// The type filter hides every file: its name.
3279    NoneOfType(String),
3280    /// The folder cannot be listed: why.
3281    Unreadable(String),
3282}
3283
3284impl FilePicker {
3285    /// A picker for a request, in its folder (else home, else the root),
3286    /// on the system's file system.
3287    pub fn new(request: &FileRequest) -> Self {
3288        Self::new_in(request, fs::native())
3289    }
3290
3291    /// A picker for a request reading from `fs`, in the request's folder
3292    /// (else home, else the root).
3293    pub fn new_in(request: &FileRequest, fs: SharedFs) -> Self {
3294        let dir = request
3295            .directory
3296            .clone()
3297            .filter(|d| fs.is_dir(d))
3298            .or_else(|| home().filter(|h| fs.is_dir(h)))
3299            .unwrap_or_else(|| PathBuf::from("/"));
3300        let proposed = if request.kind == ChooseKind::Save {
3301            request.file_name.clone().unwrap_or_default()
3302        } else {
3303            String::new()
3304        };
3305        Self {
3306            kind: request.kind,
3307            dir,
3308            filters: request.filters.clone(),
3309            filter_index: 0,
3310            text: proposed.clone(),
3311            highlight: 0,
3312            selected: BTreeSet::new(),
3313            show_hidden: false,
3314            show_preview: false,
3315            pane_width: preview::PANE_WIDTH,
3316            view: PickerView::List,
3317            dialog: dialog_of(request),
3318            thumbnail_size: THUMBNAIL_DEFAULT_SIZE,
3319            sort: PickerSort::default(),
3320            folders_first: true,
3321            grouped: true,
3322            fill: false,
3323            error: None,
3324            naming: None,
3325            naming_focus: false,
3326            new_folder_keys: Vec::new(),
3327            hidden_keys: vec!["Ctrl+H".into()],
3328            preview_keys: vec!["Alt+P".into()],
3329            back: Vec::new(),
3330            forward: Vec::new(),
3331            declared_keys: false,
3332            said: None,
3333            said_dir: None,
3334            row_ids: Vec::new(),
3335            proposed,
3336            confirm_overwrite: request.confirm_overwrite,
3337            renaming: None,
3338            renaming_focus: false,
3339            asking: None,
3340            refocus: false,
3341            select_stem: request.kind == ChooseKind::Save,
3342            cursor_to_end: false,
3343            crumb_menu: None,
3344            crumb_menu_keys: false,
3345            crumb_menu_focus: false,
3346            ctx: None,
3347            focused: false,
3348            pane_dragging: false,
3349            columns: 1,
3350            details: browser::DetailsMode::default(),
3351            thumbs: browser::ThumbnailsMode::default(),
3352            cols: browser::ColumnsMode::default(),
3353            column_cache: Arc::new(Mutex::new(
3354                browser::ColumnListings::default().folders_only(true),
3355            )),
3356            reveal_cell: false,
3357            focus_cell: false,
3358            thumbnail_dragging: false,
3359            zoom: browser::ThumbZoom::default(),
3360            resize: browser::GridResize::default(),
3361            drawn_side: THUMBNAIL_DEFAULT_SIZE,
3362            wheel_zoom: 1.0,
3363            grid_room: (800.0, 4.0),
3364            asked_thumbnails: false,
3365            thumbnails: None,
3366            lister: Arc::default(),
3367            groups: Arc::default(),
3368            loading: false,
3369            list_error: None,
3370            filtered_out: 0,
3371            reach_focus: None,
3372            fs,
3373            previews: None,
3374            groupings: None,
3375            request_groups: request.group_files,
3376            choices: request.choices.clone(),
3377            choice_values: request.choice_defaults(),
3378        }
3379    }
3380
3381    /// The application's choices ([`FileRequest::choice`]) as they stand: each
3382    /// id with its value.
3383    pub fn choices(&self) -> &ChoiceValues {
3384        &self.choice_values
3385    }
3386
3387    /// Sets one of the application's choices; refused for an id the request
3388    /// does not have or a value it cannot take.
3389    pub fn set_choice(&mut self, id: &str, value: &str) -> Result<(), String> {
3390        let c = self
3391            .choices
3392            .iter()
3393            .find(|c| c.id == id)
3394            .ok_or_else(|| format!("no choice `{id}` in this request"))?;
3395        if !c.accepts(value) {
3396            return Err(format!("`{value}` is not a value of the choice `{id}`"));
3397        }
3398        self.choice_values.insert(id.into(), value.into());
3399        Ok(())
3400    }
3401
3402    /// Shows the selected entry's preview in a pane beside the list,
3403    /// from these providers (`Alt+P` hides it).
3404    pub fn with_previews(mut self, previews: Previews) -> Self {
3405        self.thumbnails = Some(PickerThumbnails(Arc::new(browser::PreviewThumbnails::new(
3406            previews.clone(),
3407            self.fs.clone(),
3408        ))));
3409        self.previews = Some(previews);
3410        self.show_preview = true;
3411        self
3412    }
3413
3414    /// What its grid's zoom means when the grid is resized
3415    /// ([`browser::GridResize::PerRow`] by default).
3416    #[must_use]
3417    pub fn with_resize(mut self, resize: browser::GridResize) -> Self {
3418        self.resize = resize;
3419        self
3420    }
3421
3422    /// What its grid's zoom means when the grid is resized.
3423    pub fn resize(&self) -> browser::GridResize {
3424        self.resize
3425    }
3426
3427    /// Files that go together are one entry, by these groupings ([`groups`]).
3428    /// Drawn on its own, the picker answers with the main files: its caller
3429    /// reads the others with [`group_of`](Self::group_of).
3430    pub fn with_grouping(mut self, groupings: Groupings) -> Self {
3431        self.groupings = Some(groupings);
3432        self
3433    }
3434
3435    /// Whether this choice can group files: opening files, the request not
3436    /// against it, with a grouping declared.
3437    fn can_group(&self) -> bool {
3438        matches!(self.kind, ChooseKind::Open | ChooseKind::OpenMany)
3439            && self.request_groups
3440            && self.groupings.as_ref().is_some_and(|g| !g.is_empty())
3441    }
3442
3443    /// Whether it groups now.
3444    fn grouping_on(&self) -> bool {
3445        self.grouped && self.can_group()
3446    }
3447
3448    /// The group a file heads, in the folder as last listed.
3449    pub fn group_of(&self, path: &Path) -> Option<&FileGroup> {
3450        self.groups.get(path)
3451    }
3452
3453    /// The entry the preview is of: the highlighted one.
3454    pub fn highlighted(&mut self) -> Option<Entry> {
3455        let at = self.highlight;
3456        self.visible().into_iter().nth(at)
3457    }
3458
3459    /// Where it reads.
3460    pub fn file_system(&self) -> &SharedFs {
3461        &self.fs
3462    }
3463
3464    /// Shows another folder; the selection stays behind.
3465    pub fn go(&mut self, dir: PathBuf) {
3466        let dir = without_dots(&dir);
3467        if dir != self.dir {
3468            self.back
3469                .push(std::mem::replace(&mut self.dir, dir.clone()));
3470            if self.back.len() > HISTORY_KEPT {
3471                self.back.remove(0);
3472            }
3473            self.forward.clear();
3474        }
3475        self.show_dir(dir);
3476    }
3477
3478    /// Shows `dir`, the history left as it is.
3479    fn show_dir(&mut self, dir: PathBuf) {
3480        self.dir = dir;
3481        self.on_browser(|b| {
3482            b.set_focus(None);
3483            b.set_selection([]);
3484        });
3485        self.reveal_cell = true;
3486        self.error = None;
3487        self.reach_focus = None;
3488        if self.kind != ChooseKind::Save {
3489            self.text.clear();
3490        }
3491    }
3492
3493    /// Goes back to the folder shown before; says whether there was one.
3494    pub fn go_back(&mut self) -> bool {
3495        let Some(dir) = self.back.pop() else {
3496            return false;
3497        };
3498        self.forward
3499            .push(std::mem::replace(&mut self.dir, dir.clone()));
3500        self.show_dir(dir);
3501        true
3502    }
3503
3504    /// Goes forward to the folder gone back from; says whether there was one.
3505    pub fn go_forward(&mut self) -> bool {
3506        let Some(dir) = self.forward.pop() else {
3507            return false;
3508        };
3509        self.back
3510            .push(std::mem::replace(&mut self.dir, dir.clone()));
3511        self.show_dir(dir);
3512        true
3513    }
3514
3515    /// Reads the folder again, and the facts of its files.
3516    pub fn reload(&mut self) {
3517        if let Some(b) = lock(&self.lister).browser.as_mut() {
3518            b.reload();
3519        }
3520        lock(&self.column_cache).clear();
3521    }
3522
3523    /// What a key of the picker's commands does to it.
3524    fn run_key(&mut self, id: &CommandId) {
3525        if *id == CMD_TOGGLE_HIDDEN {
3526            self.show_hidden = !self.show_hidden;
3527        } else if *id == CMD_RELOAD {
3528            self.reload();
3529        } else if *id == CMD_BACK {
3530            self.go_back();
3531        } else if *id == CMD_FORWARD {
3532            self.go_forward();
3533        }
3534    }
3535
3536    /// Shows the parent folder.
3537    pub fn up(&mut self) {
3538        if let Some(p) = self.dir.parent() {
3539            self.go(p.to_path_buf());
3540        }
3541    }
3542
3543    fn filter(&self) -> Option<&FileFilter> {
3544        self.filters.get(self.filter_index)
3545    }
3546
3547    fn accepts(&self, path: &Path) -> bool {
3548        self.filter().is_none_or(|f| f.accepts(path))
3549    }
3550
3551    /// What the browser shows of the folder: the filter's files and every
3552    /// folder; none but folders when choosing a folder.
3553    fn entry_filter(&self) -> browser::EntryFilter {
3554        let f = self
3555            .filter()
3556            .map(browser::EntryFilter::from)
3557            .unwrap_or_default();
3558        if self.kind == ChooseKind::Folder {
3559            f.with_kind(browser::EntryKind::Folder)
3560        } else {
3561            f
3562        }
3563    }
3564
3565    /// The folder's entries in the picker's order, those the filter accepts
3566    /// (folders whatever the filter; none but folders when choosing a folder),
3567    /// hidden ones only when asked, those the field's text matches best first.
3568    /// The folder is listed through a [`browser::FileBrowser`], off the
3569    /// interface thread on the system's file system: its entries come in over
3570    /// the next frames.
3571    pub fn entries(&mut self) -> Vec<Entry> {
3572        let filter = self.entry_filter();
3573        let query = if self.ranks() {
3574            self.text.trim().to_owned()
3575        } else {
3576            String::new()
3577        };
3578        let grouped = self.grouping_on();
3579        let policy = self.policy();
3580        let lister = Arc::clone(&self.lister);
3581        let mut lister = lock(&lister);
3582        lister.push(self.highlight, &self.selected);
3583        let b = lister.browser.get_or_insert_with(|| {
3584            let source = Arc::new(browser::FsSource::new(self.fs.clone()));
3585            let b = browser::FileBrowser::new("egui_pop.files.picker", source, self.dir.clone())
3586                .with_modes(browser::ViewModes::empty());
3587            match self.groupings.clone() {
3588                Some(g) => b.with_grouping(g),
3589                None => b,
3590            }
3591        });
3592        if b.place() != self.dir {
3593            b.open(self.dir.clone());
3594        }
3595        if b.selection_policy() != policy {
3596            b.set_selection_policy(policy);
3597        }
3598        b.set_show_hidden(self.show_hidden);
3599        b.set_grouped(grouped);
3600        b.set_filter(filter);
3601        b.set_sort(self.sort);
3602        b.set_folders_first(self.folders_first);
3603        b.set_query(&query);
3604        b.pump();
3605        self.groups = b.groups();
3606        self.loading = b.loading() || b.groups_pending();
3607        self.list_error = b.error().map(ToString::to_string);
3608        self.filtered_out = b.filtered_out_count();
3609        if self.loading
3610            && let Some(ctx) = &self.ctx
3611        {
3612            ctx.request_repaint();
3613        }
3614        if let Some(focus) = self.reach_focus.take() {
3615            if b.entries().iter().any(|e| e.path == focus) {
3616                if self.kind == ChooseKind::Open {
3617                    b.set_focus(Some(&focus));
3618                } else {
3619                    b.click(&focus, Modifiers::NONE);
3620                }
3621                self.reveal_cell = true;
3622            } else if self.loading {
3623                self.reach_focus = Some(focus);
3624            }
3625        }
3626        let entries: Vec<Entry> = (b.entries().iter())
3627            .map(|e| Entry {
3628                path: e.path.clone(),
3629                name: e.name.clone(),
3630                is_dir: e.is_dir(),
3631            })
3632            .collect();
3633        (self.highlight, self.selected) = lister.pull();
3634        entries
3635    }
3636
3637    /// What can be selected, by the kind of choice: files, one or several
3638    /// (those the field's filter hides stay selected), or a folder (saving:
3639    /// the folder Enter goes into). Choosing one file, the highlight is the
3640    /// choice: the picker selects nothing apart from it.
3641    fn policy(&self) -> browser::SelectionPolicy {
3642        use browser::{SelectMode, SelectionPolicy};
3643        match self.kind {
3644            ChooseKind::OpenMany => SelectionPolicy::files(SelectMode::Many).keeping_filtered(true),
3645            ChooseKind::Open => SelectionPolicy::files(SelectMode::One),
3646            ChooseKind::Folder | ChooseKind::Save => SelectionPolicy::folders(SelectMode::One),
3647        }
3648    }
3649
3650    /// A step on the browser's focus and selection, the application's
3651    /// writes to the fields taken first, the fields read back after.
3652    fn on_browser<R>(&mut self, step: impl FnOnce(&mut browser::FileBrowser) -> R) -> Option<R> {
3653        let lister = Arc::clone(&self.lister);
3654        let mut lister = lock(&lister);
3655        lister.push(self.highlight, &self.selected);
3656        let out = lister.browser.as_mut().map(step);
3657        (self.highlight, self.selected) = lister.pull();
3658        if lister.browser.is_none() {
3659            self.highlight = 0;
3660            self.selected.clear();
3661            lister.highlight = 0;
3662            lister.selected.clear();
3663        }
3664        out
3665    }
3666
3667    /// Whether the folder's listing, or its groups, are still under way.
3668    pub fn loading(&self) -> bool {
3669        self.loading
3670    }
3671
3672    /// Groups files or leaves each its own entry: the highlight stays on its
3673    /// entry, or goes to the group that takes it in, and a member selected
3674    /// leaves the selection for what its group's entry stands for.
3675    pub fn set_grouped(&mut self, on: bool) {
3676        if on == self.grouped {
3677            return;
3678        }
3679        let before = self.selected.clone();
3680        self.reorder(|p| p.grouped = on);
3681        self.entries();
3682        // The browser puts a member's group in its place: the picker leaves
3683        // the member out instead.
3684        let kept: Vec<PathBuf> = (self.selected.iter())
3685            .filter(|p| before.contains(*p))
3686            .cloned()
3687            .collect();
3688        if kept.len() != self.selected.len() {
3689            self.on_browser(|b| b.set_selection(kept));
3690        }
3691    }
3692
3693    /// Takes another order; the highlighted entry stays highlighted, wherever
3694    /// it lands, and comes into view.
3695    pub fn set_sort(&mut self, sort: PickerSort) {
3696        if sort != self.sort {
3697            self.reorder(|p| p.sort = sort);
3698        }
3699    }
3700
3701    /// Keeps folders first, or sorts them among the files; the highlighted
3702    /// entry stays highlighted, wherever it lands, and comes into view.
3703    pub fn set_folders_first(&mut self, on: bool) {
3704        if on != self.folders_first {
3705            self.reorder(|p| p.folders_first = on);
3706        }
3707    }
3708
3709    /// The browser keeps its focus on its entry, or on the group that takes
3710    /// it in, wherever it lands.
3711    fn reorder(&mut self, change: impl FnOnce(&mut FilePicker)) {
3712        self.entries();
3713        change(self);
3714        self.entries();
3715        self.reveal_cell = true;
3716        if let Some(ctx) = &self.ctx {
3717            ctx.request_repaint();
3718        }
3719    }
3720
3721    /// Whether the field's text puts the entries in order of its best
3722    /// matches, whatever the order asked.
3723    fn ranks(&self) -> bool {
3724        !self.is_path() && !self.text.trim().is_empty() && self.kind != ChooseKind::Save
3725    }
3726
3727    /// Ctrl+L: the folder goes into the field, as a path to edit, and the field
3728    /// takes the focus; a path already typed stays. Saving, the name stays at the
3729    /// path's end with its stem selected, and comes back if the path leads to
3730    /// another folder instead.
3731    pub fn edit_path(&mut self) {
3732        self.refocus = true;
3733        self.select_stem = self.kind == ChooseKind::Save;
3734        self.cursor_to_end = self.kind != ChooseKind::Save;
3735        if self.is_path() {
3736            return;
3737        }
3738        let dir = self.dir.display().to_string();
3739        let separator = if dir.ends_with(['/', std::path::MAIN_SEPARATOR]) {
3740            String::new()
3741        } else {
3742            std::path::MAIN_SEPARATOR.to_string()
3743        };
3744        let name = self.keep_name();
3745        self.text = format!("{dir}{separator}{name}");
3746        self.text_changed();
3747    }
3748
3749    /// `/` or `~` typed on an entry: the field takes it, and the focus.
3750    fn start_path(&mut self, typed: &str) {
3751        self.keep_name();
3752        self.text = typed.to_string();
3753        self.text_changed();
3754        self.refocus = true;
3755        self.cursor_to_end = true;
3756    }
3757
3758    /// Saving, the name in the field, as a path is about to take its place: it
3759    /// is the one to come back once in a folder.
3760    fn keep_name(&mut self) -> String {
3761        if self.kind != ChooseKind::Save || self.is_path() {
3762            return String::new();
3763        }
3764        self.proposed = self.text.clone();
3765        self.text.clone()
3766    }
3767
3768    /// The field says something else now: a name, or a filter's first match.
3769    /// Files selected stay, and the line under the list counts them.
3770    fn text_changed(&mut self) {
3771        let many = self.kind == ChooseKind::OpenMany;
3772        self.on_browser(|b| {
3773            b.set_focus(None);
3774            if !many {
3775                b.set_selection([]);
3776            }
3777        });
3778        self.reveal_cell = true;
3779        self.error = None;
3780    }
3781
3782    /// Whether the field holds a path rather than a filter.
3783    pub fn is_path(&self) -> bool {
3784        self.text.contains('/')
3785            || self.text.contains(std::path::MAIN_SEPARATOR)
3786            || self.text.starts_with('~')
3787    }
3788
3789    /// The field as a path: `~` is home, a relative path is in the
3790    /// folder.
3791    pub fn typed_path(&self) -> PathBuf {
3792        let t = self.text.trim();
3793        // Windows takes `/` for its separator, but not after a verbatim
3794        // prefix (`\\?\C:\`, as `canonicalize` gives): typed paths get
3795        // its own.
3796        #[cfg(windows)]
3797        let t = &t.replace('/', std::path::MAIN_SEPARATOR_STR);
3798        let expanded = match t.strip_prefix('~') {
3799            Some(rest) => {
3800                let rest = rest.trim_start_matches(['/', std::path::MAIN_SEPARATOR]);
3801                home().unwrap_or_default().join(rest)
3802            }
3803            None => PathBuf::from(t),
3804        };
3805        if expanded.is_absolute() {
3806            expanded
3807        } else {
3808            self.dir.join(expanded)
3809        }
3810    }
3811
3812    /// The entries shown: [`entries`](Self::entries), the field's text ranking
3813    /// them.
3814    pub fn visible(&mut self) -> Vec<Entry> {
3815        self.entries()
3816    }
3817
3818    /// What a typed path may complete to: the names in its folder its
3819    /// last part starts (folders end with a separator).
3820    pub fn completions(&self) -> Vec<String> {
3821        if !self.is_path() {
3822            return Vec::new();
3823        }
3824        let text = self.text.as_str();
3825        let cut = text
3826            .rfind(['/', std::path::MAIN_SEPARATOR])
3827            .map_or(0, |i| i + 1);
3828        let (head, part) = text.split_at(cut);
3829        let head_path = if head.is_empty() {
3830            self.dir.clone()
3831        } else {
3832            let mut p = self.clone();
3833            p.text = head.to_string();
3834            p.typed_path()
3835        };
3836        let Ok(read) = self.fs.read_dir(&head_path) else {
3837            return Vec::new();
3838        };
3839        let lower = part.to_lowercase();
3840        let mut out: Vec<String> = read
3841            .into_iter()
3842            .filter_map(|e| {
3843                let (name, is_dir) = (e.name, e.is_dir);
3844                let shown = (self.show_hidden || !name.starts_with('.') || part.starts_with('.'))
3845                    && name.to_lowercase().starts_with(&lower)
3846                    && (is_dir
3847                        || (self.kind != ChooseKind::Folder
3848                            && self.accepts(&head_path.join(&name))));
3849                shown.then(|| format!("{head}{name}{}", if is_dir { "/" } else { "" }))
3850            })
3851            .collect();
3852        out.sort();
3853        out
3854    }
3855
3856    /// Completes the typed path (Tab): to the only completion, else to
3857    /// what every completion shares. Says whether the text changed.
3858    pub fn complete(&mut self) -> bool {
3859        let all = self.completions();
3860        let Some(first) = all.first() else {
3861            return false;
3862        };
3863        let mut common = first.clone();
3864        for c in &all[1..] {
3865            let n = common
3866                .chars()
3867                .zip(c.chars())
3868                .take_while(|(a, b)| a.to_lowercase().eq(b.to_lowercase()))
3869                .count();
3870            common = common.chars().take(n).collect();
3871        }
3872        if common.chars().count() > self.text.chars().count() {
3873            self.text = common;
3874            true
3875        } else {
3876            false
3877        }
3878    }
3879
3880    /// Enter: into a folder, or the choice. Saving, the folder selected
3881    /// goes first: otherwise the field's name is what Enter takes.
3882    pub fn activate(&mut self) -> Option<PickerAnswer> {
3883        self.error = None;
3884        if self.kind == ChooseKind::Save {
3885            if let Some(dir) = self.selected.first().cloned() {
3886                self.go(dir);
3887                self.select_stem = true;
3888                return None;
3889            }
3890            return self.save();
3891        }
3892        if self.is_path() {
3893            let p = self.typed_path();
3894            if self.fs.is_dir(&p) {
3895                self.go(p);
3896                return None;
3897            }
3898            return match self.kind {
3899                ChooseKind::Open | ChooseKind::OpenMany if self.fs.is_file(&p) => {
3900                    Some(PickerAnswer::Chosen(vec![p]))
3901                }
3902                _ => {
3903                    self.error = Some(format!("{} does not exist", p.display()));
3904                    None
3905                }
3906            };
3907        }
3908        let shown = self.visible();
3909        let e = shown.get(self.highlight)?.clone();
3910        if e.is_dir {
3911            self.go(e.path);
3912            return None;
3913        }
3914        if self.kind == ChooseKind::OpenMany && !self.selected.is_empty() {
3915            return Some(PickerAnswer::Chosen(
3916                self.selected.iter().cloned().collect(),
3917            ));
3918        }
3919        Some(PickerAnswer::Chosen(vec![e.path]))
3920    }
3921
3922    /// Enter, saving: into a folder, else the field's name with the
3923    /// filter's extension when it has none, and the question when it
3924    /// exists.
3925    fn save(&mut self) -> Option<PickerAnswer> {
3926        let typed = self.text.trim().to_string();
3927        if typed.is_empty() {
3928            return None;
3929        }
3930        if self.enters(self.typed_path()) {
3931            return None;
3932        }
3933        let parent = self.typed_path().parent().map(Path::to_path_buf);
3934        if file_part(&typed) == typed.len() || !parent.is_some_and(|d| self.fs.is_dir(&d)) {
3935            self.error = Some(format!("{} does not exist", self.typed_path().display()));
3936            return None;
3937        }
3938        if let Some(extension) = self.filter().and_then(|f| f.extensions.first()) {
3939            self.text = with_extension(&typed, extension);
3940        }
3941        let p = self.typed_path();
3942        if self.enters(p.clone()) {
3943            return None;
3944        }
3945        if self.confirm_overwrite && self.fs.is_file(&p) {
3946            return Some(PickerAnswer::Replace(p));
3947        }
3948        Some(PickerAnswer::Chosen(vec![p]))
3949    }
3950
3951    /// Goes into `p` if it is a folder, the proposed name back in the
3952    /// field in place of the folder's; says whether it did.
3953    fn enters(&mut self, p: PathBuf) -> bool {
3954        if !self.fs.is_dir(&p) {
3955            return false;
3956        }
3957        self.go(p);
3958        self.text = self.proposed.clone();
3959        self.select_stem = true;
3960        true
3961    }
3962
3963    /// Takes another filter (`filters.len()`: all files). Saving, a name
3964    /// whose extension one of the request's filters names takes the new
3965    /// filter's first, unless the new filter accepts it too; an extension
3966    /// no filter names is the person's and stays, and so does the name
3967    /// under a filter without extensions.
3968    pub fn set_filter(&mut self, index: usize) {
3969        self.filter_index = index;
3970        self.on_browser(|b| b.set_focus(None));
3971        if self.kind != ChooseKind::Save {
3972            return;
3973        }
3974        let Some(new) = self.filter().and_then(|f| f.extensions.first()).cloned() else {
3975            return;
3976        };
3977        let Some(dot) = extension_dot(&self.text) else {
3978            return;
3979        };
3980        let typed = self.text[dot + 1..].to_string();
3981        let named = |f: &FileFilter| f.extensions.iter().any(|e| e.eq_ignore_ascii_case(&typed));
3982        if self.filters.iter().any(named) && !self.filter().is_some_and(named) {
3983            self.text.truncate(dot + 1);
3984            self.text.push_str(&new);
3985            self.select_stem = true;
3986        }
3987    }
3988
3989    /// Whether this kind of choice offers a new folder.
3990    fn makes_folders(&self) -> bool {
3991        matches!(self.kind, ChooseKind::Save | ChooseKind::Folder)
3992    }
3993
3994    /// The text of `key` as the picker's language says it.
3995    fn say(&self, key: &strings::StrKey, args: &[(&str, &str)]) -> String {
3996        match &self.ctx {
3997            Some(ctx) => strings::tr_args(ctx, key, args),
3998            None => strings::fill(key.fallback, args),
3999        }
4000    }
4001
4002    /// [`Self::say`] with typed arguments (counts as numbers).
4003    fn say_with(&self, key: &strings::StrKey, args: &[(&str, Arg<'_>)]) -> String {
4004        match &self.ctx {
4005            Some(ctx) => strings::tr_with(ctx, key, args),
4006            None => strings::fill_with(key.fallback, args),
4007        }
4008    }
4009
4010    /// Asks the new folder's name, in a row under the folder: Enter makes
4011    /// it, Escape closes the row. Without a file system that can make one,
4012    /// the reason is the picker's error, and the result.
4013    pub fn begin_new_folder(&mut self) -> Result<(), String> {
4014        self.error = None;
4015        if !self.makes_folders() {
4016            return Err("a new folder is offered when saving or choosing a folder".into());
4017        }
4018        if !self.fs.can_create_dirs() {
4019            let reason = self.say(&txt::FILES_FOLDER_READ_ONLY, &[]);
4020            self.error = Some(reason.clone());
4021            return Err(reason);
4022        }
4023        self.naming.get_or_insert_default();
4024        self.naming_focus = true;
4025        Ok(())
4026    }
4027
4028    /// Makes a folder in the one shown, and goes into it. A refusal is the
4029    /// picker's error, and the result.
4030    pub fn create_folder(&mut self, name: &str) -> Result<PathBuf, String> {
4031        match self.make_folder(name.trim()) {
4032            Ok(path) => {
4033                self.naming = None;
4034                self.go(path.clone());
4035                Ok(path)
4036            }
4037            Err(reason) => {
4038                self.error = Some(reason.clone());
4039                Err(reason)
4040            }
4041        }
4042    }
4043
4044    fn make_folder(&self, name: &str) -> Result<PathBuf, String> {
4045        if !self.makes_folders() {
4046            return Err("a new folder is offered when saving or choosing a folder".into());
4047        }
4048        if !self.fs.can_create_dirs() {
4049            return Err(self.say(&txt::FILES_FOLDER_READ_ONLY, &[]));
4050        }
4051        if name.is_empty() {
4052            return Err(self.say(&txt::FILES_FOLDER_NAME_EMPTY, &[]));
4053        }
4054        if matches!(name, "." | "..") || file_part(name) != 0 {
4055            return Err(self.say(&txt::FILES_FOLDER_NAME_INVALID, &[("name", name)]));
4056        }
4057        let path = self.dir.join(name);
4058        if self.fs.metadata(&path).is_ok() {
4059            return Err(self.say(&txt::FILES_FOLDER_EXISTS, &[("name", name)]));
4060        }
4061        self.fs.create_dir(&path).map_err(|e| {
4062            let reason = e.to_string();
4063            self.say(
4064                &txt::FILES_FOLDER_FAILED,
4065                &[("name", name), ("reason", &reason)],
4066            )
4067        })?;
4068        Ok(path)
4069    }
4070
4071    /// Opens the question before replacing `path` over the picker, which
4072    /// waits for the dialog; the yes ends the choice ([`CMD_REPLACE`]).
4073    /// Without the dialogs plugin nobody can ask: nothing is replaced, and
4074    /// the picker says so.
4075    fn ask_replace(&mut self, app: &AppHandle, id: u64, path: &Path) {
4076        let name = path
4077            .file_name()
4078            .map(|n| n.to_string_lossy().into_owned())
4079            .unwrap_or_else(|| path.display().to_string());
4080        let ctx = app.egui();
4081        let Some(dialogs) = app.service(&DIALOGS) else {
4082            log::warn!(target: "egui_pop", "files: no dialogs plugin to ask before replacing {}", path.display());
4083            self.error = Some(strings::tr_args(
4084                &ctx,
4085                &txt::FILES_REPLACE_NO_DIALOGS,
4086                &[("name", &name)],
4087            ));
4088            return;
4089        };
4090        let folder = path
4091            .parent()
4092            .map(|d| d.display().to_string())
4093            .unwrap_or_default();
4094        let question = Confirm::new(
4095            &strings::tr_args(&ctx, &txt::FILES_REPLACE_TITLE, &[("name", &name)]),
4096            &strings::tr(&ctx, &txt::FILES_REPLACE),
4097            CMD_REPLACE,
4098        )
4099        .detail(&strings::tr_args(
4100            &ctx,
4101            &txt::FILES_REPLACE_DETAIL,
4102            &[("folder", &folder)],
4103        ))
4104        .danger()
4105        .args(json!({ "id": id, "path": path.display().to_string() }));
4106        self.asking = Some(dialogs.open_now(question));
4107        ctx.request_repaint();
4108    }
4109
4110    /// Ctrl+Enter, and the primary button: the folder (choosing a
4111    /// folder), the selection, the field's name (saving: a folder selected
4112    /// does not turn Save into Open), or what Enter would choose.
4113    pub fn accept(&mut self) -> Option<PickerAnswer> {
4114        match self.kind {
4115            ChooseKind::Folder => Some(PickerAnswer::Chosen(vec![self.folder_choice()])),
4116            ChooseKind::Save => {
4117                self.error = None;
4118                self.save()
4119            }
4120            ChooseKind::OpenMany if !self.selected.is_empty() => Some(PickerAnswer::Chosen(
4121                self.selected.iter().cloned().collect(),
4122            )),
4123            _ => self.activate(),
4124        }
4125    }
4126
4127    /// What choosing a folder takes now: a typed folder, the folder selected,
4128    /// the entry the filter leaves highlighted, else the folder shown.
4129    fn folder_choice(&mut self) -> PathBuf {
4130        if self.is_path() && self.fs.is_dir(&self.typed_path()) {
4131            return self.typed_path();
4132        }
4133        if let Some(selected) = self.selected.first() {
4134            return selected.clone();
4135        }
4136        if !self.text.trim().is_empty()
4137            && let Some(e) = self.visible().get(self.highlight)
4138        {
4139            return e.path.clone();
4140        }
4141        self.dir.clone()
4142    }
4143
4144    /// Selects or unselects the highlighted entry: a file choosing several (a
4145    /// folder is refused, the reason in [`error`](Self::error)), a folder
4146    /// choosing one. Does nothing in the other kinds, which have no key for it.
4147    pub fn toggle(&mut self) {
4148        self.error = None;
4149        let shown = self.visible();
4150        if let Some(e) = shown.get(self.highlight) {
4151            self.toggle_entry(e);
4152        }
4153    }
4154
4155    /// See [`toggle`](Self::toggle).
4156    fn toggle_entry(&mut self, e: &Entry) {
4157        let path = e.path.clone();
4158        match self.kind {
4159            ChooseKind::OpenMany if e.is_dir => {
4160                self.error = Some(self.say(&txt::FILES_SELECT_FOLDER, &[("name", &e.name)]));
4161                self.on_browser(|b| b.set_focus(Some(&path)));
4162            }
4163            ChooseKind::OpenMany => {
4164                self.on_browser(|b| b.click(&path, Modifiers::COMMAND));
4165            }
4166            ChooseKind::Folder => {
4167                self.on_browser(|b| {
4168                    if b.selection().contains(&path) {
4169                        b.set_selection([]);
4170                        b.set_focus(Some(&path));
4171                    } else {
4172                        b.click(&path, Modifiers::NONE);
4173                    }
4174                });
4175            }
4176            ChooseKind::Open | ChooseKind::Save => {}
4177        }
4178    }
4179
4180    /// Selects every file shown (choosing several). None to select is a
4181    /// refusal: the reason is the picker's error, and the result.
4182    pub fn select_all(&mut self) -> Result<(), String> {
4183        self.error = None;
4184        if self.kind != ChooseKind::OpenMany {
4185            return Err("selecting all is offered when choosing several files".into());
4186        }
4187        if self.visible().iter().all(|e| e.is_dir) {
4188            let reason = self.say(&txt::FILES_SELECT_ALL_NONE, &[]);
4189            self.error = Some(reason.clone());
4190            return Err(reason);
4191        }
4192        // The files the field hides stay selected (the policy keeps them).
4193        self.on_browser(|b| b.select_all());
4194        Ok(())
4195    }
4196
4197    /// Whether a selection exists apart from the highlight: several files, or
4198    /// the folder to choose, where the list opens with nothing selected.
4199    fn selects_apart(&self) -> bool {
4200        matches!(self.kind, ChooseKind::OpenMany | ChooseKind::Folder)
4201    }
4202
4203    /// The highlight goes to the `to`th entry shown, from the arrows or Tab:
4204    /// choosing several, it extends the selection with `extend`; choosing a
4205    /// folder, or saving, it selects the folder it lands on.
4206    /// The browser's focus moves, and its policy says what the selection
4207    /// does: the files from the anchor with `extend`, choosing several; the
4208    /// folder landed on alone, choosing a folder or saving.
4209    fn move_highlight(&mut self, to: usize, shown: &[Entry], extend: bool) {
4210        let Some(e) = shown.get(to) else {
4211            return;
4212        };
4213        self.error = None;
4214        let path = e.path.clone();
4215        let open = self.kind == ChooseKind::Open;
4216        self.on_browser(|b| {
4217            if open {
4218                b.set_focus(Some(&path));
4219            } else {
4220                b.focus_on(&path, extend);
4221            }
4222        });
4223    }
4224
4225    /// A click on the `n`th entry shown, with these modifiers. It selects; it
4226    /// does not open.
4227    fn click_entry(&mut self, n: usize, shown: &[Entry], modifiers: Modifiers) {
4228        let Some(e) = shown.get(n) else {
4229            return;
4230        };
4231        self.error = None;
4232        let path = e.path.clone();
4233        match self.kind {
4234            ChooseKind::OpenMany if modifiers.shift => {
4235                self.on_browser(|b| b.click(&path, Modifiers::SHIFT));
4236            }
4237            ChooseKind::Folder | ChooseKind::OpenMany if modifiers.command => self.toggle_entry(e),
4238            ChooseKind::OpenMany | ChooseKind::Folder | ChooseKind::Save => {
4239                // The policy selects a file choosing several, a folder
4240                // otherwise; anything else leaves nothing selected.
4241                self.on_browser(|b| b.click(&path, Modifiers::NONE));
4242                if self.kind == ChooseKind::Save && !e.is_dir {
4243                    self.text = e.name.clone();
4244                    self.select_stem = true;
4245                }
4246            }
4247            ChooseKind::Open => {
4248                self.on_browser(|b| b.set_focus(Some(&path)));
4249            }
4250        }
4251    }
4252
4253    /// What the primary button does now: its label, the readout of what it
4254    /// takes (announced when it changes), and why it is off, when it is.
4255    pub fn primary(&mut self) -> Primary {
4256        let name_of = |p: &Path| folder_name(p);
4257        match self.kind {
4258            ChooseKind::Save => {
4259                let label = self.say(&txt::FILES_SAVE, &[]);
4260                if self.text.trim().is_empty() {
4261                    return Primary {
4262                        label,
4263                        readout: None,
4264                        off: Some(self.say(&txt::FILES_NAME_NEEDED, &[])),
4265                    };
4266                }
4267                let p = self.typed_path();
4268                let folder = p.parent().map(name_of).unwrap_or_default();
4269                let readout = self.say(
4270                    &txt::FILES_READOUT_SAVE,
4271                    &[("name", &name_of(&p)), ("folder", &folder)],
4272                );
4273                Primary {
4274                    label,
4275                    readout: Some(readout),
4276                    off: None,
4277                }
4278            }
4279            ChooseKind::Folder => {
4280                let choice = self.folder_choice();
4281                Primary {
4282                    label: self.say(&txt::FILES_CHOOSE_NAMED, &[("name", &name_of(&choice))]),
4283                    readout: Some(path_text(&choice)),
4284                    off: None,
4285                }
4286            }
4287            ChooseKind::OpenMany if !self.selected.is_empty() => {
4288                let shown = self.visible();
4289                let total = self.selected.len();
4290                let paths: HashSet<&PathBuf> = shown.iter().map(|e| &e.path).collect();
4291                let hidden = self.selected.iter().filter(|p| !paths.contains(p)).count();
4292                let args = [("count", total.into()), ("hidden", hidden.into())];
4293                let label = if total == 1 {
4294                    self.say(&txt::FILES_OPEN_ONE_FILE, &[])
4295                } else {
4296                    self.say_with(&txt::FILES_OPEN_FILES, &args)
4297                };
4298                let readout = if total == 1 && hidden == 0 {
4299                    let name = self
4300                        .selected
4301                        .first()
4302                        .map(|p| name_of(p))
4303                        .unwrap_or_default();
4304                    Some(self.say(&txt::FILES_READOUT_FILE, &[("name", &name)]))
4305                } else if hidden == 0 {
4306                    Some(self.say_with(&txt::FILES_SELECTED, &args))
4307                } else {
4308                    Some(self.say_with(&txt::FILES_SELECTED_NOT_SHOWN, &args))
4309                };
4310                Primary {
4311                    label,
4312                    readout,
4313                    off: None,
4314                }
4315            }
4316            // What Enter takes: a file, or a folder it goes into (as GTK).
4317            ChooseKind::Open | ChooseKind::OpenMany => {
4318                let label = self.say(&txt::FILES_OPEN, &[]);
4319                let target = if self.is_path() {
4320                    let p = self.typed_path();
4321                    if self.fs.is_dir(&p) {
4322                        Some((p, true))
4323                    } else {
4324                        self.fs.is_file(&p).then_some((p, false))
4325                    }
4326                } else {
4327                    let shown = self.visible();
4328                    shown
4329                        .get(self.highlight)
4330                        .map(|e| (e.path.clone(), e.is_dir))
4331                };
4332                match target {
4333                    None => Primary {
4334                        label,
4335                        readout: None,
4336                        off: Some(self.say(&txt::FILES_NOTHING_TO_OPEN, &[])),
4337                    },
4338                    Some((p, true)) => Primary {
4339                        label,
4340                        readout: Some(
4341                            self.say(&txt::FILES_READOUT_ENTER, &[("name", &name_of(&p))]),
4342                        ),
4343                        off: None,
4344                    },
4345                    Some((p, false)) => Primary {
4346                        label,
4347                        readout: Some(
4348                            self.say(&txt::FILES_READOUT_FILE, &[("name", &name_of(&p))]),
4349                        ),
4350                        off: None,
4351                    },
4352                }
4353            }
4354        }
4355    }
4356
4357    /// What the list says when it shows nothing, and the way out it offers.
4358    pub fn empty_state(&self) -> EmptyState {
4359        if let Some(reason) = &self.list_error {
4360            return EmptyState::Unreadable(reason.clone());
4361        }
4362        if self.filtered_out > 0 && self.ranks() {
4363            return EmptyState::NoResults(self.text.trim().to_string());
4364        }
4365        if self.filtered_out > 0
4366            && self.kind != ChooseKind::Folder
4367            && let Some(f) = self.filter()
4368        {
4369            return EmptyState::NoneOfType(f.name.clone());
4370        }
4371        if self.kind == ChooseKind::Folder && self.filtered_out > 0 {
4372            return EmptyState::NoFolders;
4373        }
4374        EmptyState::Empty
4375    }
4376
4377    /// The picker as the bridge shows it.
4378    pub fn describe(&mut self) -> Json {
4379        let shown = self.visible();
4380        json!({
4381            "dir": self.dir.display().to_string(),
4382            "text": self.text,
4383            "highlight": self.highlight,
4384            "shown": shown.iter().take(64).map(|e| if e.is_dir { format!("{}/", e.name) } else { e.name.clone() }).collect::<Vec<_>>(),
4385            "selected": self.selected.iter().map(|p| p.display().to_string()).collect::<Vec<_>>(),
4386            "filter": self.filter().map(|f| f.name.clone()),
4387            "completions": self.completions(),
4388            "error": self.error,
4389            "new_folder": self.naming,
4390            "asking": self.asking,
4391            "preview": self.preview_state(),
4392            "pane_width": self.pane_width,
4393            "view": self.view.as_str(),
4394            "thumbnail_size": self.thumbnail_size,
4395            "thumbnails_per_row": self.zoom.per_row(),
4396            "columns": self.columns,
4397            "sort": self.sort.as_text(),
4398            "folders_first": self.folders_first,
4399            "choices": self.choice_values,
4400            "grouped": self.grouping_on(),
4401            "groups": shown.iter().take(64).filter_map(|e| {
4402                self.group_of(&e.path).map(|g| json!({
4403                    "main": e.name,
4404                    "members": g.member_names(),
4405                    "badges": g.badges,
4406                }))
4407            }).collect::<Vec<_>>(),
4408        })
4409    }
4410
4411    /// The highlighted entry's preview as agents read it (`null` without
4412    /// the pane).
4413    fn preview_state(&mut self) -> Json {
4414        let Some(previews) = self.previews.clone().filter(|_| self.show_preview) else {
4415            return Json::Null;
4416        };
4417        let Some(e) = self.highlighted() else {
4418            return Json::Null;
4419        };
4420        let (shown, stand_in) = self.preview_of(&e, |path| previews.peek(&self.fs, path));
4421        let mut d = shown.describe();
4422        d["path"] = json!(e.path.display().to_string());
4423        if let Some(member) = stand_in {
4424            d["stand_in"] = json!(member.display().to_string());
4425        }
4426        d
4427    }
4428
4429    /// The preview of an entry, by `ask`: its own, else, for a group's main file
4430    /// without one, the image of the first member that has one, and that member.
4431    /// A member is asked only then, in turn, and a sidecar's text never stands in
4432    /// for a photo.
4433    fn preview_of(
4434        &self,
4435        e: &Entry,
4436        mut ask: impl FnMut(&Path) -> preview::Shown,
4437    ) -> (preview::Shown, Option<PathBuf>) {
4438        let own = ask(&e.path);
4439        if !matches!(own, preview::Shown::Nothing | preview::Shown::Failed(_)) {
4440            return (own, None);
4441        }
4442        for member in self.group_of(&e.path).map_or(&[][..], |g| &g.members) {
4443            let shown = ask(member);
4444            match &shown {
4445                preview::Shown::Loading => return (shown, None),
4446                preview::Shown::Ready(ready)
4447                    if matches!(ready.preview.body, preview::Body::Image(_)) =>
4448                {
4449                    return (shown, Some(member.clone()));
4450                }
4451                _ => {}
4452            }
4453        }
4454        (own, None)
4455    }
4456
4457    /// Draws the picker; its answer when given. Drawn to fill its room
4458    /// (`fill`, a dialog), its footer keeps its whole height at the
4459    /// bottom and what is above it scrolls when the room runs short
4460    /// ([`overlay::DialogLayout`]).
4461    pub fn show(&mut self, ui: &mut Ui, places: &Places) -> Option<PickerAnswer> {
4462        let mut answer = None;
4463        if self.fill {
4464            let layout = overlay::DialogLayout::new(ui, "egui_pop.files.picker").fill(true);
4465            layout.body(ui, |ui, height| {
4466                self.show_body(ui, places, Some(height), &mut answer);
4467            });
4468            layout.footer(ui, |ui| self.show_footer(ui, &mut answer));
4469        } else {
4470            self.show_body(ui, places, None, &mut answer);
4471            self.show_footer(ui, &mut answer);
4472        }
4473        answer
4474    }
4475
4476    /// The picker above its footer: the toolbar, the path field, the
4477    /// places, the list and the preview; the list takes what `height`
4478    /// leaves (none: `LIST_HEIGHT`).
4479    fn show_body(
4480        &mut self,
4481        ui: &mut Ui,
4482        places: &Places,
4483        height: Option<f32>,
4484        answer: &mut Option<PickerAnswer>,
4485    ) {
4486        let top = ui.cursor().min.y;
4487        let t = Tokens::of(ui.ctx());
4488        self.ctx = Some(ui.ctx().clone());
4489        let first = !self.focused;
4490        self.focused = true;
4491        // Under its question: drawn, but neither the pointer nor the keys
4492        // are its own.
4493        let waiting = self.asking.is_some();
4494        if waiting {
4495            ui.disable();
4496        }
4497        let field_id = ui.scope_id().with("egui_pop.files.field");
4498        if !waiting {
4499            self.path_keys(ui);
4500        }
4501        // The plain keys go to whichever widget Tab took the focus to
4502        // (the splitter's arrows, a button's Enter); else they are the
4503        // field's and the list's.
4504        let elsewhere = !first
4505            && ui
4506                .memory(|m| m.focused())
4507                .is_some_and(|f| f != field_id && !self.row_ids.contains(&f));
4508        // Keys taken before the field sees them. Tab completes a path;
4509        // out of a path, it goes to the next widget.
4510        let empty = self.text.is_empty();
4511        let path = self.is_path();
4512        let keys = |i: &mut egui::InputState| {
4513            // First: egui matches a key asked without Alt with Alt held too,
4514            // so the plain Up below would take it.
4515            let alt_up = i.consume_key(Modifiers::ALT, Key::ArrowUp);
4516            // Shift too, for the same reason.
4517            let shift_down = !elsewhere && i.consume_key(Modifiers::SHIFT, Key::ArrowDown);
4518            let shift_up = !elsewhere && i.consume_key(Modifiers::SHIFT, Key::ArrowUp);
4519            let mut plain = |key| !elsewhere && i.consume_key(Modifiers::NONE, key);
4520            let (down, up, enter) = (
4521                shift_down || plain(Key::ArrowDown),
4522                shift_up || plain(Key::ArrowUp),
4523                plain(Key::Enter),
4524            );
4525            let tab = path && plain(Key::Tab);
4526            let backspace = empty && plain(Key::Backspace);
4527            (
4528                down,
4529                up,
4530                shift_down || shift_up,
4531                enter,
4532                i.consume_key(Modifiers::COMMAND, Key::Enter),
4533                tab,
4534                alt_up || backspace,
4535                i.consume_key(Modifiers::COMMAND, Key::D),
4536            )
4537        };
4538        let (down, up, extend, enter, accept, tab, parent, bookmark) = if waiting {
4539            Default::default()
4540        } else {
4541            ui.input_mut(keys)
4542        };
4543        // Drawn on its own, the picker has no keymap for these.
4544        // The grid's moves in two dimensions. The field keeps the keys that
4545        // move its cursor while it holds text and the focus.
4546        let grid = self.grid_on();
4547        let in_cell = self.focus_cell
4548            || ui
4549                .memory(|m| m.focused())
4550                .is_some_and(|f| self.row_ids.contains(&f));
4551        let editing = !empty && ui.memory(|m| m.has_focus(field_id));
4552        let (grid_move, grid_extend) = if grid && !waiting && !elsewhere && !editing {
4553            ui.input_mut(|i| {
4554                let mut moved = (None, false);
4555                for (key, to) in [
4556                    (Key::ArrowLeft, browser::ModeKey::Left),
4557                    (Key::ArrowRight, browser::ModeKey::Right),
4558                    (Key::Home, browser::ModeKey::Home),
4559                    (Key::End, browser::ModeKey::End),
4560                ] {
4561                    // Shift first: egui matches a key asked without it with
4562                    // it held too.
4563                    if i.consume_key(Modifiers::SHIFT, key) {
4564                        moved = (Some(to), true);
4565                    } else if i.consume_key(Modifiers::NONE, key) {
4566                        moved = (Some(to), false);
4567                    }
4568                }
4569                moved
4570            })
4571        } else {
4572            (None, false)
4573        };
4574        // Left and Right leave the folder in the columns, as the mode says.
4575        if self.columns_on() && !waiting && !elsewhere && !editing {
4576            let cols = &self.cols;
4577            let travel = ui.input_mut(|i| {
4578                [
4579                    (Key::ArrowLeft, browser::ModeKey::Left),
4580                    (Key::ArrowRight, browser::ModeKey::Right),
4581                ]
4582                .into_iter()
4583                .filter_map(|(key, mk)| cols.travel(mk).map(|t| (key, t)))
4584                .find(|(key, _)| i.consume_key(Modifiers::NONE, *key))
4585                .map(|(_, t)| t)
4586            });
4587            if let Some(t) = travel {
4588                self.travel(t);
4589            }
4590        }
4591        if grid && !waiting {
4592            let (bigger, smaller) = ui.input_mut(|i| {
4593                (
4594                    i.consume_key(Modifiers::COMMAND, Key::Plus)
4595                        || i.consume_key(Modifiers::COMMAND, Key::Equals),
4596                    i.consume_key(Modifiers::COMMAND, Key::Minus),
4597                )
4598            });
4599            let (width, gap) = self.grid_room;
4600            if bigger {
4601                self.set_zoom(
4602                    self.zoom
4603                        .zoomed_in(width, gap)
4604                        .under(self.resize, width, gap),
4605                );
4606            }
4607            if smaller {
4608                self.set_zoom(
4609                    self.zoom
4610                        .zoomed_out(width, gap)
4611                        .under(self.resize, width, gap),
4612                );
4613            }
4614        }
4615        let (toggle, select_all) = if waiting || self.declared_keys {
4616            (false, false)
4617        } else {
4618            let (selects, all) = (
4619                self.selects_apart(),
4620                self.kind == ChooseKind::OpenMany && !path,
4621            );
4622            ui.input_mut(|i| {
4623                (
4624                    selects && i.consume_key(Modifiers::COMMAND, Key::Space),
4625                    all && i.consume_key(Modifiers::COMMAND, Key::A),
4626                )
4627            })
4628        };
4629        // Drawn on its own, the picker reads its commands' keys itself.
4630        if !waiting
4631            && !self.declared_keys
4632            && self.previews.is_some()
4633            && let Some(n) = browser::mode_key(ui)
4634        {
4635            self.set_mode_index(n);
4636        }
4637        if !waiting && !self.declared_keys {
4638            // Alt+P, as the preview pane of the Windows file explorer.
4639            if self.previews.is_some() && ui.input_mut(|i| i.consume_key(Modifiers::ALT, Key::P)) {
4640                self.show_preview = !self.show_preview;
4641            }
4642            for (modifiers, key, id) in [
4643                (Modifiers::COMMAND, Key::H, CMD_TOGGLE_HIDDEN),
4644                (Modifiers::NONE, Key::F5, CMD_RELOAD),
4645                (Modifiers::ALT, Key::ArrowLeft, CMD_BACK),
4646                (Modifiers::ALT, Key::ArrowRight, CMD_FORWARD),
4647            ] {
4648                if ui.input_mut(|i| i.consume_key(modifiers, key)) {
4649                    self.run_key(&id);
4650                }
4651            }
4652        }
4653        let preview_on = self.show_preview && self.previews.is_some();
4654        let bookmarked = places.bookmarks.contains(&self.dir);
4655        let mut crumbs_below = false;
4656        ui.horizontal(|ui| {
4657            let r = ui
4658                .button(strings::tr(ui.ctx(), &txt::PICKER_UP))
4659                .on_hover_text(keys_tip(&["Alt+Up".into()]));
4660            if r.clicked() {
4661                self.up();
4662                self.refocus |= by_pointer(&r);
4663            }
4664            let label = if bookmarked {
4665                &txt::FILES_UNBOOKMARK
4666            } else {
4667                &txt::FILES_BOOKMARK
4668            };
4669            let r = ui.button(strings::tr(ui.ctx(), label));
4670            if r.clicked() {
4671                *answer = Some(PickerAnswer::Bookmark(self.dir.clone(), !bookmarked));
4672                self.refocus |= by_pointer(&r);
4673            }
4674            if self.makes_folders() {
4675                self.new_folder_button(ui);
4676            }
4677            if self.views().len() > 1 {
4678                self.view_controls(ui);
4679            }
4680            if self.can_group() {
4681                self.group_control(ui);
4682            }
4683            crumbs_below = ui.available_width() < CRUMBS_MIN_WIDTH;
4684            if !crumbs_below {
4685                self.breadcrumbs(ui);
4686            }
4687        });
4688        if crumbs_below {
4689            ui.horizontal(|ui| self.breadcrumbs(ui));
4690        }
4691        let mut back_to_field = false;
4692        if self.naming.is_some() {
4693            back_to_field = self.naming_row(ui, answer);
4694        }
4695        if bookmark {
4696            *answer = Some(PickerAnswer::Bookmark(self.dir.clone(), !bookmarked));
4697        }
4698        if parent {
4699            self.up();
4700        }
4701        let hint = if self.kind == ChooseKind::Save {
4702            &txt::FILES_NAME
4703        } else {
4704            &txt::FILES_FILTER
4705        };
4706        let field = ui.add(
4707            egui::TextEdit::singleline(&mut self.text)
4708                .id(field_id)
4709                .hint_text(strings::tr(ui.ctx(), hint))
4710                .desired_width(f32::INFINITY),
4711        );
4712        // In a path, Tab stays in the field: it completes.
4713        if self.is_path() {
4714            ui.memory_mut(|m| {
4715                m.set_focus_lock_filter(
4716                    field_id,
4717                    EventFilter {
4718                        tab: true,
4719                        horizontal_arrows: true,
4720                        vertical_arrows: true,
4721                        ..Default::default()
4722                    },
4723                )
4724            });
4725        }
4726        egui_pop_core::a11y::name(&field, egui::Role::TextInput, &strings::tr(ui.ctx(), hint));
4727        let refocus = std::mem::take(&mut self.refocus);
4728        // In the grid, the arrows leave the focus where it is: on a cell, it
4729        // follows the highlight.
4730        let cell_stays = grid && in_cell;
4731        let arrows = down || up;
4732        if first || tab || parent || (arrows && !cell_stays) || enter || back_to_field || refocus {
4733            field.request_focus();
4734            self.focus_cell = false;
4735        } else if (arrows || grid_move.is_some()) && cell_stays {
4736            self.focus_cell = true;
4737        }
4738        // The stem when the field gets the focus, not under a click placing
4739        // the cursor: typing replaces the name and keeps its extension.
4740        let clicking = ui.input(|i| i.pointer.any_down() || i.pointer.any_released());
4741        if self.kind == ChooseKind::Save
4742            && !waiting
4743            && (self.select_stem || (field.gained_focus() && !clicking))
4744        {
4745            self.select_stem = false;
4746            let (start, end) = stem_chars(&self.text);
4747            let mut state = egui::TextEdit::load_state(ui.ctx(), field.id).unwrap_or_default();
4748            state
4749                .cursor
4750                .set_char_range(Some(egui::text::CCursorRange::two(
4751                    egui::text::CCursor::new(start),
4752                    egui::text::CCursor::new(end),
4753                )));
4754            state.store(ui.ctx(), field.id);
4755        }
4756        if field.changed() {
4757            self.text_changed();
4758        }
4759        let completed = tab && self.complete();
4760        if completed {
4761            self.on_browser(|b| b.set_focus(None));
4762        }
4763        if std::mem::take(&mut self.cursor_to_end) || completed {
4764            let mut state = egui::TextEdit::load_state(ui.ctx(), field.id).unwrap_or_default();
4765            let end = egui::text::CCursor::new(self.text.chars().count());
4766            state
4767                .cursor
4768                .set_char_range(Some(egui::text::CCursorRange::one(end)));
4769            state.store(ui.ctx(), field.id);
4770        }
4771        let completions = self.completions();
4772        if !completions.is_empty() {
4773            ui.horizontal_wrapped(|ui| {
4774                for c in completions.iter().take(8) {
4775                    if ui.small_button(c).clicked() {
4776                        self.text = c.clone();
4777                    }
4778                }
4779            });
4780        }
4781        let shown = self.visible();
4782        let key = grid_move.or(if down {
4783            Some(browser::ModeKey::Down)
4784        } else if up {
4785            Some(browser::ModeKey::Up)
4786        } else {
4787            None
4788        });
4789        if let Some(key) = key {
4790            // Choosing a folder the list opens with nothing selected: the first
4791            // press selects the entry highlighted, rather than the one after it.
4792            // Otherwise the mode shown says where the key goes, by its layout.
4793            let to = if self.kind == ChooseKind::Folder && self.selected.is_empty() {
4794                self.highlight
4795            } else {
4796                let mode: &dyn browser::ViewMode = if grid { &self.thumbs } else { &self.details };
4797                mode.step(self.highlight, shown.len(), key)
4798            };
4799            self.move_highlight(to, &shown, extend || grid_extend);
4800            self.reveal_cell = true;
4801        }
4802        ui.add_space(t.space.s);
4803        // The list takes what the room leaves under what is above it (the
4804        // footer is kept apart, see `show`); at its least, the body scrolls.
4805        let list_height = match height {
4806            Some(h) => (h - (ui.cursor().min.y - top)).max(ui.spacing().interact_size.y),
4807            None => LIST_HEIGHT,
4808        };
4809        ui.horizontal_top(|ui| {
4810            // Places.
4811            ui.vertical(|ui| {
4812                ui.set_width(PLACES_WIDTH);
4813                ui.scroll_area(
4814                    egui::ScrollArea::vertical()
4815                        .id_salt("egui_pop.files.places")
4816                        .max_height(list_height)
4817                        .auto_shrink([false, true]),
4818                    |ui| {
4819                        if let Some(a) = self.side_bar(ui, places) {
4820                            *answer = Some(a);
4821                        }
4822                    },
4823                );
4824            });
4825            // Not a separator: in a row it takes the row's height, which
4826            // grows with it in a modal.
4827            ui.add_space(t.space.m);
4828            // The gap: the space added below, and the row's own spacing
4829            // after the list.
4830            let gap = t.space.m + ui.spacing().item_spacing.x;
4831            let room = ui.available_width();
4832            let (list_width, pane_width) = split_list(room, gap, preview_on, self.pane_width);
4833            self.pane_dragging = false;
4834            if let Some(mut width) = pane_width {
4835                // Laid out before the entries, for Tab to reach it
4836                // without going through them all.
4837                let at = ui.cursor().min;
4838                let rect = egui::Rect::from_min_size(
4839                    pos2(at.x + list_width, at.y),
4840                    vec2(gap, list_height),
4841                );
4842                let name = strings::tr(ui.ctx(), &txt::FILES_PREVIEW_RESIZE);
4843                let id = ui.scope_id().with("egui_pop.files.splitter");
4844                let max = room - gap - LIST_MIN_WIDTH;
4845                let r = widgets::Splitter::new(id, &name, PANE_MIN_WIDTH, max, preview::PANE_WIDTH)
4846                    .after()
4847                    .show(ui, rect, &mut width);
4848                if r.changed() {
4849                    self.pane_width = width;
4850                }
4851                self.pane_dragging = r.dragged();
4852            }
4853            ui.vertical(|ui| {
4854                ui.set_width(list_width);
4855                let spacing = ui.spacing().item_spacing.y;
4856                let row = browser::row_height(ui);
4857                let height = (list_height - row - spacing).max(0.0);
4858                // The scroll bar takes its room only when there is one.
4859                let scrolls = !grid && shown.len() as f32 * (row + spacing) > height;
4860                let bar = ui.spacing().scroll.allocated_width();
4861                let row_width = list_width - if scrolls { bar } else { 0.0 };
4862                let folders_only = shown.iter().all(|e| e.is_dir);
4863                let columns = browser::list_columns(ui, row_width, folders_only);
4864                self.entries_view(ui, shown, &columns, row_width, list_width, height, answer);
4865            });
4866            if let Some(pane_width) = pane_width {
4867                ui.add_space(t.space.m);
4868                ui.vertical(|ui| {
4869                    ui.set_width(pane_width);
4870                    // As high as the list, whatever the preview's facts.
4871                    ui.scroll_area(
4872                        egui::ScrollArea::vertical()
4873                            .id_salt("egui_pop.files.pane")
4874                            .max_height(list_height)
4875                            .auto_shrink([false, true]),
4876                        |ui| {
4877                            // Named, for a screen reader to find it.
4878                            let name = strings::tr(ui.ctx(), &txt::FILES_PREVIEW);
4879                            ui.scope_builder(
4880                                egui::UiBuilder::new()
4881                                    .accessibility_role(egui::accesskit::Role::Group)
4882                                    .accessibility_label(name),
4883                                |ui| self.preview_pane(ui),
4884                            );
4885                        },
4886                    );
4887                });
4888            }
4889        });
4890        // Out of the grid, the thumbnails it asked for are no longer wanted.
4891        if !grid
4892            && std::mem::take(&mut self.asked_thumbnails)
4893            && let Some(previews) = &self.previews
4894        {
4895            previews.want(ui.ctx(), &self.fs, &[]);
4896        }
4897        if toggle {
4898            self.toggle();
4899        }
4900        if select_all {
4901            // A refusal is the picker's error, shown below the list.
4902            let _ = self.select_all();
4903        }
4904        if enter && answer.is_none() {
4905            *answer = self.activate();
4906        }
4907        if accept && answer.is_none() {
4908            *answer = self.accept();
4909        }
4910    }
4911
4912    /// The picker's footer: an error, the selection's line, the choices,
4913    /// the filters, the toggles and the buttons.
4914    fn show_footer(&mut self, ui: &mut Ui, answer: &mut Option<PickerAnswer>) {
4915        let t = Tokens::of(ui.ctx());
4916        if let Some(e) = &self.error {
4917            ui.colored_label(t.status.danger, e);
4918        }
4919        // A folder shown anew is said, with how many entries it shows.
4920        if self.said_dir.as_ref() != Some(&self.dir) {
4921            if self.said_dir.is_some() {
4922                let said = strings::tr_with(
4923                    ui.ctx(),
4924                    &txt::FILES_FOLDER_OPENED,
4925                    &[
4926                        ("folder", Arg::Str(&folder_name(&self.dir))),
4927                        ("count", self.visible().len().into()),
4928                    ],
4929                );
4930                a11y::announce(ui.ctx(), said, Politeness::Polite);
4931            }
4932            self.said_dir = Some(self.dir.clone());
4933        }
4934        let primary = self.primary();
4935        let line = primary.readout.clone();
4936        if let Some(line) = &line {
4937            ui.label(egui::RichText::new(line).strong());
4938        }
4939        if self.said != line {
4940            // Not what it says on opening: that is no change.
4941            if let (Some(_), Some(line)) = (&self.said, &line) {
4942                a11y::announce(ui.ctx(), line, Politeness::Polite);
4943            }
4944            self.said = line;
4945        }
4946        if !self.choices.is_empty() {
4947            ui.add_space(t.space.s);
4948            self.choice_row(ui);
4949        }
4950        ui.add_space(t.space.m);
4951        ui.horizontal(|ui| {
4952            if !self.filters.is_empty() {
4953                let names: Vec<String> = self
4954                    .filters
4955                    .iter()
4956                    .map(|f| {
4957                        if f.extensions.is_empty() {
4958                            f.name.clone()
4959                        } else {
4960                            format!("{} (*.{})", f.name, f.extensions.join(", *."))
4961                        }
4962                    })
4963                    .chain([strings::tr(ui.ctx(), &txt::FILES_ALL)])
4964                    .collect();
4965                let mut at = self.filter_index.min(names.len() - 1);
4966                let combo =
4967                    widgets::combo_box("egui_pop.files.filter").selected_text(names[at].as_str());
4968                let list = ui.combo_box(combo, |ui| {
4969                    for (i, n) in names.iter().enumerate() {
4970                        widgets::selectable_value(ui, &mut at, i, n);
4971                    }
4972                });
4973                // No label beside it: a screen reader still needs its name.
4974                let name = strings::tr(ui.ctx(), &txt::FILES_TYPE);
4975                ui.ctx()
4976                    .accesskit_node_builder(list.response.id, |node| node.set_label(name));
4977                if at != self.filter_index {
4978                    self.set_filter(at);
4979                }
4980            }
4981            widgets::checkbox(
4982                ui,
4983                &mut self.show_hidden,
4984                strings::tr(ui.ctx(), &txt::FILES_HIDDEN),
4985            )
4986            .on_hover_text(keys_tip(&self.hidden_keys));
4987            let mut folders_first = self.folders_first;
4988            widgets::checkbox(
4989                ui,
4990                &mut folders_first,
4991                strings::tr(ui.ctx(), &txt::FILES_FOLDERS_FIRST),
4992            );
4993            self.set_folders_first(folders_first);
4994            if self.previews.is_some() {
4995                widgets::checkbox(
4996                    ui,
4997                    &mut self.show_preview,
4998                    strings::tr(ui.ctx(), &txt::FILES_PREVIEW),
4999                )
5000                .on_hover_text(keys_tip(&self.preview_keys));
5001            }
5002            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
5003                // The suggested action: the accent, a task for its label.
5004                let on = primary.off.is_none();
5005                let r = ui
5006                    .scoped(Stock::Button, Tone::Accent, |ui| {
5007                        ui.add_enabled(on, egui::Button::new(primary.label.as_str()))
5008                    })
5009                    .inner;
5010                let r = match &primary.off {
5011                    Some(why) => r.on_disabled_hover_text(why.as_str()),
5012                    None => r,
5013                };
5014                if r.clicked() {
5015                    *answer = answer.take().or_else(|| self.accept());
5016                }
5017                if ui.button(strings::tr(ui.ctx(), &CANCEL)).clicked() {
5018                    *answer = Some(PickerAnswer::Cancel);
5019                }
5020            });
5021        });
5022    }
5023}
5024
5025impl FilePicker {
5026    /// The list's empty state, in the list: a heading, why, and the way out
5027    /// (Clear filter, Show all files, Retry or Go up).
5028    fn empty_view(&mut self, ui: &mut Ui) {
5029        let t = Tokens::of(ui.ctx());
5030        let state = self.empty_state();
5031        let ctx = ui.ctx().clone();
5032        let tr = |key: &strings::StrKey| strings::tr(&ctx, key);
5033        ui.add_space(t.space.l);
5034        ui.vertical_centered(|ui| {
5035            let (heading, detail) = match &state {
5036                EmptyState::Empty => (tr(&txt::FILES_EMPTY_FOLDER), None),
5037                EmptyState::NoFolders => (tr(&txt::FILES_NO_SUBFOLDERS), None),
5038                EmptyState::NoResults(text) => (
5039                    tr(&txt::FILES_NO_RESULTS),
5040                    Some(strings::tr_args(
5041                        &ctx,
5042                        &txt::FILES_NO_RESULTS_FOR,
5043                        &[("text", text)],
5044                    )),
5045                ),
5046                EmptyState::NoneOfType(filter) => (
5047                    tr(&txt::FILES_NO_RESULTS),
5048                    Some(strings::tr_args(
5049                        &ctx,
5050                        &txt::FILES_NO_RESULTS_TYPE,
5051                        &[("filter", filter)],
5052                    )),
5053                ),
5054                EmptyState::Unreadable(reason) => {
5055                    (tr(&txt::FILES_UNREADABLE), Some(reason.clone()))
5056                }
5057            };
5058            ui.label(egui::RichText::new(heading).strong());
5059            if let Some(detail) = detail {
5060                ui.weak(detail);
5061            }
5062            ui.add_space(t.space.s);
5063            match &state {
5064                EmptyState::NoResults(_) => {
5065                    if ui.button(tr(&txt::FILES_CLEAR_FILTER)).clicked() {
5066                        self.text.clear();
5067                        self.text_changed();
5068                        self.refocus = true;
5069                    }
5070                }
5071                EmptyState::NoneOfType(_) => {
5072                    if ui.button(tr(&txt::FILES_SHOW_ALL)).clicked() {
5073                        self.set_filter(self.filters.len());
5074                    }
5075                }
5076                EmptyState::Unreadable(_) => {
5077                    ui.horizontal(|ui| {
5078                        if ui.button(tr(&txt::FILES_RETRY)).clicked() {
5079                            self.reload();
5080                        }
5081                        if self.dir.parent().is_some() && ui.button(tr(&txt::FILES_GO_UP)).clicked()
5082                        {
5083                            self.up();
5084                        }
5085                    });
5086                }
5087                EmptyState::Empty | EmptyState::NoFolders => {}
5088            }
5089        });
5090    }
5091
5092    /// Whether the entries are drawn as a grid: it needs the providers.
5093    fn grid_on(&self) -> bool {
5094        self.view == PickerView::Grid && self.previews.is_some()
5095    }
5096
5097    /// The columns are shown: choosing a folder, in that view.
5098    fn columns_on(&self) -> bool {
5099        self.view == PickerView::Columns && self.kind == ChooseKind::Folder
5100    }
5101
5102    /// How many thumbnails fill a row of the grid.
5103    pub fn zoom(&self) -> browser::ThumbZoom {
5104        self.zoom
5105    }
5106
5107    /// A new zoom for the grid; the highlighted cell stays in view.
5108    pub fn set_zoom(&mut self, zoom: browser::ThumbZoom) {
5109        self.zoom = zoom;
5110        self.reveal_cell = true;
5111    }
5112
5113    /// The zoom as the side its thumbnails are drawn at in `ui`'s room;
5114    /// a size asked in points since the last draw becomes the zoom.
5115    fn thumbnail_side(&mut self, ui: &Ui) -> f32 {
5116        let (width, gap) = egui_pop_core::thumbnail::ThumbnailGrid::room(ui);
5117        self.grid_room = (width, gap);
5118        if self.thumbnail_size != self.drawn_side {
5119            self.zoom = browser::ThumbZoom::Points(self.thumbnail_size);
5120        }
5121        self.zoom = self.zoom.under(self.resize, width, gap);
5122        self.thumbnail_size = self.zoom.side(width, gap);
5123        self.drawn_side = self.thumbnail_size;
5124        self.thumbnail_size
5125    }
5126
5127    /// The application's choices, on a line of their own above the buttons:
5128    /// a check box, or a label and its combo box.
5129    fn choice_row(&mut self, ui: &mut Ui) {
5130        let values = &mut self.choice_values;
5131        ui.horizontal_wrapped(|ui| {
5132            for c in &self.choices {
5133                let value = values
5134                    .entry(c.id.clone())
5135                    .or_insert_with(|| c.default.clone());
5136                if c.is_check() {
5137                    let mut on = value == "true";
5138                    if widgets::checkbox(ui, &mut on, c.label.as_str()).changed() {
5139                        *value = on.to_string();
5140                    }
5141                    continue;
5142                }
5143                ui.label(c.label.as_str());
5144                let shown = c
5145                    .options
5146                    .iter()
5147                    .find(|(id, _)| id == value)
5148                    .map_or(value.as_str(), |(_, label)| label.as_str())
5149                    .to_owned();
5150                let combo = widgets::combo_box(("egui_pop.files.choice", c.id.as_str()))
5151                    .selected_text(shown);
5152                let list = ui.combo_box(combo, |ui| {
5153                    for (id, label) in &c.options {
5154                        widgets::selectable_value(ui, value, id.clone(), label.as_str());
5155                    }
5156                });
5157                // The label beside it is not its name for a screen reader.
5158                let name = c.label.clone();
5159                ui.ctx()
5160                    .accesskit_node_builder(list.response.id, |node| node.set_label(name));
5161            }
5162        });
5163    }
5164
5165    /// A place of the side bar: a click opens its folder.
5166    fn place(&mut self, ui: &mut Ui, name: &str, dir: &Path) -> egui::Response {
5167        let r = widgets::selectable_label(ui, self.dir == dir, name)
5168            .on_hover_text(dir.display().to_string());
5169        if r.clicked() {
5170            self.go(dir.to_path_buf());
5171        }
5172        r
5173    }
5174
5175    /// The side bar: home, the system's folders, the volumes, recent places
5176    /// and bookmarks, each bookmark with a menu to rename, move or remove it.
5177    fn side_bar(&mut self, ui: &mut Ui, places: &Places) -> Option<PickerAnswer> {
5178        let t = Tokens::of(ui.ctx());
5179        let ctx = ui.ctx().clone();
5180        let mut out = None;
5181        if let Some(h) = &places.home {
5182            self.place(ui, &strings::tr(&ctx, &txt::FILES_HOME), h);
5183        }
5184        for (folder, dir) in &places.system.folders {
5185            self.place(ui, &strings::tr(&ctx, folder.title()), dir);
5186        }
5187        if !places.system.volumes.is_empty() {
5188            ui.add_space(t.space.s);
5189            ui.weak(strings::tr(&ctx, &txt::FILES_DEVICES));
5190            for v in &places.system.volumes {
5191                self.place(ui, &v.name, &v.path);
5192            }
5193        }
5194        if !places.recent.is_empty() {
5195            ui.add_space(t.space.s);
5196            ui.weak(strings::tr(&ctx, &txt::FILES_RECENT));
5197            for d in &places.recent {
5198                self.place(ui, &folder_name(d), d);
5199            }
5200        }
5201        if !places.bookmarks.is_empty() {
5202            out = self.bookmarks(ui, places);
5203        }
5204        // The application's sections: their folders.
5205        for section in &places.app_sections {
5206            let folders: Vec<_> = (section.items.iter())
5207                .filter_map(|i| i.path.as_ref().map(|p| (i, p)))
5208                .collect();
5209            if folders.is_empty() {
5210                continue;
5211            }
5212            ui.add_space(t.space.s);
5213            if !section.untitled {
5214                places::section_title(ui, &section.title);
5215            }
5216            for (item, path) in folders {
5217                let r = ui
5218                    .push_id((&section.id, &item.id), |ui| {
5219                        places::place_row(ui, item, self.dir == *path)
5220                    })
5221                    .inner;
5222                if r.clicked() {
5223                    self.go(path.clone());
5224                }
5225            }
5226        }
5227        out
5228    }
5229
5230    /// The bookmarks, each with a menu to rename, move or remove it.
5231    fn bookmarks(&mut self, ui: &mut Ui, places: &Places) -> Option<PickerAnswer> {
5232        let t = Tokens::of(ui.ctx());
5233        let ctx = ui.ctx().clone();
5234        let mut out = None;
5235        ui.add_space(t.space.s);
5236        ui.weak(strings::tr(&ctx, &txt::FILES_BOOKMARKS));
5237        let last = places.bookmarks.len() - 1;
5238        for (i, d) in places.bookmarks.iter().enumerate() {
5239            if self.renaming.as_ref().is_some_and(|(at, _)| at == d) {
5240                if let Some(a) = self.rename_field(ui, d) {
5241                    out = Some(a);
5242                }
5243                continue;
5244            }
5245            let name = places.bookmark_name(d);
5246            let r = self.place(ui, &name, d);
5247            egui_pop_core::pointer::claim::context_menu(&r, |ui| {
5248                if ui
5249                    .button(strings::tr(&ctx, &txt::FILES_RENAME_BOOKMARK))
5250                    .clicked()
5251                {
5252                    self.renaming = Some((d.clone(), name.clone()));
5253                    self.renaming_focus = true;
5254                    ui.close();
5255                }
5256                if i > 0 && ui.button(strings::tr(&ctx, &txt::FILES_MOVE_UP)).clicked() {
5257                    out = Some(PickerAnswer::MoveBookmark(d.clone(), i - 1));
5258                    ui.close();
5259                }
5260                if i < last
5261                    && ui
5262                        .button(strings::tr(&ctx, &txt::FILES_MOVE_DOWN))
5263                        .clicked()
5264                {
5265                    out = Some(PickerAnswer::MoveBookmark(d.clone(), i + 1));
5266                    ui.close();
5267                }
5268                if ui
5269                    .button(strings::tr(&ctx, &txt::FILES_UNBOOKMARK))
5270                    .clicked()
5271                {
5272                    out = Some(PickerAnswer::Bookmark(d.clone(), false));
5273                    ui.close();
5274                }
5275            });
5276        }
5277        out
5278    }
5279
5280    /// The field renaming a bookmark, in its place: Enter, or leaving it,
5281    /// keeps the name; Escape keeps the old one.
5282    fn rename_field(&mut self, ui: &mut Ui, dir: &Path) -> Option<PickerAnswer> {
5283        let ctx = ui.ctx().clone();
5284        let id = ui.make_persistent_id(("egui_pop.files.rename", dir));
5285        let label = strings::tr(&ctx, &txt::FILES_BOOKMARK_NAME);
5286        let escaped = focus::escape_left(&ctx, id)
5287            || (ui.memory(|m| m.has_focus(id))
5288                && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)));
5289        let (_, text) = self.renaming.as_mut()?;
5290        let edit = ui.add(
5291            egui::TextEdit::singleline(text)
5292                .id(id)
5293                .desired_width(f32::INFINITY),
5294        );
5295        egui_pop_core::a11y::name(&edit, egui::Role::TextInput, &label);
5296        if std::mem::take(&mut self.renaming_focus) {
5297            edit.request_focus();
5298            // Its text selected, to type the new name over it.
5299            let mut state = egui::text_edit::TextEditState::load(&ctx, id).unwrap_or_default();
5300            let all = egui::text::CCursorRange::two(
5301                egui::text::CCursor::new(0),
5302                egui::text::CCursor::new(text.chars().count()),
5303            );
5304            state.cursor.set_char_range(Some(all));
5305            state.store(&ctx, id);
5306            return None;
5307        }
5308        if escaped {
5309            self.renaming = None;
5310            return None;
5311        }
5312        if edit.lost_focus() {
5313            let (dir, name) = self.renaming.take()?;
5314            return Some(PickerAnswer::RenameBookmark(dir, name));
5315        }
5316        None
5317    }
5318
5319    /// The views it offers, in the switcher's order: details; thumbnails
5320    /// with previews; columns when choosing a folder.
5321    pub fn views(&self) -> Vec<PickerView> {
5322        PickerView::ALL
5323            .into_iter()
5324            .filter(|v| match v {
5325                PickerView::List => true,
5326                PickerView::Grid => self.previews.is_some(),
5327                PickerView::Columns => self.kind == ChooseKind::Folder,
5328            })
5329            .collect()
5330    }
5331
5332    /// The modes it offers, in the switcher's order ([`Self::views`]).
5333    fn mode_infos(&self) -> Vec<browser::ModeInfo> {
5334        let modes = browser::ViewModes::built_in();
5335        self.views()
5336            .iter()
5337            .filter_map(|v| modes.make(v.as_str()))
5338            .map(|m| m.describe())
5339            .collect()
5340    }
5341
5342    /// Shows the `n`-th mode (from 1, among [`Self::views`]), as `Ctrl+n`
5343    /// does; `false` without such a mode, or with one view alone.
5344    pub fn set_mode_index(&mut self, n: usize) -> bool {
5345        let views = self.views();
5346        let Some(view) = n.checked_sub(1).and_then(|i| views.get(i).copied()) else {
5347            return false;
5348        };
5349        if views.len() < 2 || self.view == view {
5350            return false;
5351        }
5352        self.view = view;
5353        self.reveal_cell = true;
5354        true
5355    }
5356
5357    /// The mode switcher, and the thumbnails' size with the thumbnails.
5358    fn view_controls(&mut self, ui: &mut Ui) {
5359        let id = ui.scope_id().with("egui_pop.files.modes");
5360        let modes = self.mode_infos();
5361        if let Some((mode, r)) = browser::mode_switcher(ui, id, &modes, self.view.as_str()) {
5362            if let Some(view) = PickerView::parse(&mode)
5363                && view != self.view
5364            {
5365                self.view = view;
5366                self.reveal_cell = true;
5367            }
5368            // A press leaves nothing focused: typing goes on filtering.
5369            self.refocus |= by_pointer(&r);
5370        }
5371        self.thumbnail_dragging = false;
5372        if self.view != PickerView::Grid {
5373            return;
5374        }
5375        let name = strings::tr(ui.ctx(), &txt::FILES_THUMBNAIL_SIZE);
5376        let height = ui.spacing().interact_size.y;
5377        ui.allocate_ui(vec2(THUMBNAIL_SLIDER_WIDTH, height), |ui| {
5378            let (width, gap) = self.grid_room;
5379            if self.resize == browser::GridResize::FixedSize {
5380                // The thumbnails' size in points, larger to the right.
5381                let least = f64::from(browser::ThumbnailsMode::MIN_SIZE);
5382                let mut value = match self.zoom.under(self.resize, width, gap) {
5383                    browser::ThumbZoom::Points(p) => f64::from(p),
5384                    zoom => f64::from(zoom.side(width, gap)),
5385                };
5386                let out = Slider::new(&mut value, &name, least..=f64::from(width).max(least))
5387                    .integer()
5388                    .step(1.0)
5389                    .show(ui);
5390                if out.response.changed() {
5391                    self.set_zoom(browser::ThumbZoom::Points(value.round() as f32));
5392                }
5393                self.thumbnail_dragging = out.response.dragged();
5394                return;
5395            }
5396            // Thumbnails per row, fewer (larger) to the right: the value
5397            // is the count negated, shown as the count.
5398            let most = f64::from(browser::ThumbZoom::most_per_row(width, gap));
5399            let mut value = -f64::from(self.zoom.shown_per_row(width, gap));
5400            let out = Slider::new(&mut value, &name, -most..=-1.0)
5401                .integer()
5402                .step(1.0)
5403                .display_scale(-1.0)
5404                .default(-f64::from(browser::ThumbZoom::DEFAULT_PER_ROW).max(-most))
5405                .show(ui);
5406            if out.response.changed() {
5407                self.set_zoom(browser::ThumbZoom::PerRow((-value).round().max(1.0) as u32));
5408            }
5409            self.thumbnail_dragging = out.response.dragged();
5410        });
5411    }
5412
5413    /// The switch that groups files or lets each be an entry of its own, the way
5414    /// to a member with the pointer. Only with a grouping to switch.
5415    fn group_control(&mut self, ui: &mut Ui) {
5416        let ctx = ui.ctx().clone();
5417        let name = strings::tr(&ctx, &txt::FILES_GROUP);
5418        let r = widgets::selectable_label(ui, self.grouped, name)
5419            .on_hover_text(strings::tr(&ctx, &txt::FILES_GROUP_TIP));
5420        if r.clicked() {
5421            self.set_grouped(!self.grouped);
5422            // A press leaves nothing focused: typing goes on filtering.
5423            self.refocus |= by_pointer(&r);
5424        }
5425    }
5426
5427    /// The keys that put a path into the field, read before anything is drawn:
5428    /// Ctrl+L, and `/` or `~` typed while an entry has the focus (by what they
5429    /// type: the keys making them differ from layout to layout).
5430    fn path_keys(&mut self, ui: &mut Ui) {
5431        if !self.declared_keys && ui.input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::L)) {
5432            self.edit_path();
5433        }
5434        if !ui
5435            .memory(|m| m.focused())
5436            .is_some_and(|f| self.row_ids.contains(&f))
5437        {
5438            return;
5439        }
5440        let typed = ui.input_mut(|i| {
5441            let at = i
5442                .events
5443                .iter()
5444                .position(|e| matches!(e, egui::Event::Text(t) if t == "/" || t == "~"))?;
5445            match i.events.remove(at) {
5446                egui::Event::Text(t) => Some(t),
5447                _ => None,
5448            }
5449        });
5450        if let Some(typed) = typed {
5451            self.start_path(&typed);
5452            ui.ctx().request_repaint();
5453        }
5454    }
5455
5456    /// The folder as breadcrumbs, in the room left in the row: each segment opens
5457    /// its folder, the chevron after it lists its subfolders. What does not fit
5458    /// is the start of the path, behind a button listing it; the deepest segment
5459    /// is cut only if it does not fit alone.
5460    fn breadcrumbs(&mut self, ui: &mut Ui) {
5461        let t = Tokens::of(ui.ctx());
5462        let ctx = ui.ctx().clone();
5463        let crumbs = crumbs_of(&self.dir);
5464        ui.spacing_mut().item_spacing.x = 0.0;
5465        let room = ui.available_width();
5466        let padding = 2.0 * ui.spacing().button_padding.x;
5467        let font = egui::TextStyle::Button.resolve(ui.style());
5468        let text_width = |text: &str| {
5469            ui.painter()
5470                .layout_no_wrap(text.to_string(), font.clone(), egui::Color32::PLACEHOLDER)
5471                .size()
5472                .x
5473        };
5474        let chevron = vec2(
5475            t.size.icon_inline + t.space.xs,
5476            ui.spacing().interact_size.y,
5477        );
5478        // Each as wide as it will be drawn, its chevron with it; the deepest is
5479        // strong.
5480        let name_widths: Vec<f32> = crumbs
5481            .iter()
5482            .enumerate()
5483            .map(|(n, c)| {
5484                let width = if n + 1 == crumbs.len() {
5485                    let strong = egui::RichText::new(&c.name).strong();
5486                    egui::WidgetText::from(strong)
5487                        .into_galley(
5488                            ui,
5489                            Some(egui::TextWrapMode::Extend),
5490                            f32::INFINITY,
5491                            font.clone(),
5492                        )
5493                        .size()
5494                        .x
5495                } else {
5496                    text_width(&c.name)
5497                };
5498                // Rounded up: a fraction over would push the row out.
5499                (width + padding).ceil()
5500            })
5501            .collect();
5502        let widths: Vec<f32> = name_widths.iter().map(|w| w + chevron.x).collect();
5503        let collapsed_width = (text_width("…") + padding).ceil();
5504        let first = first_crumb(&widths, room, collapsed_width);
5505        let mut chosen = None;
5506        if first > 0 {
5507            let name = strings::tr(&ctx, &txt::FILES_CRUMB_COLLAPSED);
5508            let r = ui
5509                .add(egui::Button::new("…").frame_when_inactive(false))
5510                .on_hover_text(&name);
5511            a11y::name(&r, egui::Role::Button, &name);
5512            let above: Vec<Crumb> = crumbs[..first].iter().rev().cloned().collect();
5513            chosen = self.crumb_menu(ui, &r, move |_| Some(above));
5514        }
5515        let left = if first > 0 {
5516            room - collapsed_width
5517        } else {
5518            room
5519        };
5520        for (n, crumb) in crumbs.iter().enumerate().skip(first) {
5521            let current = n + 1 == crumbs.len();
5522            let mut text = egui::RichText::new(&crumb.name);
5523            if current {
5524                text = text.strong();
5525            }
5526            let button = egui::Button::new(text).frame_when_inactive(false);
5527            let fits = (left - chevron.x).max(chevron.x);
5528            // By its path: the focus stays on it as the start collapses.
5529            let r = ui
5530                .push_id((&crumb.path, "open"), |ui| {
5531                    if current && name_widths[n] > fits {
5532                        ui.allocate_ui(vec2(fits, chevron.y), |ui| ui.add(button.truncate()))
5533                            .inner
5534                    } else {
5535                        ui.add(button)
5536                    }
5537                })
5538                .inner;
5539            let name = strings::tr_args(&ctx, &txt::FILES_CRUMB_OPEN, &[("name", &crumb.name)]);
5540            a11y::name(&r, egui::Role::Button, &name);
5541            if current {
5542                let shown = strings::tr(&ctx, &txt::FILES_CRUMB_CURRENT);
5543                ctx.accesskit_node_builder(r.id, |node| node.set_description(shown));
5544            }
5545            let r = r.on_hover_text(crumb.path.display().to_string());
5546            if r.clicked() {
5547                chosen = Some(crumb.path.clone());
5548            }
5549            let name =
5550                strings::tr_args(&ctx, &txt::FILES_CRUMB_SUBFOLDERS, &[("name", &crumb.name)]);
5551            let r = ui
5552                .push_id(&crumb.path, |ui| {
5553                    ui.add(
5554                        egui::Button::new("")
5555                            .min_size(chevron)
5556                            .frame_when_inactive(false),
5557                    )
5558                })
5559                .inner
5560                .on_hover_text(&name);
5561            a11y::name(&r, egui::Role::Button, &name);
5562            let dir = crumb.path.clone();
5563            let popup = egui::Popup::default_response_id(&r);
5564            let color = ui.style().interact(&r).text_color();
5565            let icon = if egui::Popup::is_id_open(&ctx, popup) {
5566                Icon::ChevronDown
5567            } else {
5568                Icon::ChevronRight
5569            };
5570            let side = t.size.icon_inline.min(r.rect.height());
5571            icon.paint(
5572                ui.painter(),
5573                egui::Rect::from_center_size(r.rect.center(), vec2(side, side)),
5574                color,
5575            );
5576            chosen = self
5577                .crumb_menu(ui, &r, move |picker| picker.subfolders(&dir))
5578                .or(chosen);
5579        }
5580        if let Some(dir) = chosen {
5581            // The folder shown, asked again: it is read again.
5582            if dir == self.dir
5583                && let Some(b) = lock(&self.lister).browser.as_mut()
5584            {
5585                b.reload();
5586            }
5587            self.go(dir);
5588            self.refocus = true;
5589            ctx.request_repaint();
5590        }
5591    }
5592
5593    /// A folder's subfolders by name, hidden ones only when the list shows them.
5594    /// None when it cannot be read.
5595    fn subfolders(&self, dir: &Path) -> Option<Vec<Crumb>> {
5596        let mut names: Vec<String> = self
5597            .fs
5598            .read_dir(dir)
5599            .ok()?
5600            .into_iter()
5601            .filter(|e| e.is_dir && (self.show_hidden || !e.name.starts_with('.')))
5602            .map(|e| e.name)
5603            .collect();
5604        names.sort_by(|a, b| sort::natural_cmp(a, b));
5605        Some(
5606            names
5607                .into_iter()
5608                .map(|name| Crumb {
5609                    path: dir.join(&name),
5610                    name,
5611                })
5612                .collect(),
5613        )
5614    }
5615
5616    /// A key the columns' mode reads as leaving the folder shown: into the
5617    /// highlighted folder (the selection left behind, so the folder entered
5618    /// is the choice), or back to the parent, the folder left selected.
5619    fn travel(&mut self, travel: browser::Travel) {
5620        match travel {
5621            browser::Travel::Into => {
5622                if let Some(e) = self.highlighted().filter(|e| e.is_dir) {
5623                    self.go(e.path);
5624                }
5625            }
5626            browser::Travel::Out => {
5627                if let Some(parent) = self.dir.parent().map(Path::to_path_buf) {
5628                    let left = self.dir.clone();
5629                    self.reach(parent, Some(left));
5630                }
5631            }
5632        }
5633    }
5634
5635    /// Shows `place`, `focus` highlighted and selected there: a click in
5636    /// another column than the folder shown's.
5637    fn reach(&mut self, place: PathBuf, focus: Option<PathBuf>) {
5638        self.go(place);
5639        self.reach_focus = focus;
5640        self.entries();
5641    }
5642
5643    /// The menu under a breadcrumb's `button`, listing what `read` gives as it
5644    /// opens: the folder chosen. By the keyboard it is walked with the arrows,
5645    /// Tab or Escape close it, and the focus goes back to the button; by the
5646    /// pointer, the focus goes back to the field, for typing to go on.
5647    fn crumb_menu(
5648        &mut self,
5649        ui: &Ui,
5650        button: &egui::Response,
5651        read: impl FnOnce(&Self) -> Option<Vec<Crumb>>,
5652    ) -> Option<PathBuf> {
5653        let ctx = ui.ctx().clone();
5654        let popup =
5655            egui::Popup::menu(button).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
5656        let id = popup.get_id();
5657        let was_open = egui::Popup::is_id_open(&ctx, id);
5658        if button.clicked() && !was_open {
5659            let items = read(self);
5660            self.crumb_menu_keys = !by_pointer(button);
5661            self.crumb_menu_focus = self.crumb_menu_keys;
5662            // Nothing to walk: what the menu says is read out.
5663            let empty = match &items {
5664                None => Some(&txt::FILES_CRUMB_UNREADABLE),
5665                Some(list) if list.is_empty() => Some(&txt::FILES_CRUMB_NONE),
5666                Some(_) => None,
5667            };
5668            if let Some(empty) = empty {
5669                a11y::announce(&ctx, strings::tr(&ctx, empty), Politeness::Polite);
5670            }
5671            self.crumb_menu = Some(Arc::new(items));
5672        }
5673        ctx.accesskit_node_builder(button.id, |node| {
5674            node.set_has_popup(egui::accesskit::HasPopup::Menu);
5675            node.set_expanded(was_open);
5676        });
5677        let items = self.crumb_menu.clone();
5678        let mut chosen = None;
5679        let mut leave = false;
5680        popup.show(|ui| {
5681            let Some(items) = items.as_deref() else {
5682                return;
5683            };
5684            let Some(list) = items.as_ref() else {
5685                ui.weak(strings::tr(ui.ctx(), &txt::FILES_CRUMB_UNREADABLE));
5686                return;
5687            };
5688            if list.is_empty() {
5689                ui.weak(strings::tr(ui.ctx(), &txt::FILES_CRUMB_NONE));
5690                return;
5691            }
5692            // As wide as its longest name, up to a limit: its items fill the menu.
5693            let font = egui::TextStyle::Button.resolve(ui.style());
5694            let widest = list.iter().fold(0.0_f32, |widest, item| {
5695                let name = item.name.clone();
5696                let galley =
5697                    ui.painter()
5698                        .layout_no_wrap(name, font.clone(), egui::Color32::PLACEHOLDER);
5699                widest.max(galley.size().x)
5700            });
5701            let room = widest
5702                + 2.0 * ui.spacing().button_padding.x
5703                + ui.spacing().scroll.allocated_width();
5704            ui.set_width(room.ceil().min(CRUMB_MENU_WIDTH));
5705            let on_path = list.iter().position(|c| self.dir.starts_with(&c.path));
5706            let mut ids = Vec::with_capacity(list.len());
5707            ui.scroll_area(
5708                egui::ScrollArea::vertical()
5709                    .id_salt("egui_pop.files.crumb_menu")
5710                    .max_height(CRUMB_MENU_HEIGHT),
5711                |ui| {
5712                    for (n, item) in list.iter().enumerate() {
5713                        let r = ui.add(
5714                            egui::Button::new(&item.name)
5715                                .selected(on_path == Some(n))
5716                                .truncate(),
5717                        );
5718                        a11y::name(&r, egui::Role::Button, &item.name);
5719                        if r.clicked() {
5720                            chosen = Some(item.path.clone());
5721                        }
5722                        ids.push(r.id);
5723                    }
5724                },
5725            );
5726            if chosen.is_some() {
5727                ui.close();
5728            }
5729            // The sizing pass draws nothing to focus.
5730            if self.crumb_menu_focus && !ui.is_sizing_pass() {
5731                self.crumb_menu_focus = false;
5732                ui.memory_mut(|m| m.request_focus(ids[on_path.unwrap_or(0)]));
5733                ui.ctx().request_repaint();
5734            }
5735            if let Some(at) = ui
5736                .memory(|m| m.focused())
5737                .and_then(|f| ids.iter().position(|i| *i == f))
5738            {
5739                // The arrows stay in the menu, and Tab does not walk on under it.
5740                ui.memory_mut(|m| {
5741                    m.set_focus_lock_filter(
5742                        ids[at],
5743                        EventFilter {
5744                            tab: true,
5745                            vertical_arrows: true,
5746                            ..Default::default()
5747                        },
5748                    )
5749                });
5750                let (down, up, tab) = ui.input_mut(|i| {
5751                    (
5752                        i.consume_key(Modifiers::NONE, Key::ArrowDown),
5753                        i.consume_key(Modifiers::NONE, Key::ArrowUp),
5754                        i.consume_key(Modifiers::SHIFT, Key::Tab)
5755                            || i.consume_key(Modifiers::NONE, Key::Tab),
5756                    )
5757                });
5758                let to = if down {
5759                    Some((at + 1) % ids.len())
5760                } else if up {
5761                    Some((at + ids.len() - 1) % ids.len())
5762                } else {
5763                    None
5764                };
5765                if let Some(to) = to {
5766                    ui.memory_mut(|m| m.request_focus(ids[to]));
5767                    ui.ctx().request_repaint();
5768                }
5769                if tab {
5770                    leave = true;
5771                    ui.close();
5772                }
5773            }
5774        });
5775        // On the bus (ADR 0029): opened, closed and how.
5776        egui_pop_core::overlay::follow_popup(
5777            &ctx,
5778            id,
5779            "folder menu",
5780            egui::Popup::is_id_open(&ctx, id),
5781            None,
5782        );
5783        if was_open && !egui::Popup::is_id_open(&ctx, id) {
5784            self.crumb_menu = None;
5785            if chosen.is_none() {
5786                if self.crumb_menu_keys || leave {
5787                    button.request_focus();
5788                } else {
5789                    self.refocus = true;
5790                }
5791                ctx.request_repaint();
5792            }
5793        }
5794        chosen
5795    }
5796
5797    /// The entries, drawn by the mode shown (`details`, `thumbnails` or
5798    /// `columns`) with the file browser's own rows and cells
5799    /// ([`browser::PlainDrawer`]): the picker adds its column headers, the
5800    /// highlight its field drives, its groups' badges and its own rules on a
5801    /// click, a rubber band choosing several files.
5802    #[allow(
5803        clippy::too_many_arguments,
5804        reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
5805    )]
5806    fn entries_view(
5807        &mut self,
5808        ui: &mut Ui,
5809        shown: Vec<Entry>,
5810        columns: &[browser::ListColumn],
5811        row_width: f32,
5812        list_width: f32,
5813        height: f32,
5814        answer: &mut Option<PickerAnswer>,
5815    ) {
5816        let grid = self.grid_on();
5817        if grid {
5818            // `Ctrl` and the wheel over the grid change the thumbnails' size.
5819            let area =
5820                egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), height));
5821            if ui.rect_contains_pointer(area) {
5822                let zoom = ui.input(|i| i.zoom_delta());
5823                if (zoom - 1.0).abs() > f32::EPSILON {
5824                    // Gathered until it makes a step: a pinch's small
5825                    // deltas zoom too.
5826                    self.wheel_zoom *= zoom;
5827                    let (width, gap) = self.grid_room;
5828                    if self.wheel_zoom >= THUMBNAIL_STEP - 1e-3 {
5829                        self.set_zoom(self.zoom.zoomed_in(width, gap).under(
5830                            self.resize,
5831                            width,
5832                            gap,
5833                        ));
5834                        self.wheel_zoom = 1.0;
5835                    } else if self.wheel_zoom <= 1.0 / THUMBNAIL_STEP + 1e-3 {
5836                        self.set_zoom(self.zoom.zoomed_out(width, gap).under(
5837                            self.resize,
5838                            width,
5839                            gap,
5840                        ));
5841                        self.wheel_zoom = 1.0;
5842                    }
5843                }
5844            }
5845        }
5846        let reveal = std::mem::take(&mut self.reveal_cell) && !shown.is_empty();
5847        let highlight = self.highlight.min(shown.len().saturating_sub(1));
5848        // The browser's entries, with their facts, in the order shown.
5849        let (entries, groups, absorbed, mut selection) = match lock(&self.lister).browser.as_ref() {
5850            Some(b) => (
5851                b.entries().to_vec(),
5852                b.groups(),
5853                b.absorbed().clone(),
5854                b.selection().clone(),
5855            ),
5856            None => Default::default(),
5857        };
5858        // Where a selection exists apart from the highlight, a ring says
5859        // where the highlight is; otherwise the highlight is the selection.
5860        let apart = self.selects_apart();
5861        if !apart && let Some(e) = shown.get(highlight) {
5862            selection.paths.insert(e.path.clone());
5863        }
5864        let mut settings = browser::ModeSettings {
5865            thumbnail_size: if grid {
5866                self.thumbnail_side(ui)
5867            } else {
5868                self.thumbnail_size
5869            },
5870            ..browser::ModeSettings::default()
5871        };
5872        let name = strings::tr_args(
5873            ui.ctx(),
5874            &txt::FILES_ENTRIES_OF,
5875            &[("folder", &folder_name(&self.dir))],
5876        );
5877        let many = self.kind == ChooseKind::OpenMany;
5878        self.row_ids.clear();
5879        // A group's entry carries its members' badges, and stands in with a
5880        // member's thumbnail.
5881        let ctx = ui.ctx().clone();
5882        let marked = groups.clone();
5883        let marks = move |e: &browser::SourceEntry| browser::EntryMarks {
5884            chips: marked
5885                .get(&e.path)
5886                .map(|g| browser::group_chips(&ctx, g))
5887                .unwrap_or_default(),
5888            ..browser::EntryMarks::default()
5889        };
5890        let mut details = std::mem::take(&mut self.details);
5891        let mut thumbs = std::mem::take(&mut self.thumbs);
5892        let mut cols = std::mem::take(&mut self.cols);
5893        let place = self.dir.clone();
5894        let columns_on = self.columns_on();
5895        // The columns beside the folder shown list off the interface
5896        // thread: their entries stream in, a busy row while they do.
5897        let column_cache = self.column_cache.clone();
5898        let mut side = lock(&column_cache);
5899        if columns_on {
5900            let mut wanted: Vec<PathBuf> = self
5901                .dir
5902                .ancestors()
5903                .skip(1)
5904                .map(Path::to_path_buf)
5905                .collect();
5906            wanted.reverse();
5907            let peek = entries
5908                .get(highlight)
5909                .filter(|e| e.is_dir())
5910                .map(|e| e.path.clone());
5911            let source = browser::FsSource::new(self.fs.clone());
5912            let options = browser::ListOptions {
5913                hidden: self.show_hidden,
5914            };
5915            if side.sync(&source, &options, &wanted, &self.dir, peek.as_deref()) {
5916                ui.ctx().request_repaint();
5917            }
5918        } else {
5919            side.clear();
5920        }
5921        let (ancestors, peek) = if columns_on {
5922            (side.ancestors(), side.peek())
5923        } else {
5924            (&[][..], None)
5925        };
5926        let thumbnails = self.thumbnails.as_ref().map(|t| t.0.clone());
5927        let no_thumbnails = browser::NoThumbnails;
5928        let inner: &dyn browser::ThumbnailProvider = match &thumbnails {
5929            Some(t) => t.as_ref(),
5930            None => &no_thumbnails,
5931        };
5932        let grouped = browser::GroupThumbnails {
5933            inner,
5934            groups: &groups,
5935            absorbed: &absorbed,
5936        };
5937        let id = ui.scope_id().with("egui_pop.files.entries");
5938        let mut drawer = PickerDrawer {
5939            plain: browser::PlainDrawer {
5940                entries: &entries,
5941                selection: &selection,
5942                focus: (apart && !entries.is_empty()).then_some(highlight),
5943                marks: Some(&marks),
5944            },
5945            modifiers: ui.input(|i| i.modifiers),
5946            pointer: ui.input(|i| i.pointer.any_down() || i.pointer.any_released()),
5947            picker: self,
5948            shown,
5949            columns,
5950            row_width,
5951            list_width,
5952            answer,
5953        };
5954        let cx = browser::ModeContext {
5955            entries: &entries,
5956            selection: &selection,
5957            focus: (!entries.is_empty()).then_some(highlight),
5958            thumbnails: &grouped,
5959            settings: &mut settings,
5960            id,
5961            reveal_focus: reveal,
5962            max_height: Some(height),
5963            drawer: Some(&mut drawer),
5964            name: Some(name),
5965            many,
5966            place: &place,
5967            ancestors,
5968            peek,
5969            loading: false,
5970            generation: 0,
5971            marks: None,
5972        };
5973        if grid {
5974            grouped.begin_frame(ui.ctx());
5975        }
5976        let out = if columns_on {
5977            cols.show(ui, cx)
5978        } else if grid {
5979            thumbs.show(ui, cx)
5980        } else {
5981            details.show(ui, cx)
5982        };
5983        if grid {
5984            grouped.end_frame(ui.ctx());
5985        }
5986        drop(side);
5987        self.details = details;
5988        self.thumbs = thumbs;
5989        self.cols = cols;
5990        self.columns = out.columns;
5991        if let Some(r) = out.reach {
5992            self.reach(r.place, r.focus);
5993            self.refocus = true;
5994            ui.ctx().request_repaint();
5995        }
5996        // A rubber band selects the files it touches as it is drawn.
5997        if let Some(band) = browser::take_band(ui.ctx(), id) {
5998            self.apply_band(&band);
5999        }
6000        self.asked_thumbnails = grid;
6001    }
6002
6003    /// Selects the files a rubber band touches (choosing several): alone, or
6004    /// added to the selection it started from with Ctrl or Shift held. The
6005    /// highlight goes to its last entry once it is let go.
6006    fn apply_band(&mut self, band: &Band) {
6007        // The browser's policy: files alone, several at once; one entry at a
6008        // time, a band selects nothing.
6009        if self.kind == ChooseKind::OpenMany {
6010            self.error = None;
6011        }
6012        self.on_browser(|b| b.apply_band(band));
6013    }
6014
6015    /// What the row just drawn does with the pointer and the keys.
6016    #[allow(
6017        clippy::too_many_arguments,
6018        reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
6019    )]
6020    fn row_input(
6021        &mut self,
6022        _ui: &mut Ui,
6023        r: &egui::Response,
6024        n: usize,
6025        shown: &[Entry],
6026        modifiers: Modifiers,
6027        pointer: bool,
6028        answer: &mut Option<PickerAnswer>,
6029    ) {
6030        self.row_ids.push(r.id);
6031        // Tab through the rows moves the highlight too.
6032        if r.gained_focus() && !pointer {
6033            self.move_highlight(n, shown, false);
6034            r.scroll_to_me(None);
6035        }
6036        self.entry_clicks(r, n, shown, modifiers, pointer, answer);
6037    }
6038
6039    /// What the cell just drawn does with the pointer and the keys.
6040    #[allow(
6041        clippy::too_many_arguments,
6042        reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
6043    )]
6044    fn cell_input(
6045        &mut self,
6046        ui: &mut Ui,
6047        r: &egui::Response,
6048        n: usize,
6049        shown: &[Entry],
6050        modifiers: Modifiers,
6051        pointer: bool,
6052        answer: &mut Option<PickerAnswer>,
6053    ) {
6054        self.row_ids.push(r.id);
6055        // The grid's own arrows, not egui's moves from widget to widget.
6056        if r.has_focus() {
6057            ui.memory_mut(|m| {
6058                m.set_focus_lock_filter(
6059                    r.id,
6060                    EventFilter {
6061                        horizontal_arrows: true,
6062                        vertical_arrows: true,
6063                        ..Default::default()
6064                    },
6065                )
6066            });
6067        }
6068        // Tab through the cells moves the highlight too.
6069        if r.gained_focus() && !pointer && n != self.highlight {
6070            self.move_highlight(n, shown, false);
6071            r.scroll_to_me(None);
6072        }
6073        if self.focus_cell && n == self.highlight {
6074            self.focus_cell = false;
6075            r.request_focus();
6076        }
6077        self.entry_clicks(r, n, shown, modifiers, pointer, answer);
6078        // A filter holds text: the arrows must reach the grid, so the cell
6079        // keeps the focus. Saving, the field holds the name just taken.
6080        if r.clicked() && self.kind != ChooseKind::Save && !self.text.is_empty() {
6081            self.refocus = false;
6082            r.request_focus();
6083        }
6084    }
6085
6086    /// What a click does on an entry, the same in the list and the grid. It
6087    /// selects; a double click opens.
6088    fn entry_clicks(
6089        &mut self,
6090        r: &egui::Response,
6091        n: usize,
6092        shown: &[Entry],
6093        modifiers: Modifiers,
6094        pointer: bool,
6095        answer: &mut Option<PickerAnswer>,
6096    ) {
6097        if r.double_clicked() && !modifiers.command && !modifiers.shift {
6098            self.click_entry(n, shown, Modifiers::NONE);
6099            *answer = answer.take().or_else(|| self.activate());
6100        } else if r.clicked() {
6101            self.click_entry(n, shown, modifiers);
6102            // By the pointer: the keys go on as before.
6103            self.refocus |= pointer;
6104        }
6105    }
6106
6107    /// The New folder button: disabled, with the reason, on a file system
6108    /// that cannot make one (the key says the same in the picker).
6109    fn new_folder_button(&mut self, ui: &mut Ui) {
6110        let ctx = ui.ctx().clone();
6111        let can = self.fs.can_create_dirs();
6112        let button = egui::Button::new(strings::tr(&ctx, &txt::FILES_NEW_FOLDER));
6113        let r = ui.add_enabled(can, button);
6114        let r = if can {
6115            match self.new_folder_keys.first() {
6116                Some(keys) => r.on_hover_text(keys),
6117                None => r,
6118            }
6119        } else {
6120            r.on_disabled_hover_text(strings::tr(&ctx, &txt::FILES_FOLDER_READ_ONLY))
6121        };
6122        if r.clicked() {
6123            // A refusal is the picker's error, shown below the list.
6124            let _ = self.begin_new_folder();
6125        }
6126    }
6127
6128    /// The row asking a new folder's name. Says whether the focus goes
6129    /// back to the picker's field: the row closed.
6130    fn naming_row(&mut self, ui: &mut Ui, answer: &mut Option<PickerAnswer>) -> bool {
6131        let ctx = ui.ctx().clone();
6132        let id = ui.scope_id().with("egui_pop.files.new_folder");
6133        // Escape takes the focus from a field before anything else sees
6134        // it; from the row's buttons, it comes this way.
6135        let mut close = focus::escape_left(&ctx, id)
6136            || ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
6137        let focused = ui.memory(|m| m.has_focus(id));
6138        let mut create = focused && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter));
6139        let mut name = self.naming.take().unwrap_or_default();
6140        let label = strings::tr(&ctx, &txt::FILES_FOLDER_NAME);
6141        ui.horizontal(|ui| {
6142            ui.label(&label);
6143            let edit = ui.add(
6144                egui::TextEdit::singleline(&mut name)
6145                    .id(id)
6146                    .desired_width(ui.available_width() / 2.0),
6147            );
6148            egui_pop_core::a11y::name(&edit, egui::Role::TextInput, &label);
6149            if std::mem::take(&mut self.naming_focus) {
6150                edit.request_focus();
6151            }
6152            if edit.changed() {
6153                self.error = None;
6154            }
6155            create |= ui.button(strings::tr(&ctx, &txt::FILES_CREATE)).clicked();
6156            close |= ui.button(strings::tr(&ctx, &CANCEL)).clicked();
6157        });
6158        if close {
6159            self.error = None;
6160            return true;
6161        }
6162        self.naming = Some(name.clone());
6163        if !create {
6164            return false;
6165        }
6166        match self.create_folder(&name) {
6167            Ok(path) => {
6168                *answer = Some(PickerAnswer::FolderCreated(path));
6169                true
6170            }
6171            Err(_) => {
6172                // The reason shows below the list; the name stays to fix.
6173                self.naming_focus = true;
6174                ctx.request_repaint();
6175                false
6176            }
6177        }
6178    }
6179
6180    /// The pane beside the list: the highlighted entry's preview, asked
6181    /// of the providers (the one asked before is cancelled).
6182    fn preview_pane(&mut self, ui: &mut Ui) {
6183        let Some(previews) = self.previews.clone() else {
6184            return;
6185        };
6186        match self.highlighted() {
6187            Some(e) => {
6188                let ctx = ui.ctx().clone();
6189                let (shown, stand_in) =
6190                    self.preview_of(&e, |path| previews.get(&ctx, &self.fs, path));
6191                let meta = self.fs.metadata(&e.path).ok();
6192                let stand_in = stand_in
6193                    .as_ref()
6194                    .and_then(|p| p.file_name())
6195                    .map(|n| n.to_string_lossy());
6196                preview::pane_for(ui, &e.name, meta.as_ref(), &shown, stand_in.as_deref());
6197                if let Some(group) = self.group_of(&e.path) {
6198                    let t = Tokens::of(&ctx);
6199                    ui.add_space(t.space.s);
6200                    ui.weak(strings::tr(&ctx, &txt::FILES_GROUP_MEMBERS));
6201                    for name in group.member_names() {
6202                        ui.add(egui::Label::new(name).truncate());
6203                    }
6204                }
6205            }
6206            None => {
6207                ui.weak(strings::tr(ui.ctx(), &txt::FILES_PREVIEW_NONE));
6208            }
6209        }
6210    }
6211}
6212
6213/// The picker's [`browser::EntryDrawer`]: the browser's own rows and cells
6214/// ([`browser::PlainDrawer`]), with the picker's column headers that sort and
6215/// its own rules on a click, on Tab and on the keys.
6216struct PickerDrawer<'a> {
6217    plain: browser::PlainDrawer<'a>,
6218    picker: &'a mut FilePicker,
6219    shown: Vec<Entry>,
6220    columns: &'a [browser::ListColumn],
6221    /// The rows' width: the list's, less the scroll bar's when it scrolls.
6222    row_width: f32,
6223    list_width: f32,
6224    modifiers: Modifiers,
6225    pointer: bool,
6226    answer: &'a mut Option<PickerAnswer>,
6227}
6228
6229impl browser::EntryDrawer for PickerDrawer<'_> {
6230    fn headers(&mut self, ui: &mut Ui, _width: f32) {
6231        let ranks = self.picker.ranks();
6232        let clicked =
6233            browser::sort_headers(ui, self.columns, self.list_width, self.picker.sort, ranks);
6234        if let Some(sort) = clicked {
6235            self.picker.set_sort(sort);
6236            // By the pointer: the keys go on as before.
6237            self.picker.refocus |= self.pointer;
6238            ui.ctx().request_repaint();
6239        }
6240    }
6241
6242    fn empty(&mut self, ui: &mut Ui) {
6243        self.picker.empty_view(ui);
6244    }
6245
6246    fn row_size(&self, ui: &Ui, width: f32) -> egui::Vec2 {
6247        // A column of Finder's view keeps its own width.
6248        let width = if self.picker.columns_on() {
6249            width
6250        } else {
6251            self.row_width
6252        };
6253        self.plain.row_size(ui, width)
6254    }
6255
6256    fn row(&mut self, ui: &mut Ui, n: usize, size: egui::Vec2) -> egui::Response {
6257        let r = self.plain.row(ui, n, size);
6258        self.picker.row_input(
6259            ui,
6260            &r,
6261            n,
6262            &self.shown,
6263            self.modifiers,
6264            self.pointer,
6265            self.answer,
6266        );
6267        r
6268    }
6269
6270    fn cell_size(&self, ui: &Ui, side: f32) -> egui::Vec2 {
6271        self.plain.cell_size(ui, side)
6272    }
6273
6274    fn cell(
6275        &mut self,
6276        ui: &mut Ui,
6277        n: usize,
6278        size: egui::Vec2,
6279        thumbnail: browser::ThumbState,
6280    ) -> egui::Response {
6281        let r = self.plain.cell(ui, n, size, thumbnail);
6282        self.picker.cell_input(
6283            ui,
6284            &r,
6285            n,
6286            &self.shown,
6287            self.modifiers,
6288            self.pointer,
6289            self.answer,
6290        );
6291        r
6292    }
6293}
6294
6295/// The system's chooser, awaited on a thread of its own.
6296mod native {
6297    use std::path::PathBuf;
6298    use std::sync::{Arc, Mutex};
6299
6300    use super::{Answer, FileRequest};
6301
6302    #[cfg(all(feature = "native-dialogs", not(target_arch = "wasm32")))]
6303    pub(super) fn start(
6304        ctx: &egui::Context,
6305        request: &FileRequest,
6306        start: Option<PathBuf>,
6307        parent: Option<egui::ViewportId>,
6308        answer: Arc<Mutex<Option<Answer>>>,
6309    ) {
6310        use std::future::Future;
6311        use std::pin::Pin;
6312
6313        use super::ChooseKind;
6314
6315        let mut d = rfd::AsyncFileDialog::new().set_title(&request.title);
6316        // Attached to the window it was asked from: rfd reads the handles
6317        // here, on the interface thread, while the window is there.
6318        if let Some(window) = parent.and_then(|v| super::PARENT_WINDOW.keyed(v).get(ctx)) {
6319            d = d.set_parent(&*window.0);
6320        }
6321        if let Some(dir) = start {
6322            d = d.set_directory(dir);
6323        }
6324        if let Some(name) = &request.file_name {
6325            d = d.set_file_name(name);
6326        }
6327        for f in &request.filters {
6328            d = d.add_filter(&f.name, &f.extensions);
6329        }
6330        // Made here, on the interface thread (macOS wants its panels made
6331        // on the main thread); awaited elsewhere.
6332        type Fut = Pin<Box<dyn Future<Output = Answer> + Send>>;
6333        let one = |p: Option<rfd::FileHandle>| p.map(|h| vec![h.path().to_path_buf()]);
6334        let fut: Fut = match request.kind {
6335            ChooseKind::Open => {
6336                let f = d.pick_file();
6337                Box::pin(async move { one(f.await) })
6338            }
6339            ChooseKind::OpenMany => {
6340                let f = d.pick_files();
6341                Box::pin(async move {
6342                    f.await
6343                        .map(|v| v.iter().map(|h| h.path().to_path_buf()).collect())
6344                })
6345            }
6346            ChooseKind::Save => {
6347                let f = d.save_file();
6348                Box::pin(async move { one(f.await) })
6349            }
6350            ChooseKind::Folder => {
6351                let f = d.pick_folder();
6352                Box::pin(async move { one(f.await) })
6353            }
6354        };
6355        let ctx = ctx.clone();
6356        let spawned = std::thread::Builder::new()
6357            .name("egui-pop-file-chooser".into())
6358            .spawn(move || {
6359                let r = block_on(fut);
6360                *egui_pop_core::lock(&answer) = Some(r);
6361                ctx.request_repaint();
6362            });
6363        if let Err(e) = spawned {
6364            log::warn!(target: "egui_pop", "files: no thread for the chooser: {e}");
6365        }
6366    }
6367
6368    #[cfg(not(all(feature = "native-dialogs", not(target_arch = "wasm32"))))]
6369    pub(super) fn start(
6370        _ctx: &egui::Context,
6371        _request: &FileRequest,
6372        _start: Option<PathBuf>,
6373        _parent: Option<egui::ViewportId>,
6374        answer: Arc<Mutex<Option<Answer>>>,
6375    ) {
6376        // Never reached: `native_available` is false without the feature.
6377        *egui_pop_core::lock(&answer) = Some(None);
6378    }
6379
6380    /// Runs a future to its end on this thread.
6381    #[cfg(all(feature = "native-dialogs", not(target_arch = "wasm32")))]
6382    fn block_on<F: std::future::Future>(f: F) -> F::Output {
6383        use std::task::{Context, Poll, Wake, Waker};
6384
6385        struct Unpark(std::thread::Thread);
6386        impl Wake for Unpark {
6387            fn wake(self: Arc<Self>) {
6388                self.0.unpark();
6389            }
6390        }
6391        let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
6392        let mut cx = Context::from_waker(&waker);
6393        let mut f = std::pin::pin!(f);
6394        loop {
6395            if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
6396                return v;
6397            }
6398            std::thread::park();
6399        }
6400    }
6401}
6402
6403#[cfg(test)]
6404mod tests {
6405    use super::browser::fit_columns;
6406    use super::*;
6407
6408    /// The names a picker shows once its folder is listed: the system's file
6409    /// system lists off the thread, its entries coming in over the next looks.
6410    fn listed(p: &mut FilePicker) -> Vec<String> {
6411        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
6412        loop {
6413            let names: Vec<String> = p.visible().into_iter().map(|e| e.name).collect();
6414            if !p.loading() {
6415                return names;
6416            }
6417            assert!(std::time::Instant::now() < deadline, "still listing");
6418            std::thread::yield_now();
6419        }
6420    }
6421
6422    fn tree(name: &str) -> PathBuf {
6423        let root =
6424            std::env::temp_dir().join(format!("egui-pop-files-unit-{name}-{}", std::process::id()));
6425        let _ = std::fs::remove_dir_all(&root);
6426        for d in ["photos/2026", "photos/2025", "notes", ".hidden"] {
6427            std::fs::create_dir_all(root.join(d)).unwrap();
6428        }
6429        for f in [
6430            "photos/a.png",
6431            "photos/b.jpg",
6432            "photos/readme.txt",
6433            "notes/todo.md",
6434        ] {
6435            std::fs::write(root.join(f), b"x").unwrap();
6436        }
6437        root
6438    }
6439
6440    #[test]
6441    fn breadcrumbs_read_from_the_root_without_dots() {
6442        let names = |path: &str| -> Vec<String> {
6443            crumbs_of(Path::new(path))
6444                .into_iter()
6445                .map(|c| c.name)
6446                .collect()
6447        };
6448        // A root without a drive reads `/` on every system.
6449        let root = "/";
6450        assert_eq!(names("/home/me/photos"), [root, "home", "me", "photos"]);
6451        assert_eq!(names("/"), [root]);
6452        assert_eq!(names("/home/me/../you/./a/"), [root, "home", "you", "a"]);
6453        assert_eq!(names("/../a"), [root, "a"]);
6454        #[cfg(windows)]
6455        {
6456            assert_eq!(names(r"C:\Users\me"), [r"C:\", "Users", "me"]);
6457            assert_eq!(names(r"\\?\C:\Users"), [r"C:\", "Users"]);
6458            assert_eq!(names(r"\\?\UNC\nas\photos\2026"), [r"\\nas\photos", "2026"]);
6459        }
6460        let crumbs = crumbs_of(Path::new("/home/me"));
6461        assert_eq!(crumbs[1].path, Path::new("/home"));
6462        assert_eq!(without_dots(Path::new("../a/./b/..")), Path::new("../a"));
6463    }
6464
6465    #[test]
6466    fn a_path_without_a_drive_reads_the_same_on_every_system() {
6467        let p = Path::new("/demo").join("Photos").join("2026");
6468        assert_eq!(path_text(&p), "/demo/Photos/2026");
6469        assert_eq!(path_text(Path::new("/")), "/");
6470        #[cfg(windows)]
6471        assert_eq!(path_text(Path::new(r"C:\Users\me")), r"C:\Users\me");
6472    }
6473
6474    #[test]
6475    fn the_start_of_a_path_collapses_and_the_deepest_stays() {
6476        let widths = [10.0, 20.0, 30.0, 40.0];
6477        // All of them fit: no button for the others.
6478        assert_eq!(first_crumb(&widths, 100.0, 5.0), 0);
6479        // The button takes its room from what is left.
6480        assert_eq!(first_crumb(&widths, 99.0, 5.0), 1);
6481        assert_eq!(first_crumb(&widths, 75.0, 5.0), 2);
6482        assert_eq!(first_crumb(&widths, 74.0, 5.0), 3);
6483        // Too narrow even for the deepest: it stays, and is cut.
6484        assert_eq!(first_crumb(&widths, 10.0, 5.0), 3);
6485        assert_eq!(first_crumb(&[50.0], 10.0, 5.0), 0);
6486    }
6487
6488    #[test]
6489    fn the_columns_give_way_to_the_name_the_type_first() {
6490        let wanted = [
6491            (SortColumn::Modified, 150.0),
6492            (SortColumn::Size, 60.0),
6493            (SortColumn::Type, 50.0),
6494        ];
6495        let fit = |room| {
6496            fit_columns(room, 10.0, 4.0, &wanted)
6497                .iter()
6498                .map(|c| c.column)
6499                .collect::<Vec<_>>()
6500        };
6501        use SortColumn::*;
6502        let all = 8.0 + NAME_MIN_WIDTH + 150.0 + 60.0 + 50.0 + 30.0;
6503        assert_eq!(fit(all), [Name, Modified, Size, Type]);
6504        assert_eq!(fit(all - 1.0), [Name, Modified, Size]);
6505        assert_eq!(fit(all - 61.0), [Name, Modified]);
6506        assert_eq!(fit(all - 131.0), [Name]);
6507        // Too narrow even for the name: it is cut, and nothing goes negative.
6508        assert_eq!(fit_columns(4.0, 10.0, 4.0, &wanted)[0].width, 0.0);
6509        // Each starts where the one before ends, and the name takes what is left.
6510        let columns = fit_columns(all + 40.0, 10.0, 4.0, &wanted);
6511        assert_eq!(columns[0].left, 4.0);
6512        assert_eq!(columns[0].width, NAME_MIN_WIDTH + 40.0);
6513        assert_eq!(columns[1].left, 4.0 + NAME_MIN_WIDTH + 40.0 + 10.0);
6514        assert_eq!(columns[2].left, columns[1].left + 160.0);
6515    }
6516
6517    #[test]
6518    fn the_preview_pane_takes_the_list_s_width_and_shrinks_first() {
6519        // Off: all the room is the list's.
6520        let wanted = preview::PANE_WIDTH;
6521        assert_eq!(split_list(700.0, 8.0, false, wanted), (700.0, None));
6522        // Room for both: the full pane, from the list's width.
6523        let (list, pane) = split_list(700.0, 8.0, true, wanted);
6524        assert_eq!(pane, Some(preview::PANE_WIDTH));
6525        assert_eq!(list, 700.0 - 8.0 - preview::PANE_WIDTH);
6526        // Less room: the pane shrinks, the list keeps its minimum.
6527        let (list, pane) = split_list(LIST_MIN_WIDTH + 8.0 + 150.0, 8.0, true, wanted);
6528        assert_eq!((list, pane), (LIST_MIN_WIDTH, Some(150.0)));
6529        // Too little: no pane at all.
6530        assert_eq!(split_list(300.0, 8.0, true, wanted), (300.0, None));
6531        // The width the person gave, within the limits.
6532        let (list, pane) = split_list(700.0, 8.0, true, 300.0);
6533        assert_eq!((list, pane), (392.0, Some(300.0)));
6534        assert_eq!(split_list(700.0, 8.0, true, 10.0).1, Some(PANE_MIN_WIDTH));
6535        assert_eq!(split_list(700.0, 8.0, true, 900.0).0, LIST_MIN_WIDTH);
6536    }
6537
6538    #[test]
6539    fn requests_round_trip_and_results_read() {
6540        let r = FileRequest::save("Export", "out.png")
6541            .directory("/tmp")
6542            .filter("PNG", &["PNG"]);
6543        assert_eq!(FileRequest::from_json(&r.to_json()).unwrap(), r);
6544        assert_eq!(r.filters[0].extensions, vec!["png"]);
6545        assert!(r.filters[0].accepts(Path::new("a.PNG")));
6546        assert_eq!(chosen(&Ok(Json::Null)), Ok(Chosen::Cancelled));
6547        assert_eq!(
6548            chosen(&Ok(json!({ "paths": ["/a", "/b"] }))),
6549            Ok(Chosen::Paths(vec!["/a".into(), "/b".into()]))
6550        );
6551        assert_eq!(chosen(&Err("no".into())), Err("no".into()));
6552    }
6553
6554    #[test]
6555    fn the_picker_filters_completes_and_navigates() {
6556        let root = tree("navigate");
6557        let mut p = FilePicker::new(
6558            &FileRequest::open("Open")
6559                .directory(&root)
6560                .filter("Images", &["png", "jpg"]),
6561        );
6562        let names = listed;
6563        assert_eq!(names(&mut p), vec!["notes", "photos"]);
6564        p.go(root.join("photos"));
6565        // Folders first, then the files the filter accepts.
6566        assert_eq!(names(&mut p), vec!["2025", "2026", "a.png", "b.jpg"]);
6567        p.filter_index = 1; // all files
6568        assert_eq!(names(&mut p).len(), 5);
6569        // The fuzzy filter.
6570        p.text = "rdm".into();
6571        assert_eq!(names(&mut p), vec!["readme.txt"]);
6572        assert_eq!(
6573            p.activate(),
6574            Some(PickerAnswer::Chosen(vec![root.join("photos/readme.txt")]))
6575        );
6576        // A typed path completes, then Enter goes in.
6577        p.text = format!("{}/no", root.display());
6578        assert!(p.complete());
6579        assert_eq!(p.text, format!("{}/notes/", root.display()));
6580        assert_eq!(p.activate(), None);
6581        assert_eq!(p.dir, root.join("notes"));
6582        p.text = "../ph".into();
6583        assert!(p.complete());
6584        assert_eq!(p.text, "../photos/");
6585        p.text = "../photos/20".into();
6586        // 2025 and 2026 share 202.
6587        assert!(p.complete());
6588        assert_eq!(p.text, "../photos/202");
6589        assert!(!p.complete());
6590        assert_eq!(p.completions().len(), 2);
6591        // Hidden folders only when asked.
6592        p.go(root.clone());
6593        assert!(!names(&mut p).contains(&".hidden".to_string()));
6594        p.show_hidden = true;
6595        assert!(names(&mut p).contains(&".hidden".to_string()));
6596        // A missing file is said.
6597        p.text = "~/surely/not/here.png".into();
6598        assert_eq!(p.activate(), None);
6599        assert!(p.error.is_some());
6600        let _ = std::fs::remove_dir_all(root);
6601    }
6602
6603    #[test]
6604    fn the_picker_reads_a_memory_folder() {
6605        let root = PathBuf::from("/demo");
6606        let fs: SharedFs = Arc::new(
6607            fs::MemoryFs::new()
6608                .file(root.join("Photos/a.png"), b"x".to_vec())
6609                .file(root.join("notes.txt"), b"y".to_vec()),
6610        );
6611        let mut p = FilePicker::new_in(&FileRequest::open("Open").directory(&root), fs);
6612        assert_eq!(p.dir, root);
6613        let names =
6614            |p: &mut FilePicker| p.visible().into_iter().map(|e| e.name).collect::<Vec<_>>();
6615        assert_eq!(names(&mut p), vec!["Photos", "notes.txt"]);
6616        // Enter goes into the folder, then chooses its file.
6617        assert_eq!(p.activate(), None);
6618        assert_eq!(p.dir, root.join("Photos"));
6619        assert_eq!(
6620            p.activate(),
6621            Some(PickerAnswer::Chosen(vec![root.join("Photos/a.png")]))
6622        );
6623    }
6624
6625    /// A provider that names what it was asked for, at the size asked.
6626    #[derive(Debug)]
6627    struct Fake;
6628
6629    impl preview::PreviewProvider for Fake {
6630        fn id(&self) -> &str {
6631            "fake"
6632        }
6633        fn handles(&self) -> preview::Handles {
6634            preview::Handles::new().extensions(&["fake"]).folders()
6635        }
6636        fn priority(&self) -> i32 {
6637            50
6638        }
6639        fn preview(
6640            &self,
6641            request: &preview::PreviewRequest,
6642        ) -> Result<Option<preview::Preview>, String> {
6643            if request.meta.is_dir {
6644                return Err("folders are not faked".into());
6645            }
6646            Ok(Some(
6647                preview::Preview::new(preview::Body::Empty)
6648                    .dimensions(request.max_side, 7)
6649                    .pages(3)
6650                    .fact("Name", request.path.display().to_string()),
6651            ))
6652        }
6653    }
6654
6655    #[test]
6656    fn agents_read_a_preview_and_the_picker_says_it() {
6657        let root = PathBuf::from("/demo");
6658        let fs: SharedFs = Arc::new(
6659            fs::MemoryFs::new()
6660                .file_at(
6661                    root.join("a.fake"),
6662                    b"x".to_vec(),
6663                    Some(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(60)),
6664                )
6665                .dir(root.join("sub")),
6666        );
6667        let mut app = crate::App::builder()
6668            .plugin(FilesPlugin::in_app().file_system(fs.clone()))
6669            .build(&egui::Context::default())
6670            .unwrap();
6671        let files = app.handle().service(&FILES).unwrap();
6672        files.previews().register(Arc::new(Fake));
6673        assert_eq!(files.previews().providers()[0], ("fake".into(), 50));
6674        let out = app
6675            .run(
6676                &CMD_PREVIEW,
6677                json!({ "path": "/demo/a.fake" }),
6678                Origin::Agent("test".into()),
6679            )
6680            .now()
6681            .unwrap()
6682            .unwrap();
6683        assert_eq!(out["state"], "ready");
6684        assert_eq!(out["provider"], "fake");
6685        assert_eq!(out["dimensions"], json!([preview::MAX_SIDE, 7]));
6686        assert_eq!(out["pages"], 3);
6687        assert_eq!(out["size"], 1);
6688        assert_eq!(out["modified"], 60);
6689        assert_eq!(out["modified_text"], "1970-01-01 00:01 UTC");
6690        // A failure is a reason.
6691        let out = preview_metadata(&files, &root.join("sub")).unwrap();
6692        assert_eq!(out["state"], "failed");
6693        assert_eq!(out["reason"], "folders are not faked");
6694        assert!(preview_metadata(&files, &root.join("missing")).is_err());
6695        // The picker's pane asks the same providers; the bridge says what
6696        // it shows.
6697        let mut p = FilePicker::new_in(&FileRequest::open("Open").directory(&root), fs)
6698            .with_previews(files.previews());
6699        assert_eq!(p.highlighted().unwrap().name, "sub");
6700        p.highlight = 1;
6701        let d = p.describe();
6702        assert_eq!(d["preview"]["state"], "ready", "{d}");
6703        assert_eq!(
6704            d["preview"]["path"],
6705            root.join("a.fake").display().to_string()
6706        );
6707        p.show_preview = false;
6708        assert!(p.describe()["preview"].is_null());
6709    }
6710
6711    #[test]
6712    fn a_picker_drawn_in_a_panel_says_what_it_highlights() {
6713        let root = PathBuf::from("/demo");
6714        let fs: SharedFs = Arc::new(fs::MemoryFs::new().dir(root.join("sub")));
6715        let app = crate::App::builder()
6716            .plugin(FilesPlugin::in_app().file_system(fs))
6717            .build(&egui::Context::default())
6718            .unwrap();
6719        let h = app.handle().clone();
6720        let files = h.service(&FILES).unwrap();
6721        let (id, _pending) = files.choose_inline(&h, FileRequest::open("Open").directory(&root));
6722        assert_eq!(files.highlighted(id).unwrap().name, "sub");
6723        assert!(files.highlighted(id + 1).is_none());
6724    }
6725
6726    #[test]
6727    fn a_name_s_extension_is_read_added_and_its_stem_found() {
6728        assert_eq!(extension_dot("a.png"), Some(1));
6729        assert_eq!(extension_dot("a.tar.gz"), Some(5));
6730        assert_eq!(extension_dot("/x.y/photo"), None);
6731        assert_eq!(extension_dot(".config"), None);
6732        assert_eq!(extension_dot("photo."), None);
6733        assert_eq!(extension_dot("Mr. Smith"), None);
6734        assert_eq!(with_extension("a", "png"), "a.png");
6735        assert_eq!(with_extension("a.", "png"), "a.png");
6736        assert_eq!(with_extension("Mr. Smith", "png"), "Mr. Smith.png");
6737        assert_eq!(with_extension("a.jpg", "png"), "a.jpg");
6738        assert_eq!(with_extension(".config", "png"), ".config");
6739        assert_eq!(with_extension("/x.y/a", "png"), "/x.y/a.png");
6740        assert_eq!(stem_chars("été.png"), (0, 3));
6741        assert_eq!(stem_chars("/é/a.png"), (3, 4));
6742        assert_eq!(stem_chars("a.tar.gz"), (0, 5));
6743        assert_eq!(stem_chars(".config"), (0, 7));
6744        assert_eq!(stem_chars(""), (0, 0));
6745    }
6746
6747    #[test]
6748    fn a_filter_changes_only_the_extensions_filters_name() {
6749        let fs: SharedFs = Arc::new(fs::MemoryFs::new().dir("/demo"));
6750        let request = FileRequest::save("Save", "a.png")
6751            .directory("/demo")
6752            .filter("PNG", &["png"])
6753            .filter("Images", &["jpg", "png"])
6754            .filter("Any", &[]);
6755        let mut p = FilePicker::new_in(&request, fs);
6756        // The new filter accepts it too.
6757        p.set_filter(1);
6758        assert_eq!(p.text, "a.png");
6759        p.set_filter(0);
6760        p.text = "a.jpg".into();
6761        p.set_filter(1);
6762        assert_eq!(p.text, "a.jpg");
6763        p.set_filter(0);
6764        assert_eq!(p.text, "a.png");
6765        // No extension to follow with: a filter without any, or all files.
6766        p.set_filter(2);
6767        assert_eq!(p.text, "a.png");
6768        p.set_filter(3);
6769        assert_eq!(p.text, "a.png");
6770        // Back from all files, an extension a filter names follows.
6771        p.text = "a.jpg".into();
6772        p.set_filter(0);
6773        assert_eq!(p.text, "a.png");
6774        // One no filter names is the person's; no extension waits for Enter.
6775        p.text = "a.tiff".into();
6776        p.set_filter(1);
6777        assert_eq!(p.text, "a.tiff");
6778        p.text = "a".into();
6779        p.set_filter(0);
6780        assert_eq!(p.text, "a");
6781        // Not when opening: the field filters there.
6782        let mut p = FilePicker::new_in(
6783            &FileRequest::open("Open")
6784                .directory("/demo")
6785                .filter("PNG", &["png"])
6786                .filter("JPEG", &["jpg"]),
6787            Arc::new(fs::MemoryFs::new().dir("/demo")),
6788        );
6789        p.text = "a.png".into();
6790        p.set_filter(1);
6791        assert_eq!(p.text, "a.png");
6792    }
6793
6794    #[test]
6795    fn a_typed_folder_is_entered_and_the_proposed_name_comes_back() {
6796        let root = tree("save-folder");
6797        let mut p = FilePicker::new(&FileRequest::save("Save", "new.png").directory(&root));
6798        p.text = "photos".into();
6799        assert_eq!(p.activate(), None);
6800        assert_eq!(p.dir, root.join("photos"));
6801        assert_eq!(p.text, "new.png");
6802        // A missing folder is said, rather than made into a file's name.
6803        p.text = "nowhere/".into();
6804        assert_eq!(p.activate(), None);
6805        assert!(p.error.is_some());
6806        p.text = "nowhere/x.png".into();
6807        assert_eq!(p.activate(), None);
6808        assert!(p.error.is_some());
6809        // On its own, the picker hands the question to its caller.
6810        p.text = "a.png".into();
6811        assert_eq!(
6812            p.activate(),
6813            Some(PickerAnswer::Replace(root.join("photos/a.png")))
6814        );
6815        let _ = std::fs::remove_dir_all(root);
6816    }
6817
6818    #[test]
6819    fn folders_saves_and_several_files() {
6820        let root = tree("kinds");
6821        let mut p = FilePicker::new(&FileRequest::folder("Folder").directory(&root));
6822        assert_eq!(listed(&mut p), ["notes", "photos"]);
6823        assert_eq!(p.accept(), Some(PickerAnswer::Chosen(vec![root.clone()])));
6824        let mut p = FilePicker::new(&FileRequest::save("Save", "new.png").directory(&root));
6825        assert_eq!(p.text, "new.png");
6826        assert_eq!(
6827            p.activate(),
6828            Some(PickerAnswer::Chosen(vec![root.join("new.png")]))
6829        );
6830        let mut p = FilePicker::new(&FileRequest::open_many("Many").directory(root.join("photos")));
6831        listed(&mut p);
6832        p.highlight = 2;
6833        p.toggle();
6834        p.highlight = 3;
6835        p.toggle();
6836        assert_eq!(
6837            p.accept(),
6838            Some(PickerAnswer::Chosen(vec![
6839                root.join("photos/a.png"),
6840                root.join("photos/b.jpg")
6841            ]))
6842        );
6843        let _ = std::fs::remove_dir_all(root);
6844    }
6845
6846    /// A memory folder of two subfolders and three files, listed at once.
6847    fn selection_picker(request: FileRequest) -> FilePicker {
6848        let root = PathBuf::from("/sel");
6849        let fs: SharedFs = Arc::new(
6850            fs::MemoryFs::new()
6851                .file(root.join("Raw/x.png"), b"x".to_vec())
6852                .file(root.join("Done/y.png"), b"y".to_vec())
6853                .file(root.join("a.png"), b"a".to_vec())
6854                .file(root.join("b.png"), b"b".to_vec())
6855                .file(root.join("c.png"), b"c".to_vec()),
6856        );
6857        let mut p = FilePicker::new_in(&request.directory(&root), fs);
6858        if p.kind != ChooseKind::Folder {
6859            assert_eq!(listed(&mut p), ["Done", "Raw", "a.png", "b.png", "c.png"]);
6860        }
6861        p
6862    }
6863
6864    fn names_of(p: &FilePicker) -> Vec<String> {
6865        (p.selected.iter())
6866            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
6867            .collect()
6868    }
6869
6870    #[test]
6871    fn choosing_one_file_the_highlight_is_the_choice() {
6872        let mut p = selection_picker(FileRequest::open("Open"));
6873        let shown = p.visible();
6874        p.click_entry(3, &shown, Modifiers::NONE);
6875        assert_eq!(p.highlight, 3);
6876        // Nothing selected apart from the highlight, Ctrl or Shift held.
6877        p.click_entry(4, &shown, Modifiers::SHIFT);
6878        p.click_entry(2, &shown, Modifiers::COMMAND);
6879        assert_eq!(p.highlight, 2);
6880        assert!(p.selected.is_empty());
6881        p.move_highlight(4, &shown, true);
6882        assert_eq!(p.highlight, 4);
6883        assert!(p.selected.is_empty());
6884        assert_eq!(
6885            p.activate(),
6886            Some(PickerAnswer::Chosen(vec![PathBuf::from("/sel/c.png")]))
6887        );
6888        // The highlight the application sets is the browser's focus.
6889        p.highlight = 2;
6890        assert_eq!(p.highlighted().unwrap().name, "a.png");
6891    }
6892
6893    #[test]
6894    fn choosing_several_files_the_policy_keeps_folders_out() {
6895        let mut p = selection_picker(FileRequest::open_many("Many"));
6896        let shown = p.visible();
6897        // A click on a file selects it alone; on a folder, nothing.
6898        p.click_entry(2, &shown, Modifiers::NONE);
6899        assert_eq!(names_of(&p), ["a.png"]);
6900        p.click_entry(1, &shown, Modifiers::NONE);
6901        assert!(p.selected.is_empty());
6902        // Ctrl adds and takes away; on a folder it is refused, and said.
6903        p.click_entry(2, &shown, Modifiers::COMMAND);
6904        p.click_entry(4, &shown, Modifiers::COMMAND);
6905        assert_eq!(names_of(&p), ["a.png", "c.png"]);
6906        p.click_entry(0, &shown, Modifiers::COMMAND);
6907        assert!(p.error.is_some());
6908        assert_eq!(names_of(&p), ["a.png", "c.png"]);
6909        p.click_entry(4, &shown, Modifiers::COMMAND);
6910        assert_eq!(names_of(&p), ["a.png"]);
6911        // Shift selects the files from the anchor, the folders left out.
6912        p.click_entry(0, &shown, Modifiers::NONE);
6913        p.click_entry(3, &shown, Modifiers::SHIFT);
6914        assert_eq!(names_of(&p), ["a.png", "b.png"]);
6915        // A move without Shift takes the anchor along.
6916        p.move_highlight(4, &shown, false);
6917        assert_eq!(names_of(&p), ["a.png", "b.png"]);
6918        p.move_highlight(3, &shown, true);
6919        assert_eq!(names_of(&p), ["b.png", "c.png"]);
6920        // Files the field hides stay selected, and are counted.
6921        p.text = "a.p".into();
6922        p.text_changed();
6923        assert_eq!(listed(&mut p), ["a.png"]);
6924        assert_eq!(names_of(&p), ["b.png", "c.png"]);
6925        p.select_all().unwrap();
6926        assert_eq!(names_of(&p), ["a.png", "b.png", "c.png"]);
6927        let line = p.primary().readout.unwrap();
6928        assert!(line.contains('3') && line.contains('2'), "{line}");
6929        // Another folder leaves the selection behind.
6930        p.text.clear();
6931        p.text_changed();
6932        p.go(PathBuf::from("/sel/Raw"));
6933        assert_eq!(listed(&mut p), ["x.png"]);
6934        assert!(p.selected.is_empty());
6935    }
6936
6937    #[test]
6938    fn choosing_a_folder_selects_one_folder() {
6939        let mut p = selection_picker(FileRequest::folder("Folder"));
6940        assert_eq!(listed(&mut p), ["Done", "Raw"]);
6941        let shown = p.visible();
6942        p.click_entry(1, &shown, Modifiers::NONE);
6943        assert_eq!(names_of(&p), ["Raw"]);
6944        // One at a time: Shift is a plain click, Ctrl unselects.
6945        p.click_entry(0, &shown, Modifiers::SHIFT);
6946        assert_eq!(names_of(&p), ["Done"]);
6947        p.click_entry(0, &shown, Modifiers::COMMAND);
6948        assert!(p.selected.is_empty());
6949        assert_eq!(p.highlight, 0);
6950        assert_eq!(
6951            p.accept(),
6952            Some(PickerAnswer::Chosen(vec![PathBuf::from("/sel")]))
6953        );
6954        // The arrows select the folder they land on.
6955        p.move_highlight(1, &shown, true);
6956        assert_eq!(names_of(&p), ["Raw"]);
6957        p.toggle();
6958        assert!(p.selected.is_empty());
6959        p.toggle();
6960        assert_eq!(
6961            p.accept(),
6962            Some(PickerAnswer::Chosen(vec![PathBuf::from("/sel/Raw")]))
6963        );
6964        // The selection the application sets is kept to the policy.
6965        p.selected = BTreeSet::from([PathBuf::from("/sel/Done"), PathBuf::from("/sel/Raw")]);
6966        p.visible();
6967        assert_eq!(names_of(&p), ["Done"]);
6968    }
6969
6970    #[test]
6971    fn saving_a_click_on_a_file_takes_its_name_on_a_folder_selects_it() {
6972        let mut p = selection_picker(FileRequest::save("Save", "new.png"));
6973        let shown = p.visible();
6974        p.click_entry(3, &shown, Modifiers::NONE);
6975        assert_eq!(p.text, "b.png");
6976        assert!(p.selected.is_empty());
6977        p.click_entry(1, &shown, Modifiers::NONE);
6978        assert_eq!(names_of(&p), ["Raw"]);
6979        p.move_highlight(2, &shown, false);
6980        assert!(p.selected.is_empty());
6981        p.move_highlight(0, &shown, false);
6982        assert_eq!(names_of(&p), ["Done"]);
6983        // Enter goes into the folder selected.
6984        assert_eq!(p.activate(), None);
6985        assert_eq!(p.dir, PathBuf::from("/sel/Done"));
6986        assert!(p.selected.is_empty());
6987    }
6988}