use crate::event::{Key, Mods};
use crate::layout::{Align, Length};
use crate::listing::{By, Listing, Reader, Small, Wanted, ending, ends_in};
use crate::places::Place;
use crate::table::{Column, Table};
use crate::told::Role;
use crate::ui::{Icon, Picture, Response, Stroke, Ui};
use std::fmt::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;
const FOLDER: Icon = Icon::line("M2 4.5h4l1.5 1.5H14v6.5H2z");
const PAGE: Icon = Icon::line("M4 2h5l3 3v9H4zM9 2v3h3");
const PICTURE: Icon = Icon::line("M2.5 3.5h11v9h-11zM2.5 10.5l3-3 3 3 2-2 3 3");
const BACK: Icon = Icon::line("M13 8H3.5M7.5 4 3.5 8l4 4");
const AHEAD: Icon = Icon::line("M3 8h9.5M8.5 4l4 4-4 4");
const UP: Icon = Icon::line("M8 13V3.5M4 7.5l4-4 4 4");
const SEARCH: Icon = Icon::line("M7 2.5a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9zM10.3 10.3l3.2 3.2");
const TYPE: Icon = Icon::line("M11 2.5 13.5 5 6 12.5H3.5V10z");
const NEW_FOLDER: Icon = Icon::line("M2 4.5h4l1.5 1.5H14v6.5H2zM8 7.5v4M6 9.5h4");
const VIEW: Icon = Icon::line("M2.5 4.5h11M2.5 8h11M2.5 11.5h11");
const PLACES: Icon = Icon::line("M8 2.5l1.7 3.5 3.8.5-2.8 2.6.7 3.8L8 11.1l-3.4 1.8.7-3.8-2.8-2.6 3.8-.5z");
const HOME: Icon = Icon::line("M2.5 7.5 8 3l5.5 4.5M4 6.5V13h8V6.5");
const DRIVE: Icon = Icon::line("M2 9.5h12v3H2zM3.5 9.5l1.5-5h6l1.5 5");
const RECENT: Icon = Icon::line("M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11zM8 5v3l2 1.5");
const BETWEEN: Icon = Icon::line("M6.5 4 10.5 8 6.5 12");
const ROW: f32 = 24.0;
const CELL: f32 = 100.0;
const SMALL: f32 = 64.0;
const SIDE: f32 = 148.0;
const WITH_KINDS: f32 = 140.0 + 64.0 + 2.0 * 13.0 + 16.0;
const WITH_SIZES: f32 = WITH_KINDS + 80.0 + 13.0;
const WITH_DATES: f32 = WITH_SIZES + 128.0 + 13.0;
const LOOK_AGAIN: Duration = Duration::from_millis(40);
const TYPED_TOGETHER: Duration = Duration::from_millis(900);
const KEPT_PICTURES: usize = 256;
const RECENT_KEPT: usize = 8;
const ALT: Mods = Mods { alt: true, ..Mods::NONE };
const CTRL_SHIFT: Mods = Mods { ctrl: true, shift: true, alt: false };
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FileWords {
pub open_a_file: &'static str,
pub open_files: &'static str,
pub save_as: &'static str,
pub pick_a_folder: &'static str,
pub back: &'static str,
pub ahead: &'static str,
pub up: &'static str,
pub path: &'static str,
pub type_path: &'static str,
pub search: &'static str,
pub places: &'static str,
pub home: &'static str,
pub recent: &'static str,
pub drives: &'static str,
pub new_folder: &'static str,
pub view: &'static str,
pub hidden: &'static str,
pub grid: &'static str,
pub cancel: &'static str,
pub open: &'static str,
pub save: &'static str,
pub choose: &'static str,
pub name_hint: &'static str,
pub folder_hint: &'static str,
pub name: &'static str,
pub size: &'static str,
pub kind: &'static str,
pub date: &'static str,
pub folder: &'static str,
pub reading: &'static str,
pub none_found: &'static str,
pub not_there: &'static str,
pub there_already: &'static str,
pub replace: &'static str,
}
impl Default for FileWords {
fn default() -> Self {
FileWords {
open_a_file: "Open a file",
open_files: "Open files",
save_as: "Save as",
pick_a_folder: "Pick a folder",
back: "Back",
ahead: "Forward",
up: "Up",
path: "Where",
type_path: "Type a path",
search: "Search",
places: "Places",
home: "Home",
recent: "Recent",
drives: "Drives",
new_folder: "New folder",
view: "View",
hidden: "Hidden files",
grid: "Small pictures",
cancel: "Cancel",
open: "Open",
save: "Save",
choose: "Choose this folder",
name_hint: "The name of a file",
folder_hint: "A folder in this one, or none for this one itself",
name: "Name",
size: "Size",
kind: "Kind",
date: "Date",
folder: "Folder",
reading: "Reading the folder…",
none_found: "Nothing has that in its name",
not_there: "There is nothing of this name",
there_already: "is there already. Put the new one in its place?",
replace: "Replace",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FileAsk {
pub saving: bool,
pub folders: bool,
pub folder: PathBuf,
pub name: String,
pub endings: Vec<String>,
pub title: &'static str,
}
pub(crate) type Own = fn(&mut Ui, &mut Files) -> Option<PathBuf>;
pub struct Files {
pub system: bool,
own: Option<Own>,
pub folder: PathBuf,
pub name: String,
pub shown: bool,
pub words: FileWords,
pub chosen: Vec<PathBuf>,
pub recent: Vec<PathBuf>,
pub own_places: Vec<(String, PathBuf)>,
pub show_hidden: bool,
pub grid: bool,
saving: bool,
folders: bool,
many: bool,
endings: Vec<String>,
listing: Listing,
stale: bool,
table: Table,
columns_chosen: bool,
places: Vec<Place>,
drives: Vec<Place>,
places_due: bool,
back: Vec<PathBuf>,
ahead: Vec<PathBuf>,
seek: String,
searching: bool,
typing_path: Option<String>,
making: Option<String>,
asking: Option<PathBuf>,
fresh: Fresh,
trouble: String,
trouble_new: bool,
visits: u32,
focus_was: crate::id::Id,
opened_from: Option<crate::id::Id>,
asked_from: crate::id::Id,
jump: Option<usize>,
onto: Option<String>,
typed: (String, Duration),
read: Option<Reader>,
small: Option<Small>,
pictures: Vec<(u32, Picture, [f32; 2])>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Fresh {
#[default]
Nothing,
Name,
Search,
Path,
NewFolder,
Question,
}
enum Go {
To(PathBuf),
Back,
Ahead,
}
#[derive(Default)]
struct Did {
on: Option<usize>,
taken: Option<u32>,
picked: bool,
pictures: Vec<u32>,
}
impl Default for Files {
fn default() -> Self {
Files::new(false, Some(Ui::own_file_dialog))
}
}
impl std::fmt::Debug for Files {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Files").field("folder", &self.folder).field("name", &self.name).field("chosen", &self.chosen).field("shown", &self.shown).field("system", &self.system).finish_non_exhaustive()
}
}
impl Files {
pub fn of_the_system() -> Self {
#[cfg(windows)]
let own = None;
#[cfg(not(windows))]
let own = Some(Ui::own_file_dialog as Own);
Files::new(true, own)
}
fn new(system: bool, own: Option<Own>) -> Self {
Files {
system,
own,
folder: PathBuf::new(),
name: String::new(),
shown: false,
words: FileWords::default(),
chosen: Vec::new(),
recent: Vec::new(),
own_places: Vec::new(),
show_hidden: false,
grid: false,
saving: false,
folders: false,
many: false,
endings: Vec::new(),
listing: Listing::default(),
stale: false,
table: Table::default(),
columns_chosen: false,
places: Vec::new(),
drives: Vec::new(),
places_due: false,
back: Vec::new(),
ahead: Vec::new(),
seek: String::new(),
searching: false,
typing_path: None,
making: None,
asking: None,
fresh: Fresh::Nothing,
trouble: String::new(),
trouble_new: false,
visits: 0,
focus_was: 0,
opened_from: None,
asked_from: 0,
jump: None,
onto: None,
typed: (String::new(), Duration::ZERO),
read: None,
small: None,
pictures: Vec::new(),
}
}
pub fn only(&mut self, endings: &[&str]) {
(self.endings, self.stale) = (endings.iter().map(|ending| ending.to_lowercase()).collect(), true);
}
pub fn show_pictures(&mut self) {
self.read = Some(crate::ui::read_picture);
}
pub fn pick(&mut self, folder: impl Into<PathBuf>) {
self.show(folder.into(), String::new(), [false, false, false]);
}
pub fn pick_many(&mut self, folder: impl Into<PathBuf>) {
self.own.get_or_insert(Ui::own_file_dialog);
self.show(folder.into(), String::new(), [false, false, true]);
}
pub fn save(&mut self, folder: impl Into<PathBuf>, name: &str) {
self.show(folder.into(), name.into(), [true, false, false]);
}
pub fn pick_folder(&mut self, folder: impl Into<PathBuf>) {
self.show(folder.into(), String::new(), [false, true, false]);
}
fn show(&mut self, folder: PathBuf, name: String, [saving, folders, many]: [bool; 3]) {
let folder = std::path::absolute(&folder).unwrap_or(folder);
(self.saving, self.folders, self.many, self.shown, self.fresh) = (saving, folders, many, true, Fresh::Name);
self.back.clear();
self.ahead.clear();
self.places_due = true;
self.arrive(folder);
self.name = name;
}
fn go(&mut self, way: Go, on_list: bool) {
let (to, back, fresh) = match way {
Go::To(folder) => (Some(folder), true, true),
Go::Back => (self.back.pop(), false, false),
Go::Ahead => (self.ahead.pop(), true, false),
};
let Some(to) = to.filter(|to| *to != self.folder) else { return };
let was = std::mem::take(&mut self.folder);
let left = was.parent().filter(|above| *above == to).and(was.file_name()).map(|name| name.to_string_lossy().into_owned());
let onto = on_list.then(|| left.unwrap_or_default());
match back {
true => self.back.push(was),
false => self.ahead.push(was),
}
if fresh {
self.ahead.clear();
}
self.arrive(to);
self.onto = onto;
}
fn arrive(&mut self, folder: PathBuf) {
(self.folder, self.stale, self.searching, self.typing_path, self.making) = (folder, true, false, None, None);
self.visits = self.visits.wrapping_add(1);
(self.jump, self.onto) = (None, None);
self.seek.clear();
self.trouble.clear();
if !self.saving {
self.name.clear();
}
}
fn above(&self) -> Option<PathBuf> {
let empty = self.folder.as_os_str().is_empty();
self.folder.parent().map(PathBuf::from).or((cfg!(windows) && !empty).then(PathBuf::new))
}
fn picked_names(&self) -> Option<String> {
let names: Vec<&str> = self.listing.picked().filter(|at| !self.saving || !self.listing.entry(*at).folder()).map(|at| self.listing.name(at)).collect();
match names[..] {
[] if self.saving => None,
[] => Some(String::new()),
[one] => Some(one.into()),
_ => Some(names.iter().map(|name| format!("\"{name}\"")).collect::<Vec<_>>().join(" ")),
}
}
fn named(&self) -> Vec<PathBuf> {
let text = self.name.trim();
let quoted: Vec<&str> = text.split('"').skip(1).step_by(2).filter(|name| !name.trim().is_empty()).collect();
let names = if text.starts_with('"') && !quoted.is_empty() { quoted } else { vec![text] };
names.into_iter().filter(|name| !name.is_empty()).map(|name| self.full(name)).collect()
}
fn full(&self, name: &str) -> PathBuf {
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
match (name.strip_prefix('~'), home) {
(Some(rest), Some(home)) if rest.is_empty() || rest.starts_with(['/', '\\']) => home.join(rest.trim_start_matches(['/', '\\'])),
_ => self.folder.join(name),
}
}
fn take(&mut self) -> Option<PathBuf> {
let named = self.named();
let [first, ..] = &named[..] else { return None };
if named.len() == 1 && first.is_dir() {
self.go(Go::To(first.clone()), false);
self.name.clear();
return None;
}
if self.folders {
return None;
}
if self.saving {
return self.save_as(first.clone());
}
match named.iter().find(|file| !file.is_file()) {
Some(missing) => self.tell_trouble(format!("{}: {}", self.words.not_there, missing.file_name().unwrap_or_default().to_string_lossy())),
None => return self.answer(if self.many { named } else { vec![first.clone()] }),
}
None
}
fn save_as(&mut self, file: PathBuf) -> Option<PathBuf> {
let name = file.file_name().unwrap_or_default().to_string_lossy().into_owned();
let file = match self.endings.first() {
Some(first) if !self.endings.iter().any(|ending| ends_in(&name, ending)) => file.with_file_name(name + first),
_ => file,
};
if !file.parent().is_some_and(Path::is_dir) {
self.tell_trouble(format!("{}: {}", self.words.not_there, file.parent().unwrap_or(&file).to_string_lossy()));
return None;
}
if file.is_dir() {
self.go(Go::To(file), false);
return None;
}
if file.exists() {
(self.asking, self.fresh) = (Some(file), Fresh::Question);
return None;
}
self.answer(vec![file])
}
fn choose(&mut self) -> Option<PathBuf> {
let folder = self.named().into_iter().next().unwrap_or(self.folder.clone());
if folder.as_os_str().is_empty() || !folder.is_dir() {
return None;
}
self.answer(vec![folder])
}
fn answer(&mut self, chosen: Vec<PathBuf>) -> Option<PathBuf> {
let first = chosen.first()?.clone();
let folder = if self.folders { Some(first.as_path()) } else { first.parent() };
if let Some(folder) = folder.filter(|folder| !folder.as_os_str().is_empty()) {
self.recent.retain(|recent| recent != folder);
self.recent.insert(0, folder.to_path_buf());
self.recent.truncate(RECENT_KEPT);
}
(self.shown, self.chosen, self.asking) = (false, chosen, None);
Some(first)
}
fn tell_trouble(&mut self, trouble: String) {
(self.trouble, self.trouble_new) = (trouble, true);
}
fn make_folder(&mut self) {
let Some(name) = self.making.take() else { return };
let new = self.folder.join(name.trim());
match std::fs::create_dir(&new) {
Ok(()) => self.go(Go::To(new), false),
Err(error) => self.tell_trouble(error.to_string()),
}
}
fn free_name(&self) -> String {
let name = |number: u32| if number < 2 { self.words.new_folder.to_string() } else { format!("{} {number}", self.words.new_folder) };
(1..1000).map(name).find(|name| !self.folder.join(name).exists()).unwrap_or_default()
}
fn title(&self) -> &'static str {
match (self.folders, self.saving, self.many) {
(true, ..) => self.words.pick_a_folder,
(false, true, _) => self.words.save_as,
(false, false, true) => self.words.open_files,
(false, false, false) => self.words.open_a_file,
}
}
fn sorted(&self) -> (By, bool) {
let (by, down) = self.table.sort.first().copied().unwrap_or((0, false));
([By::Name, By::Size, By::Kind, By::Date][by.min(3)], down)
}
}
impl Ui {
pub fn file_dialog(&mut self, files: &mut Files) -> Option<PathBuf> {
if files.shown && files.system && self.system_files && !files.many {
return self.ask_system(files);
}
match files.own {
Some(own) => own(self, files),
None => {
files.shown = false;
None
}
}
}
pub(crate) fn own_file_dialog(&mut self, files: &mut Files) -> Option<PathBuf> {
if !files.shown {
if let Some(back) = files.opened_from.take() {
self.set_focus(back);
}
self.let_pictures_go(files);
return None;
}
if std::mem::take(&mut files.places_due) {
files.places = files.own_places.iter().map(|(name, folder)| Place { name: name.clone(), folder: folder.clone() }).collect();
files.places.extend(crate::places::own_folders(files.words.home));
files.drives = crate::places::volumes();
}
self.read_folder(files);
let (t, room, words) = (self.theme, self.size(), files.words);
let (wide, high) = ((room.w - 76.0).clamp(240.0, 720.0), (room.h - 220.0).clamp(72.0, 420.0));
let side = wide >= 480.0;
let beside = self.dialog_up_to(wide + 36.0);
self.column().key("all").gap(12.0).max(f32::INFINITY, (room.h - 60.0).max(120.0)).scroll().open();
self.text(files.title(), t.font.bold(), t.text);
let mut went = self.file_bar(files, wide);
self.row().size(wide, high).gap(8.0).align(Align::Start, Align::Spread).open();
if side {
went = went.or(self.file_places(files));
}
let did = match (files.grid && files.read.is_some(), files.listing.found.is_empty() && files.making.is_none()) {
(_, true) => self.nothing_listed(files),
(true, false) => self.file_grid(files, [wide - if side { SIDE + 8.0 } else { 0.0 }, high]),
(false, false) => self.file_table(files, [wide - if side { SIDE + 8.0 } else { 0.0 }, high]),
};
self.close();
self.file_note(files, wide);
self.row().key("name").w(Length::Px(wide)).open();
let name = self.text_box(&mut files.name, if files.folders { words.folder_hint } else { words.name_hint });
self.close();
let (bottom, pressed) = self.file_buttons(files, !side, wide);
self.close();
self.close();
went = went.or(bottom);
let replace = self.ask_to_replace(files);
self.after_list(files, &did);
self.fresh_keyboard(files, &name);
files.focus_was = self.focus();
let keyed = self.file_keys(files, did.on.is_some());
went = went.or(keyed.0);
let went_anywhere = went.is_some();
if let Some(way) = went {
files.go(way, did.on.is_some());
}
let closed = files.asking.is_none() && (beside.clicked || keyed.1 == Some(false) || pressed == Some(false));
if closed {
files.shown = false;
}
let answer = match (replace, pressed, keyed.1, did.taken) {
(Some(true), ..) => files.asking.take().and_then(|file| files.answer(vec![file])),
(_, Some(true), ..) if files.folders => files.choose(),
(_, Some(true), ..) | (_, _, Some(true), _) => files.take(),
(.., Some(at)) => self.take_thing(files, at),
_ => None,
};
if std::mem::take(&mut files.trouble_new) && !files.trouble.is_empty() {
self.announce(&files.trouble);
}
let acted = went_anywhere || pressed.is_some() || keyed.1.is_some() || did.taken.is_some() || replace.is_some();
if acted || answer.is_some() || !files.shown || files.stale || name.changed || did.picked {
self.rerun();
}
answer
}
fn read_folder(&mut self, files: &mut Files) {
if std::mem::take(&mut files.stale) {
if let Some(there) = files.folder.ancestors().find(|folder| folder.is_dir()).filter(|there| *there != files.folder) {
files.folder = there.to_path_buf();
}
self.let_pictures_go(files);
let wanted = Wanted { folders_only: files.folders, endings: files.endings.clone() };
files.listing = Listing::of(files.folder.clone(), wanted, files.sorted(), files.show_hidden);
files.listing.show(&files.seek, files.show_hidden);
files.tell_trouble(files.listing.trouble.clone());
let onto = files.onto.take().filter(|_| !files.listing.found.is_empty());
files.jump = onto.map(|name| files.listing.found.iter().position(|at| files.listing.name(*at) == name).unwrap_or(0));
}
files.listing.take_coming();
if files.listing.reading() || files.small.as_ref().is_some_and(|small| small.out > 0) {
self.wake_after(LOOK_AGAIN);
}
let scale = self.scale;
while let Some((at, small)) = files.small.as_mut().and_then(Small::answer) {
let Some((width, pixels)) = small.filter(|(width, pixels)| *width > 0 && !pixels.is_empty()) else { continue };
let [wide, high] = [width as f32, (pixels.len() / width) as f32].map(|side| side / scale);
let fit = (SMALL / wide.max(high)).min(1.0);
files.pictures.push((at, self.add_picture(width, pixels), [wide * fit, high * fit]));
}
}
fn let_pictures_go(&mut self, files: &mut Files) {
for (_, picture, _) in files.pictures.drain(..) {
self.drop_picture(picture);
}
files.small = None;
}
fn file_bar(&mut self, files: &mut Files, wide: f32) -> Option<Go> {
let (words, usable) = (files.words, self.enabled);
self.row().w(Length::Px(wide)).gap(4.0).align(Align::Start, Align::Center).open();
self.enabled = usable && !files.back.is_empty();
let back = self.icon_button(BACK, words.back).clicked.then_some(Go::Back);
self.enabled = usable && !files.ahead.is_empty();
let ahead = self.icon_button(AHEAD, words.ahead).clicked.then_some(Go::Ahead);
self.enabled = usable && files.above().is_some();
let up = self.icon_button(UP, words.up).clicked.then(|| files.above()).flatten().map(Go::To);
self.enabled = usable;
let room = wide - 5.0 * (self.theme.control + 4.0);
let path = match (files.typing_path.is_some(), files.searching) {
(true, _) => self.path_box(files),
(false, true) => self.search_box(files),
(false, false) => self.path_buttons(files, room),
};
let mut typing = files.typing_path.is_some();
if self.icon_toggle(&mut typing, TYPE, words.type_path).changed {
(files.typing_path, files.searching, files.fresh) = (typing.then(|| files.folder.to_string_lossy().into_owned()), false, Fresh::Path);
}
let mut searching = files.searching;
if self.icon_toggle(&mut searching, SEARCH, words.search).changed {
self.look_for_names(files, searching);
}
self.close();
back.or(ahead).or(up).or(path)
}
fn look_for_names(&mut self, files: &mut Files, open: bool) {
(files.searching, files.typing_path, files.fresh) = (open, None, if open { Fresh::Search } else { Fresh::Nothing });
if !open {
files.seek.clear();
files.listing.show("", files.show_hidden);
}
}
fn path_buttons(&mut self, files: &Files, room: f32) -> Option<Go> {
let (t, mut went) = (self.theme, None);
let ancestors = files.folder.ancestors().filter(|folder| !folder.as_os_str().is_empty());
let mut parts: Vec<(String, PathBuf)> = ancestors.map(|folder| (crumb(folder), folder.to_path_buf())).collect();
parts.reverse();
if cfg!(windows) {
parts.insert(0, (files.words.drives.into(), PathBuf::new()));
}
let (mut left, mut fit) = (room - 40.0, 0);
for (name, _) in parts.iter().rev() {
left -= self.text_width(name, t.font) + 30.0;
if left < 0.0 && fit > 0 {
break;
}
fit += 1;
}
let hidden = parts.len() - fit;
let bar = self.row().grow().min(0.0, t.control).gap(0.0).align(Align::Start, Align::Center).clip().open();
self.tell(&bar, Role::Group, None, files.words.path);
if hidden > 0 {
went = self.path_menu(&parts[..hidden]);
}
for (nth, (name, folder)) in parts.iter().enumerate().skip(hidden) {
if nth > hidden {
self.el().icon(BETWEEN, 12.0, t.text_faint).show();
}
if self.folder_crumb(name, *folder == files.folder).clicked {
went = Some(Go::To(folder.clone()));
}
}
self.close();
went
}
fn path_menu(&mut self, parts: &[(String, PathBuf)]) -> Option<Go> {
let opens = self.folder_crumb("…", false);
if opens.clicked {
self.open_popup(opens.id, opens.rect);
}
if !self.menu(opens.id) {
return None;
}
let mut picked = None;
for (name, folder) in parts.iter().rev() {
if self.menu_item(name).clicked {
picked = Some(Go::To(folder.clone()));
}
}
self.close();
picked
}
fn folder_crumb(&mut self, name: &str, here: bool) -> Response {
let t = self.theme;
let state = self.press(self.next_id());
let fill = if state.hovered || state.pressed { t.hover } else { crate::color::Color::NONE };
let font = if here { t.font.bold() } else { t.font };
let el = self.el().text(name, font, if here { t.text } else { t.text_dim }).pad((6.0, 0.0)).fill(fill).radius(4.0).sense().focusable();
el.min(24.0, t.control).gives_way(if here { 1 } else { 2 }).show();
state
}
fn path_box(&mut self, files: &mut Files) -> Option<Go> {
let mut typed = files.typing_path.take().unwrap_or_default();
let state = self.text_box(&mut typed, files.words.type_path);
files.typing_path = Some(typed);
if files.fresh == Fresh::Path {
files.fresh = Fresh::Nothing;
self.set_focus(state.id);
self.select_all();
}
if !state.focused {
return None;
}
if self.key(Key::Escape, Mods::NONE) {
files.typing_path = None;
return None;
}
if !self.key(Key::Enter, Mods::NONE) {
return None;
}
let path = files.full(files.typing_path.as_deref().unwrap_or_default().trim());
if path.is_dir() {
return Some(Go::To(path));
}
let folder = path.parent().filter(|folder| folder.is_dir()).map(PathBuf::from);
let name = path.file_name().map(|name| name.to_string_lossy().into_owned());
let Some((folder, name)) = folder.zip(name).filter(|_| !files.folders) else {
files.tell_trouble(format!("{}: {}", files.words.not_there, path.to_string_lossy()));
return None;
};
(files.typing_path, files.name, files.fresh) = (None, name, Fresh::Name);
Some(Go::To(folder))
}
fn search_box(&mut self, files: &mut Files) -> Option<Go> {
let state = self.text_box(&mut files.seek, files.words.search);
if files.fresh == Fresh::Search {
files.fresh = Fresh::Nothing;
self.set_focus(state.id);
}
if state.changed {
files.listing.show(&files.seek, files.show_hidden);
}
if !state.focused {
return None;
}
if self.key(Key::Escape, Mods::NONE) {
let open = !files.seek.is_empty();
self.look_for_names(files, open);
files.seek.clear();
files.listing.show("", files.show_hidden);
}
match files.listing.found[..] {
[only] if self.enter_waiting() => files.name = files.listing.name(only).into(),
_ if self.key(Key::Enter, Mods::NONE) => files.jump = Some(0),
_ => {}
}
None
}
fn file_places(&mut self, files: &Files) -> Option<Go> {
let (t, mut to) = (self.theme, None);
let around = self.column().w(Length::Px(SIDE)).gap(1.0).scroll().open();
self.tell(&around, Role::Group, None, files.words.places);
let own = files.own_places.len();
for (nth, place) in files.places.iter().enumerate() {
let mark = if nth < own {
PLACES
} else if nth == own {
HOME
} else {
FOLDER
};
to = to.or(self.place_row(mark, &place.name, &place.folder, &files.folder));
}
if !files.recent.is_empty() {
self.el().text(files.words.recent, t.small, t.text_faint).pad((8.0, 6.0, 0.0, 2.0)).show();
}
for folder in &files.recent {
to = to.or(self.place_row(RECENT, &crumb(folder), folder, &files.folder));
}
self.el().text(files.words.drives, t.small, t.text_faint).pad((8.0, 6.0, 0.0, 2.0)).show();
for place in &files.drives {
to = to.or(self.place_row(DRIVE, &place.name, &place.folder, &files.folder));
}
self.close();
to.map(Go::To)
}
fn place_row(&mut self, mark: Icon, name: &str, folder: &Path, shown: &Path) -> Option<PathBuf> {
let (t, picked) = (self.theme, folder == shown);
let state = self.press(self.next_id());
let fill = if picked {
t.selected
} else if state.hovered {
t.hover
} else {
crate::color::Color::NONE
};
self.row().min(0.0, t.control).pad((8.0, 0.0)).gap(6.0).align(Align::Start, Align::Center).fill(fill).radius(4.0).clip().sense().focusable().open();
self.tell(&state, Role::Row, Some(picked), name);
self.el().icon(mark, 16.0, t.text_dim).show();
self.label(name);
self.close();
state.clicked.then(|| folder.to_path_buf())
}
fn places_menu(&mut self, files: &Files) -> Option<Go> {
let opens = self.icon_button(PLACES, files.words.places);
if opens.clicked {
self.open_popup(opens.id, opens.rect);
}
if !self.menu(opens.id) {
return None;
}
let recent = files.recent.iter().map(|folder| Place { name: crumb(folder), folder: folder.clone() });
let all: Vec<Place> = files.places.iter().cloned().chain(recent).chain(files.drives.iter().cloned()).collect();
let mut picked = None;
for place in all {
if self.menu_item(&place.name).clicked {
picked = Some(Go::To(place.folder));
}
}
self.close();
picked
}
fn enter_waiting(&self) -> bool {
self.input.strokes.iter().any(|stroke| matches!(stroke, Stroke::Key(Key::Enter, mods) if *mods == Mods::NONE))
}
fn file_table(&mut self, files: &mut Files, [wide, high]: [f32; 2]) -> Did {
let words = files.words;
let columns = [Column::new(words.name), Column::new(words.size).px(80.0).align(Align::End), Column::new(words.kind).px(64.0), Column::new(words.date).px(128.0)];
if !files.columns_chosen {
files.table.hidden = [(3, wide < WITH_DATES), (1, wide < WITH_SIZES)].into_iter().filter(|(_, out)| *out).map(|(column, _)| column).collect();
}
let hidden = files.table.hidden.len();
let (t, mut did) = (self.theme, Did::default());
files.table.kept = 1;
self.el().key(files.visits).grow().border(t.line, 1.0).radius(6.0).clip().open();
let sorted = self.table_of_rows(&mut files.table, &columns).changed;
files.columns_chosen |= files.table.hidden.len() != hidden;
if sorted {
let (by, down) = files.sorted();
files.listing.sort(by, down);
}
let row = ROW.max(self.text.metrics(t.font, self.scale).height().ceil() + 6.0);
self.start_rows(files.jump, row, files.listing.found.len(), high - t.control - 1.0);
if files.making.is_some() {
self.table_row().open();
self.new_folder_box(files);
self.close();
}
let enter = self.enter_waiting();
let mut written = std::mem::take(&mut self.scratch);
for row in self.rows(files.listing.found.len(), row) {
let at = files.listing.found[row];
let state = self.file_row(files, at, &mut written);
self.row_did(files, row, at, &state, enter, &mut did);
}
self.scratch = written;
self.close();
self.close();
self.close();
did
}
fn start_rows(&mut self, jump: Option<usize>, row: f32, count: usize, high: f32) {
let Some(jump) = jump.filter(|jump| *jump < count) else { return };
let Some(open) = self.open.last() else { return };
let (id, offset) = (self.tree.specs[open.at as usize].id, self.tree.specs[open.at as usize].offset);
let (top, high) = (jump as f32 * row, high.max(row));
if top < offset[1] || top + row > offset[1] + high {
self.scrolls.insert(id, [offset[0], (top - (high - row) / 2.0).max(0.0)]);
self.again = true;
}
}
fn file_row(&mut self, files: &Files, at: u32, written: &mut String) -> Response {
let (entry, name) = (files.listing.entry(at), files.listing.name(at));
let state = self.pick_row(at, entry.picked());
self.row().gap(6.0).align(Align::Start, Align::Center).open();
self.icon(match (entry.folder(), files.listing.is_picture(at)) {
(true, _) => FOLDER,
(false, true) => PICTURE,
(false, false) => PAGE,
});
self.label(name);
self.close();
written.clear();
if !entry.folder() {
size(written, entry.size);
}
self.note(written);
written.clear();
match entry.folder() {
true => written.push_str(files.words.folder),
false => written.extend(ending(name).chars().map(|letter| letter.to_ascii_uppercase())),
}
self.note(written);
written.clear();
if entry.time != 0 {
let [year, month, day, hour, minute] = crate::places::local_time(entry.time);
let _ = write!(written, "{year}-{month:02}-{day:02} {hour:02}:{minute:02}");
}
self.note(written);
self.close();
state
}
fn row_did(&mut self, files: &mut Files, row: usize, at: u32, state: &Response, enter: bool, did: &mut Did) {
if files.jump == Some(row) {
self.set_focus(state.id);
files.jump = None;
}
let arrived = state.focused && self.focus_shows() && files.focus_was != state.id;
if state.focused {
did.on = Some(row);
}
let by_key = state.clicked && !self.input.released[0];
if state.clicked && !(by_key && enter) {
let mods = if by_key { Mods::NONE } else { self.mods() };
files.listing.click(row, mods.ctrl && files.many, mods.shift && files.many);
did.picked = true;
}
if state.clicked {
did.taken = did.taken.or((state.double_clicked || by_key && enter).then_some(at));
} else if arrived && !files.listing.entry(at).picked() {
files.listing.pick_only(Some(at));
did.picked = true;
}
}
fn new_folder_box(&mut self, files: &mut Files) {
let mut name = files.making.take().unwrap_or_default();
self.row().gap(6.0).align(Align::Start, Align::Center).open();
self.icon(FOLDER);
let state = self.text_box(&mut name, files.words.new_folder);
self.close();
files.making = Some(name);
if files.fresh == Fresh::NewFolder {
(files.fresh, files.jump) = (Fresh::Nothing, None);
self.set_focus(state.id);
self.select_all();
}
if state.focused && self.key(Key::Escape, Mods::NONE) {
files.making = None;
}
if state.focused && self.key(Key::Enter, Mods::NONE) {
files.make_folder();
}
}
fn file_grid(&mut self, files: &mut Files, [wide, high]: [f32; 2]) -> Did {
let (t, mut did) = (self.theme, Did::default());
let across = ((wide - 20.0) / CELL).floor().max(1.0) as usize;
let high_cell = SMALL + self.text.metrics(t.small, self.scale).height().ceil() + 16.0;
let count = files.listing.found.len();
self.column().key(files.visits).grow().border(t.line, 1.0).radius(6.0).clip().scroll().open();
self.start_rows(files.jump.map(|row| row / across), high_cell, count.div_ceil(across), high);
if files.making.is_some() {
self.row().pad((8.0, 4.0)).open();
self.new_folder_box(files);
self.close();
}
let enter = self.enter_waiting();
for line in self.rows(count.div_ceil(across), high_cell) {
self.row().open();
for row in line * across..(line * across + across).min(count) {
let at = files.listing.found[row];
let state = self.file_cell(files, at, [row, count], &mut did);
self.row_did(files, row, at, &state, enter, &mut did);
}
self.close();
}
self.close();
self.close();
did
}
fn file_cell(&mut self, files: &Files, at: u32, [nth, count]: [usize; 2], did: &mut Did) -> Response {
let (t, entry, name) = (self.theme, files.listing.entry(at), files.listing.name(at));
let state = self.press(self.id(("cell", at)));
let fill = if entry.picked() {
t.selected
} else if state.hovered {
t.hover
} else {
crate::color::Color::NONE
};
self.column().key(("cell", at)).w(Length::Px(CELL)).h(Length::Grow(1.0)).pad(4.0).gap(4.0).align(Align::Start, Align::Center).fill(fill).radius(6.0).sense().focusable().open();
self.tell(&state, Role::Row, Some(entry.picked()), name);
self.tell_place(nth + 1, count);
self.el().size(SMALL, SMALL).align(Align::Center, Align::Center).open();
let mark = if entry.folder() {
FOLDER
} else if files.listing.is_picture(at) {
PICTURE
} else {
PAGE
};
match files.pictures.iter().find(|(of, ..)| *of == at) {
Some((_, picture, [wide, high])) => self.el().picture(*picture).size(*wide, *high).show(),
None => self.el().icon(mark, 40.0, t.text_dim).show(),
};
self.close();
self.el().w(Length::Grow(1.0)).text(name, t.small, t.text).text_align(Align::Center).clip().show();
self.close();
if files.listing.is_picture(at) {
did.pictures.push(at);
}
state
}
fn nothing_listed(&mut self, files: &Files) -> Did {
let t = self.theme;
let why = match (files.listing.reading(), files.seek.is_empty()) {
(true, _) => files.words.reading,
(false, false) => files.words.none_found,
(false, true) => "",
};
self.column().grow().border(t.line, 1.0).radius(6.0).pad(12.0).align(Align::Center, Align::Center).open();
self.el().text(why, t.small, t.text_dim).show();
self.close();
Did::default()
}
fn file_note(&mut self, files: &Files, wide: f32) {
let t = self.theme;
let (text, color) = match (files.trouble.is_empty(), files.listing.reading()) {
(false, _) => (files.trouble.as_str(), t.red),
(true, true) => (files.words.reading, t.text_dim),
(true, false) => return,
};
self.el().w(Length::Px(wide)).clip().text(text, t.small, color).show();
}
fn file_buttons(&mut self, files: &mut Files, places: bool, wide: f32) -> (Option<Go>, Option<bool>) {
let (t, words) = (self.theme, files.words);
let button = match (files.folders, files.saving) {
(true, _) => words.choose,
(false, true) => words.save,
(false, false) => words.open,
};
let wanted = 3.0 * (t.control + 8.0) + self.text_width(words.cancel, t.font) + self.text_width(button, t.font.bold()) + 60.0;
let row = if wanted > wide { self.wrapping_row().w(Length::Px(wide)).align(Align::End, Align::Center) } else { self.row().align(Align::Start, Align::Center) };
row.key("buttons").gap(8.0).open();
if self.icon_button(NEW_FOLDER, words.new_folder).clicked {
self.new_folder(files);
}
let went = if places { self.places_menu(files) } else { None };
self.view_menu(files);
if wanted <= wide {
self.spacer();
}
let cancel = self.button(words.cancel).clicked;
let pressed = self.primary_button(button).clicked;
self.close();
(went, if cancel { Some(false) } else { pressed.then_some(true) })
}
fn new_folder(&mut self, files: &mut Files) {
(files.making, files.fresh, files.jump) = (Some(files.free_name()), Fresh::NewFolder, Some(0));
self.rerun();
}
fn view_menu(&mut self, files: &mut Files) {
let opens = self.icon_button(VIEW, files.words.view);
if opens.clicked {
self.open_popup(opens.id, opens.rect);
}
if !self.menu(opens.id) {
return;
}
let words = files.words;
if self.menu_check(&mut files.show_hidden, words.hidden).changed {
files.listing.show(&files.seek, files.show_hidden);
}
if files.read.is_some() {
self.menu_check(&mut files.grid, words.grid);
}
self.separator();
let (by, down) = files.table.sort.first().copied().unwrap_or((0, false));
for (column, name) in [words.name, words.size, words.kind, words.date].into_iter().enumerate() {
let mut on = by == column;
if self.menu_check(&mut on, name).changed {
files.table.sort = vec![(column, by == column && !down)];
let (by, down) = files.sorted();
files.listing.sort(by, down);
}
}
self.close();
}
fn ask_to_replace(&mut self, files: &mut Files) -> Option<bool> {
let file = files.asking.clone()?;
let (t, words) = (self.theme, files.words);
let beside = self.dialog_up_to(380.0);
self.el().text(&file.file_name().unwrap_or_default().to_string_lossy(), t.font.bold(), t.text).show();
self.paragraph(words.there_already);
self.row().gap(8.0).align(Align::End, Align::Center).open();
let cancel = self.button(words.cancel);
let replace = self.primary_button(words.replace).clicked;
self.close();
self.close();
if files.fresh == Fresh::Question {
(files.fresh, files.asked_from) = (Fresh::Nothing, self.focus());
self.set_focus(cancel.id);
}
let no = cancel.clicked || beside.clicked || self.key(Key::Escape, Mods::NONE);
if no {
files.asking = None;
self.set_focus(files.asked_from);
}
if no { Some(false) } else { replace.then_some(true) }
}
fn after_list(&mut self, files: &mut Files, did: &Did) {
if let Some(names) = files.picked_names().filter(|_| did.picked) {
files.name = names;
}
if let Some(row) = did.on {
self.keys_on_list(files, row);
}
let Some(read) = files.read.filter(|_| files.grid && !did.pictures.is_empty()) else { return };
let most = (SMALL * self.scale).ceil() as usize;
let small = files.small.get_or_insert_with(Small::default);
for at in did.pictures.iter().copied() {
if small.out < 2 && files.listing.ask_picture(at) {
small.ask(at, files.folder.join(files.listing.name(at)), read, most);
}
}
if files.pictures.len() > KEPT_PICTURES {
let (keep, gone): (Vec<_>, Vec<_>) = files.pictures.drain(..).partition(|(at, ..)| did.pictures.contains(at));
files.pictures = keep;
for (at, picture, _) in gone {
files.listing.forget_picture(at);
self.drop_picture(picture);
}
}
}
fn keys_on_list(&mut self, files: &mut Files, row: usize) {
let count = files.listing.found.len();
let page = 8;
let typed = self.typed();
if !typed.is_empty() {
let (so_far, when) = &mut files.typed;
if self.now.saturating_sub(*when) > TYPED_TOGETHER {
so_far.clear();
}
so_far.push_str(&typed);
*when = self.now;
let first = so_far.chars().next().map(String::from).unwrap_or_default();
let again = so_far.chars().all(|letter| first.starts_with(letter));
let whole = files.listing.starting(so_far, row).filter(|_| so_far.chars().nth(1).is_some());
let found = whole.or_else(|| again.then(|| files.listing.starting(&first, row + 1)).flatten());
self.go_to_row(files, found);
}
let wanted = [(Key::Up, Mods::SHIFT), (Key::Down, Mods::SHIFT), (Key::Home, Mods::NONE), (Key::End, Mods::NONE), (Key::PageUp, Mods::NONE), (Key::PageDown, Mods::NONE)];
let which = wanted.iter().position(|(key, mods)| self.key(*key, *mods));
let to = which.map(|which| match which {
0 => row.saturating_sub(1),
1 => row + 1,
2 => 0,
3 => count.saturating_sub(1),
4 => row.saturating_sub(page),
_ => row + page,
});
match to.map(|to| to.min(count.saturating_sub(1))) {
Some(to) if files.many && which < Some(2) => self.stretch_to_row(files, to),
to => self.go_to_row(files, to),
}
let [one, all] = [(Key::Space, Mods::CTRL), (Key::Char('a'), Mods::CTRL)].map(|(key, mods)| files.many && self.key(key, mods));
if one {
files.listing.click(row, true, false);
}
if all {
files.listing.pick_all();
}
if one || all {
files.name = files.picked_names().unwrap_or_default();
self.rerun();
}
}
fn go_to_row(&mut self, files: &mut Files, row: Option<usize>) {
let Some(row) = row else { return };
let Some(&at) = files.listing.found.get(row) else { return };
files.listing.pick_only(Some(at));
if let Some(names) = files.picked_names() {
files.name = names;
}
files.jump = Some(row);
self.rerun();
}
fn stretch_to_row(&mut self, files: &mut Files, row: usize) {
if row >= files.listing.found.len() {
return;
}
files.listing.click(row, false, true);
files.name = files.picked_names().unwrap_or_default();
files.jump = Some(row);
self.rerun();
}
fn fresh_keyboard(&mut self, files: &mut Files, name: &Response) {
if files.fresh != Fresh::Name {
return;
}
files.fresh = Fresh::Nothing;
files.opened_from = files.opened_from.or(Some(self.focus()));
self.set_focus(name.id);
let stem = files.name.rfind('.').filter(|at| *at > 0).unwrap_or(files.name.len());
self.reader_selects = Some((name.id, [0, stem], false));
}
fn file_keys(&mut self, files: &mut Files, on_list: bool) -> (Option<Go>, Option<bool>) {
if files.asking.is_some() {
return (None, None);
}
files.stale |= self.key(Key::F(5), Mods::NONE);
let went = match () {
_ if self.key(Key::Left, ALT) => Some(Go::Back),
_ if self.key(Key::Right, ALT) => Some(Go::Ahead),
_ if self.key(Key::Up, ALT) || on_list && self.key(Key::Backspace, Mods::NONE) => files.above().map(Go::To),
_ => None,
};
let [path, search, hidden, new] = [('l', Mods::CTRL), ('f', Mods::CTRL), ('h', Mods::CTRL), ('n', CTRL_SHIFT)].map(|(letter, mods)| self.key(Key::Char(letter), mods));
if path {
(files.typing_path, files.searching, files.fresh) = (Some(files.folder.to_string_lossy().into_owned()), false, Fresh::Path);
}
if search {
self.look_for_names(files, true);
}
if hidden {
files.show_hidden = !files.show_hidden;
files.listing.show(&files.seek, files.show_hidden);
}
if new {
self.new_folder(files);
}
if path || search || hidden {
self.rerun();
}
let done = match () {
_ if self.key(Key::Escape, Mods::NONE) => Some(false),
_ if self.key(Key::Enter, Mods::NONE) => Some(true),
_ => None,
};
(went, done)
}
fn take_thing(&mut self, files: &mut Files, at: u32) -> Option<PathBuf> {
let path = files.folder.join(files.listing.name(at));
if files.listing.entry(at).folder() {
files.go(Go::To(path), true);
return None;
}
if !files.many || !files.listing.entry(at).picked() {
files.name = files.listing.name(at).into();
}
files.take()
}
fn ask_system(&mut self, files: &mut Files) -> Option<PathBuf> {
if let Some(answer) = self.file_answer.take() {
self.file_asked = false;
files.shown = false;
let went = answer.as_deref().and_then(|file| if files.folders { Some(file) } else { file.parent() }).map(PathBuf::from);
files.folder = went.unwrap_or(std::mem::take(&mut files.folder));
return answer.and_then(|file| files.answer(vec![file]));
}
if !std::mem::replace(&mut self.file_asked, true) {
crate::platform::hand_file_dialog();
let (folder, name, endings) = (files.folder.clone(), files.name.clone(), files.endings.clone());
self.file_ask = Some(FileAsk { saving: files.saving, folders: files.folders, folder, name, endings, title: files.title() });
}
None
}
pub fn set_system_files(&mut self, can: bool) {
self.system_files = can;
}
pub fn take_file_ask(&mut self) -> Option<FileAsk> {
self.file_ask.take()
}
pub fn file_answered(&mut self, file: Option<PathBuf>) {
self.file_answer = Some(file);
}
pub(crate) fn forget_answer(&mut self) {
if self.file_answer.take().is_some() {
self.file_asked = false;
}
}
}
fn crumb(folder: &Path) -> String {
let name = folder.file_name().map_or(folder.as_os_str(), |name| name);
let name = name.to_string_lossy();
if cfg!(windows) && name.len() > 1 { name.trim_end_matches('\\').to_string() } else { name.into_owned() }
}
fn size(written: &mut String, bytes: u64) {
const KB: u64 = 1024;
let _ = match bytes {
bytes if bytes < KB => write!(written, "{bytes} B"),
bytes if bytes < KB * KB => write!(written, "{} KB", bytes.div_ceil(KB)),
bytes if bytes < KB * KB * KB => write!(written, "{:.1} MB", bytes as f64 / (KB * KB) as f64),
bytes => write!(written, "{:.1} GB", bytes as f64 / (KB * KB * KB) as f64),
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_librarys_own_dialog_is_handed_over_only_where_it_may_show() {
let mut system = Files::of_the_system();
assert_eq!(system.own.is_none(), cfg!(windows));
assert!(Files::default().own.is_some() && Files { system: true, ..Default::default() }.own.is_some());
let mut many = Files::of_the_system();
many.pick_many(".");
assert!(many.own.is_some());
let mut windowed = Ui::new(Box::new(crate::text::BuiltInFont), Box::new(crate::platform::LocalClipboard::default()));
windowed.set_system_files(true);
system.pick_folder(".");
let mut got = Vec::new();
windowed.run(&mut |ui| got.extend(ui.file_dialog(&mut system)));
assert!(windowed.take_file_ask().is_some_and(|ask| ask.folders) && windowed.take_file_ask().is_none());
let folder = std::path::absolute(".").unwrap();
windowed.file_answered(Some(folder.clone()));
windowed.run(&mut |ui| got.extend(ui.file_dialog(&mut system)));
windowed.run(&mut |ui| got.extend(ui.file_dialog(&mut system)));
assert_eq!((got, system.shown, system.chosen.clone()), (vec![folder.clone()], false, vec![folder]));
assert!(system.places.is_empty() && system.drives.is_empty());
if cfg!(windows) {
let mut alone = Ui::new(Box::new(crate::text::BuiltInFont), Box::new(crate::platform::LocalClipboard::default()));
system.pick(".");
let mut answers = 0;
alone.run(&mut |ui| answers += ui.file_dialog(&mut system).is_some() as u32);
assert_eq!((answers, system.shown, alone.take_file_ask().is_none()), (0, false, true));
}
}
#[test]
fn sizes_are_written_the_way_people_read_them() {
let written = |bytes: u64| {
let mut text = String::new();
size(&mut text, bytes);
text
};
assert_eq!([0, 1023, 1024, 1025, 5 << 20, 3 << 30].map(written), ["0 B", "1023 B", "1 KB", "2 KB", "5.0 MB", "3.0 GB"]);
assert_eq!(crumb(Path::new("/")), "/");
#[cfg(windows)]
assert_eq!((crumb(Path::new("C:\\")), crumb(Path::new("C:\\Users"))), ("C:".to_string(), "Users".to_string()));
}
#[test]
fn names_in_the_box_are_whole_paths_and_get_the_ending_asked_for() {
let folder = std::env::temp_dir().join(format!("taut-named-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let mut files = Files { folder: folder.clone(), ..Default::default() };
files.name = "\"one.txt\" \"two words.txt\"".into();
assert_eq!(files.named(), [folder.join("one.txt"), folder.join("two words.txt")]);
files.name = " notes.txt ".into();
assert_eq!(files.named(), [folder.join("notes.txt")]);
files.save(&folder, "report");
files.only(&[".md", ".txt"]);
assert_eq!(files.save_as(folder.join("report")), Some(folder.join("report.md")));
files.save(&folder, "");
assert_eq!(files.save_as(folder.join("Report.TXT")), Some(folder.join("Report.TXT")));
assert_eq!(files.recent, std::slice::from_ref(&folder), "the folder is the first of the recent ones, once");
std::fs::remove_dir_all(folder).unwrap();
}
}