files-w1: net change of 1 commits

- files-w1: written from its sheet
This commit is contained in:
bflatastic
2026-11-21 21:28:01 +07:00
parent 2cdb9ee526
commit d1fbb63a56
10 changed files with 271 additions and 232 deletions
+9 -6
View File
@@ -15,13 +15,14 @@ Browse button).
`craft_dialogs::save` is File › Save and Save As with their guards, on the file service's pickers and
craft-platform's `FileWatch`. It has no egui dependency: `SaveFlow::start` takes a `SaveDocument`
and a `SaveTarget` (`InPlace`, `As`, `Copy`) and answers a `SaveStep` the app acts on: `Picking`,
`AskChangedOnDisk`, `Write`, `Cancelled` or `Busy` (one save runs at a time per flow). The app
serializes and writes, then reports with `written` (which records the new file version unless the
target is a copy) or `failed`.
`AskChangedOnDisk`, `Write`, `Cancelled` or `Busy` (one save runs at a time per flow). `Write`
carries the index of the file type picked in the panel (`file_type`, `None` for the document's own
file). The app serializes and writes, then reports with `written` (which records the new file
version unless the target is a copy) or `failed`.
- A document without a file, Save As, and an email attachment's temporary copy (`is_mail_temp_copy`)
open the save picker in the document's folder (`save_dialog_folder`) with the document's name
and the extension suggested.
open the save picker in the document's folder (`save_dialog_folder`, or `SaveDocument::directory`
when the app sets one) with the document's name and the extension suggested.
- A save onto an existing file that changed on disk since it was opened or last saved asks first.
The app answers with `replace`, `save_elsewhere` (the picker again, keeping both files) or
`cancel`. The check also runs when a picked path is the document's own file, for every target.
@@ -48,7 +49,8 @@ pub struct Filter { pub name: String, pub extensions: Vec<String> }
pub struct Message { pub level: MessageLevel, pub title: String, pub description: String,
pub buttons: MessageButtons }
pub enum Request { File(FileDialog), Message(Message) }
pub enum Answer { Cancelled, Paths(Vec<PathBuf>), Message(MessageResult), Unavailable(String) }
pub enum Answer { Cancelled, Paths(Vec<PathBuf>), Saved { path: PathBuf, filter: Option<usize> },
Message(MessageResult), Unavailable(String) }
impl<T> Dialogs<T> {
pub fn new(wake: Wake) -> Self;
@@ -80,6 +82,7 @@ self.dialogs.ask(FileDialog::open().filter("PDF", &["pdf"]), Then::Open);
for (then, answer) in self.dialogs.take_answers() {
match answer {
Answer::Paths(paths) => self.run(then, paths),
Answer::Saved { path, .. } => self.run(then, vec![path]),
Answer::Unavailable(why) => self.report_error(why),
Answer::Cancelled | Answer::Message(_) => {}
}
+1 -1
View File
@@ -218,7 +218,7 @@ pub enum Request {
pub enum Answer {
/// The user closed a file dialog without choosing.
Cancelled,
/// The chosen files, folder or save path.
/// The chosen files or folder.
Paths(Vec<PathBuf>),
/// A Save panel's answer: the name as typed and the file type picked, when the panel reports it (the portal's
/// current filter; rfd reports `None`).
+4 -3
View File
@@ -74,6 +74,7 @@ fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Optio
// The worker first, so a dialog once shown always has somewhere to answer.
let worker = worker(reply)?;
let one = |file: Option<rfd::FileHandle>| file.map_or(Answer::Cancelled, |f| Answer::Paths(vec![f.path().to_path_buf()]));
let saved = |file: Option<rfd::FileHandle>| file.map_or(Answer::Cancelled, |f| Answer::Saved { path: f.path().to_path_buf(), filter: None });
let pending: Pending = match d.kind {
Kind::Open { multiple: false } => {
let picked = dialog.pick_file();
@@ -100,11 +101,11 @@ fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Optio
let request = crate::portal::SaveRequest::new(&d, parent_id);
Box::pin(async move {
match crate::portal::save_as(request) {
Ok(Some((path, _))) => Answer::Paths(vec![path]), // P3(files-w1): fl.F8
Ok(Some((path, filter))) => Answer::Saved { path, filter },
Ok(None) => Answer::Cancelled,
Err(e) => {
log::info!("portal save dialog unavailable ({e}), using rfd");
one(dialog.save_file().await)
saved(dialog.save_file().await)
}
}
})
@@ -112,7 +113,7 @@ fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Optio
#[cfg(not(target_os = "linux"))]
Kind::Save => {
let picked = dialog.save_file();
Box::pin(async move { one(picked.await) })
Box::pin(async move { saved(picked.await) })
}
};
// The worker can't be gone: it waits for this. If it were, its reply answers Unavailable.
+13 -75
View File
@@ -3,9 +3,10 @@
//! The GTK file chooser behind the portal keeps the typed name when the user picks another file
//! type, and rfd 0.17 reads only the file name from the portal's answer, so `image.psd` with PNG
//! picked came back as `image.psd`. The answer does say which type was picked (`current_filter`),
//! so Save asks the portal itself and gives a name the dialog left alone that type's extension
//! ([`with_chosen_type`]). rfd stays the fallback (zenity, or no portal), and this can go once an
//! rfd release reads the picked type (PolyMeilex/rfd#341).
//! so Save asks the portal itself and reports that type with the typed path; the service gives a
//! name the dialog left alone the type's extension ([`crate::service::with_chosen_type`]). rfd stays
//! the fallback (zenity, or no portal), and this can go once an rfd release reads the picked type
//! (PolyMeilex/rfd#341).
//!
//! The dialog is attached to the window on X11. On Wayland it has no parent: naming the window to
//! the portal needs an xdg-foreign handle, which takes `unsafe` code the workspace forbids.
@@ -16,6 +17,7 @@ use std::path::{Path, PathBuf};
use raw_window_handle::RawWindowHandle;
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
use crate::service::normal;
use crate::{FileDialog, Filter};
/// A Save dialog to show.
@@ -26,9 +28,7 @@ pub(crate) struct SaveRequest {
/// The name the dialog shows: the stem of the suggested file (`test`), see
/// [`crate::service::dialog_file_name`].
pub name: Option<String>,
/// The suggested file's name (`test.psd`): a name that comes back with its extension still
/// takes the extension of the type picked ([`with_chosen_type`]).
pub suggested: Option<String>,
/// The folder the dialog opens in.
pub folder: Option<PathBuf>,
/// The file types offered.
@@ -49,7 +49,6 @@ impl SaveRequest {
Self {
parent,
name: dialog.file_name.as_deref().and_then(|n| crate::service::dialog_file_name(n, true)),
suggested,
folder: dialog.directory.clone(),
filters: dialog.filters.clone(),
current: current.filter(|_| !dialog.filters.is_empty()),
@@ -64,10 +63,6 @@ struct Saved {
filter: Option<String>,
}
/// An extension as compared: without the dot, in lower case.
fn normal(ext: &str) -> String {
ext.trim_start_matches('.').to_ascii_lowercase()
}
/// The portal's parent window identifier for `window`: `x11:<xid>` on X11, empty elsewhere.
// pc: apps/photocraft/src/portal_save.rs:47 parent_id
@@ -192,72 +187,15 @@ fn file_uri_path(uri: &str) -> Option<PathBuf> {
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
}
/// Which file type's extensions belong on the name the dialog returned: the one it reported, or,
/// when the dialog offered only one type, that one. It reports no pick then, and the name it was
/// given is the stem, so a bare `Swatches` has to come back as `Swatches.aco`. `None` when the
/// answer names no type this dialog offered.
// pc: apps/photocraft/src/portal_save.rs:163 chosen_type
fn chosen_type(filters: &[Filter], picked: Option<usize>) -> Option<usize> {
match picked {
Some(i) if i < filters.len() => Some(i),
None if filters.len() == 1 => Some(0),
_ => None,
}
}
/// `path` with the extension of the file type picked in the Save dialog (`chosen`, its extensions
/// without the dot), where the dialog left the name alone: the format follows the extension, and
/// the GTK file chooser keeps the typed name when another type is picked. Only a name that still
/// has the extension the dialog opened with (`opened_with`, `Untitled-1.psd` with PNG picked) or
/// none gets the type's first extension, as PolyMeilex/rfd#341 does. An extension of the picked
/// type stays (`.psb` for PSD), and so does one that any of the request's `filters` lists
/// (`art.png` with the PSD type untouched): the user typed a type the app saves. Any other
/// extension (`scan.2024`) is part of the name, and the type's extension is added after it. With
/// no type picked the path is as typed. Extensions compare in any letter case.
// pc: apps/photocraft/src/services.rs:161 with_chosen_type
pub(crate) fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &[String], filters: &[Filter]) -> PathBuf {
let Some(first) = chosen.first() else { return path.to_path_buf() };
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let opened_ext = opened_with.and_then(|n| Path::new(n).extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let first = normal(first);
let lists = |ext: &str| filters.iter().any(|f| f.extensions.iter().any(|e| normal(e) == ext));
match ext {
Some(ext) if chosen.iter().any(|e| normal(e) == ext) => path.to_path_buf(),
Some(ext) if opened_ext.as_ref() == Some(&ext) => path.with_extension(first),
Some(ext) if lists(&ext) => path.to_path_buf(),
_ => {
let mut name = path.as_os_str().to_owned();
name.push(".");
name.push(first);
PathBuf::from(name)
}
}
}
/// Save on Linux: the portal's dialog, with the name given the extension of the file type picked.
/// When that changes the name to one that already exists, the dialog opens again under the new
/// name, so the portal asks before replacing it (it asked only about the typed name). Connects to
/// the session bus; `Err` when the portal can't be reached, and the caller shows rfd's dialog.
/// Save on Linux: the portal's dialog, answering the typed path and the index of the file type
/// picked (into `req.filters`). The service settles the name from them. Connects to the session
/// bus; `Err` when the portal can't be reached, and the caller shows rfd's dialog.
// pc: apps/photocraft/src/portal_save.rs:174 save_as, services.rs:244-280
pub(crate) fn save_as(mut req: SaveRequest) -> Result<Option<(PathBuf, Option<usize>)>, String> {
pub(crate) fn save_as(req: SaveRequest) -> Result<Option<(PathBuf, Option<usize>)>, String> {
let conn = zbus::blocking::connection::Builder::session().and_then(|b| b.build()).map_err(|e| e.to_string())?;
loop {
let Some(saved) = save_file(&conn, &req)? else { return Ok(None) };
let picked = saved.filter.as_deref().and_then(|label| req.filters.iter().position(|f| f.name == label));
// A typed extension is the user's own: `with_chosen_type` keeps one it recognises.
let exts: &[String] = match chosen_type(&req.filters, picked) {
Some(i) => &req.filters[i].extensions,
None => &[],
};
let path = with_chosen_type(&saved.path, req.suggested.as_deref(), exts, &req.filters);
if path == saved.path || !path.exists() {
return Ok(Some((path, picked))); // P3(files-w1): fl.F8
}
req.name = path.file_name().map(|n| n.to_string_lossy().into_owned());
req.suggested = req.name.clone();
req.folder = path.parent().map(Path::to_path_buf);
req.current = picked;
}
let Some(saved) = save_file(&conn, &req)? else { return Ok(None) };
let picked = saved.filter.as_deref().and_then(|label| req.filters.iter().position(|f| f.name == label));
Ok(Some((saved.path, picked)))
}
#[cfg(test)]
-27
View File
@@ -9,30 +9,3 @@ fn file_uris_become_local_paths() {
assert_eq!(file_uri_path("sftp://host/x.png"), None);
assert_eq!(file_uri_path("file://host/x.png"), None);
}
/// The name the Save dialog's answer ends up with: the picked type (`picked`, an index into `filters`) decides the
/// extension a bare name takes, and an extension the user typed wins unless it is the one the dialog opened with.
#[trial]
fn the_picked_file_type_gives_a_bare_name_its_extension_and_a_typed_extension_wins() {
let two = [Filter::new("Photoshop", &["psd", "psb"]), Filter::new("PNG", &["png"])];
let only = [Filter::new("Swatches", &["aco"])];
// (path, opened with, filters, picked type, expected path)
type Case<'a> = (&'a str, Option<&'a str>, &'a [Filter], Option<usize>, &'a str);
let table: [Case; 8] = [
("/s/Untitled", Some("Untitled.psd"), &two, Some(1), "/s/Untitled.png"),
("/s/Untitled.psd", Some("Untitled.psd"), &two, Some(1), "/s/Untitled.png"),
("/s/art.png", Some("art.psd"), &two, Some(0), "/s/art.png"),
("/s/art.PSB", Some("art.psd"), &two, Some(0), "/s/art.PSB"),
("/s/scan.2024", None, &two, Some(1), "/s/scan.2024.png"),
("/s/Swatches", None, &only, None, "/s/Swatches.aco"),
("/s/Swatches.aco", None, &only, None, "/s/Swatches.aco"),
("/s/free", None, &two, None, "/s/free"),
];
for (path, opened, filters, picked, expected) in table {
let chosen: &[String] = match chosen_type(filters, picked) {
Some(at) => &filters[at].extensions,
None => &[],
};
assert_eq!(with_chosen_type(Path::new(path), opened, chosen, filters), PathBuf::from(expected), "{path} with type {picked:?}");
}
}
+9 -8
View File
@@ -5,7 +5,8 @@
//! (on a job when large) and reports back. One save runs at a time per flow. The guards:
//!
//! - **No file, or Save As**: the save picker opens in the document's own folder
//! ([`save_dialog_folder`]), with the document's name and extension suggested. The file
//! ([`save_dialog_folder`], or [`SaveDocument::directory`] when the app names one), with the
//! document's name and extension suggested. The file
//! service applies the extension policy and asks about replacing a file the panel didn't ask
//! about.
//! - **An email attachment's temporary copy** ([`is_mail_temp_copy`]): Save asks where to keep
@@ -24,7 +25,7 @@ use std::hash::Hash;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use craft_host::{FileFilter, Files, PickId, PickRequest};
use craft_host::{FileFilter, Files, PickId, PickRequest, Picked};
use craft_platform::PlatformText;
use craft_platform::watch::FileWatch;
@@ -115,7 +116,7 @@ enum Pending<D> {
/// ```ignore
/// // File › Save
/// match saves.start(host.files(), &watch, document(doc), SaveTarget::InPlace) {
/// SaveStep::Write { key, path, target, .. } => write_on_a_job(key, path, target),
/// SaveStep::Write { key, path, target, file_type } => write_on_a_job(key, path, target, file_type),
/// SaveStep::AskChangedOnDisk { key, path } => { dialogs.open(StandardPrompt::changed_on_disk(name(key)).tag(key)); }
/// SaveStep::Busy => status(SAVE_IN_PROGRESS),
/// SaveStep::Picking | SaveStep::Cancelled { .. } => {}
@@ -168,12 +169,12 @@ impl<D: Clone + Eq + Hash + Send + 'static> SaveFlow<D> {
let Some(Pending::Picking { ticket, .. }) = &self.pending else { return None };
let picked = files.take_answer(*ticket)?;
let Some(Pending::Picking { document, target, .. }) = self.pending.take() else { return None };
let Some(path) = picked.first_path() else { return Some(SaveStep::Cancelled { key: document.key }) };
let Picked::Saved { path, file_type } = picked else { return Some(SaveStep::Cancelled { key: document.key }) };
if document.path.as_deref() == Some(path.as_path()) {
return Some(self.confirm(watch, document, target, path));
}
self.pending = Some(Pending::Writing { key: document.key.clone(), target });
Some(SaveStep::Write { key: document.key, path, target, file_type: None }) // P3(files-w1): fl.F10
Some(SaveStep::Write { key: document.key, path, target, file_type })
}
/// The changed-on-disk question's Replace: write over the changed file. [`SaveStep::Busy`]
@@ -182,7 +183,7 @@ impl<D: Clone + Eq + Hash + Send + 'static> SaveFlow<D> {
pub fn replace(&mut self) -> SaveStep<D> {
let Some(Pending::Asking { document, target, path }) = self.pending.take() else { return SaveStep::Busy };
self.pending = Some(Pending::Writing { key: document.key.clone(), target });
SaveStep::Write { key: document.key, path, target, file_type: None } // P3(files-w1): fl.F10
SaveStep::Write { key: document.key, path, target, file_type: None }
}
/// The changed-on-disk question's Save As: leave the file on disk as it is and ask where to
@@ -252,14 +253,14 @@ impl<D: Clone + Eq + Hash + Send + 'static> SaveFlow<D> {
return SaveStep::AskChangedOnDisk { key, path };
}
self.pending = Some(Pending::Writing { key: document.key.clone(), target });
SaveStep::Write { key: document.key, path, target, file_type: None } // P3(files-w1): fl.F10
SaveStep::Write { key: document.key, path, target, file_type: None }
}
fn open_picker(&mut self, files: &dyn Files, document: SaveDocument<D>, target: SaveTarget) -> SaveStep<D> {
let mut request =
PickRequest::save(document.purpose.clone()).file_name(suggested_name(&document)).suggested_extension(document.extension.clone());
request.filters = document.filters.clone();
request.directory = save_dialog_folder(document.path.as_deref());
request.directory = document.directory.clone().or_else(|| save_dialog_folder(document.path.as_deref()));
let ticket = files.pick(request);
self.pending = Some(Pending::Picking { document, target, ticket });
SaveStep::Picking
+14 -13
View File
@@ -47,11 +47,6 @@ impl Files for ScriptedFiles {
self.answers.lock().unwrap().remove(&id);
}
fn pick_pending(&self) -> bool {
false
}
// P3(files-w1): fl.F2
fn pending_pick(&self) -> Option<craft_host::PendingPick> {
None
}
@@ -78,7 +73,7 @@ fn document(path: Option<&Path>, name: &str) -> SaveDocument<u32> {
filters: vec![FileFilter::new("PDF", &["pdf"])],
purpose: "document".into(),
saved: None,
directory: None, // P3(files-w1): fl.F11
directory: None,
}
}
@@ -106,11 +101,11 @@ fn a_file_changed_on_disk_is_asked_about_once() {
assert_eq!(flow.start(&files, &watch, document(Some(&file), "a.pdf"), SaveTarget::InPlace), ask);
assert!(flow.is_busy());
assert_eq!(flow.replace(), SaveStep::Write { key: 7, path: file.clone(), target: SaveTarget::InPlace, file_type: None }); // P3(files-w1): fl.F10
assert_eq!(flow.replace(), SaveStep::Write { key: 7, path: file.clone(), target: SaveTarget::InPlace, file_type: None });
flow.written(&mut watch, 7, &file);
assert_eq!(
flow.start(&files, &watch, document(Some(&file), "a.pdf"), SaveTarget::InPlace),
SaveStep::Write { key: 7, path: file.clone(), target: SaveTarget::InPlace, file_type: None }, // P3(files-w1): fl.F10
SaveStep::Write { key: 7, path: file.clone(), target: SaveTarget::InPlace, file_type: None },
"the app's own write is no change on disk"
);
flow.failed(&7);
@@ -121,13 +116,19 @@ fn a_file_changed_on_disk_is_asked_about_once() {
let request = files.last_request();
assert_eq!(request.directory.as_deref(), Some(dir.as_path()));
let elsewhere = dir.join("b.pdf");
files.answer(files.last_ticket(), Picked::Paths(vec![elsewhere.clone()]));
assert_eq!(flow.take_pick(&files, &watch), Some(SaveStep::Write { key: 7, path: elsewhere, target: SaveTarget::As, file_type: None })); // P3(files-w1): fl.F10
files.answer(files.last_ticket(), Picked::Saved { path: elsewhere.clone(), file_type: Some(0) });
assert_eq!(flow.take_pick(&files, &watch), Some(SaveStep::Write { key: 7, path: elsewhere, target: SaveTarget::As, file_type: Some(0) }));
flow.failed(&7);
assert_eq!(flow.start(&files, &watch, document(Some(&file), "a.pdf"), SaveTarget::InPlace), ask);
assert_eq!(flow.cancel(&files), Some(SaveStep::Cancelled { key: 7 }));
assert!(!flow.is_busy());
let mut named = document(None, "C");
named.directory = Some(dir.join("exports"));
assert_eq!(flow.start(&files, &watch, named, SaveTarget::As), SaveStep::Picking);
assert_eq!(files.last_request().directory, Some(dir.join("exports")), "the document's directory starts the picker");
assert_eq!(flow.cancel(&files), Some(SaveStep::Cancelled { key: 7 }));
std::fs::remove_dir_all(dir).ok();
}
@@ -137,7 +138,7 @@ fn a_late_write_does_not_free_another_save() {
let (files, mut watch, mut flow) = (ScriptedFiles::default(), watch(), SaveFlow::new());
assert_eq!(
flow.start(&files, &watch, document(Some(Path::new("/x/a.pdf")), "a.pdf"), SaveTarget::InPlace),
SaveStep::Write { key: 7, path: PathBuf::from("/x/a.pdf"), target: SaveTarget::InPlace, file_type: None } // P3(files-w1): fl.F10
SaveStep::Write { key: 7, path: PathBuf::from("/x/a.pdf"), target: SaveTarget::InPlace, file_type: None }
);
assert_eq!(flow.cancel(&files), Some(SaveStep::Cancelled { key: 7 }));
let mut other = document(None, "B");
@@ -147,11 +148,11 @@ fn a_late_write_does_not_free_another_save() {
flow.written(&mut watch, 7, Path::new("/x/a.pdf"));
assert!(flow.is_busy(), "the pick of the other document is still open");
files.answer(ticket, Picked::Paths(vec![PathBuf::from("/x/b.pdf")]));
files.answer(ticket, Picked::Saved { path: PathBuf::from("/x/b.pdf"), file_type: None });
assert_eq!(
flow.take_pick(&files, &watch),
Some(SaveStep::Write { key: 8, path: PathBuf::from("/x/b.pdf"), target: SaveTarget::As, file_type: None })
); // P3(files-w1): fl.F10
);
flow.written(&mut watch, 8, Path::new("/x/b.pdf"));
assert!(!flow.is_busy());
}
+211 -75
View File
@@ -12,15 +12,17 @@
//! OS panel did not ask about gets the Replace question (PhotoCraft `file_dialog.rs:193
//! replaces_unasked`), a native message box from [`FilePanels::pump`] or, with the `ui` feature, a
//! prompt on the app's `DialogHost` from `FilePanels::pump_with`; a typed name without an extension gets the suggested one and a new file's
//! uppercase extension is lowercased, while an existing file keeps its spelling (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the two
//! steps are separate settings of the [`ExtensionPolicy`].
//! uppercase extension is lowercased, while an existing file keeps its spelling (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the
//! steps are separate settings of the [`ExtensionPolicy`]. A name the panel left alone takes the
//! extension of the file type picked in the panel ([`with_chosen_type`]): the GTK file chooser keeps
//! the typed name when another type is picked, and the format follows the extension.
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use craft_host::{FileError, Files, PickAnswer, PickId, PickRequest, Wake};
use craft_host::{FileError, FileFilter, Files, PendingPick, PickAnswer, PickId, PickRequest, Wake};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use craft_host::{PickKind, Picked};
@@ -135,20 +137,52 @@ impl Default for ExtensionPolicy {
}
}
/// `path` with the extension of the file type picked in the Save panel (`chosen`, its extensions without the dot),
/// where the panel left the name alone; an extension of the picked type, or one that any of `filters` lists, stays.
#[allow(dead_code)] // P3(files-w1): fl.F9
pub(crate) fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &[String], filters: &[Filter]) -> PathBuf {
let _ = (path, opened_with, chosen, filters);
todo!("fl.F9")
/// An extension as compared: without the dot, in lower case.
pub(crate) fn normal(ext: &str) -> String {
ext.trim_start_matches('.').to_ascii_lowercase()
}
/// Which file type's extensions belong on the name the panel returned: the one it reported, or the only one it
/// offered; `None` when the answer names no type the panel offered.
#[allow(dead_code)] // P3(files-w1): fl.F9
fn chosen_type(filters: &[Filter], picked: Option<usize>) -> Option<usize> {
let _ = (filters, picked);
todo!("fl.F9")
/// `path` with the extension of the file type picked in the Save panel (`chosen`, its extensions
/// without the dot), where the panel left the name alone: the format follows the extension, and
/// the GTK file chooser keeps the typed name when another type is picked. Only a name that still
/// has the extension the panel opened with (`opened_with`, `Untitled-1.psd` with PNG picked) or
/// none gets the type's first extension, as PolyMeilex/rfd#341 does. An extension of the picked
/// type stays (`.psb` for PSD), and so does one that any of the request's `filters` lists
/// (`art.png` with the PSD type untouched): the user typed a type the app saves. Any other
/// extension (`scan.2024`) is part of the name, and the type's extension is added after it. With
/// no type picked the path is as typed. Extensions compare in any letter case.
// PLAN: fl.F9 says `&[Filter]`; `settled_save_path` holds a `PickRequest`, whose filters are `FileFilter`s
// pc: apps/photocraft/src/services.rs:161 with_chosen_type
pub(crate) fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &[String], filters: &[FileFilter]) -> PathBuf {
let Some(first) = chosen.first() else { return path.to_path_buf() };
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let opened_ext = opened_with.and_then(|n| Path::new(n).extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let first = normal(first);
let lists = |ext: &str| filters.iter().any(|f| f.extensions.iter().any(|e| normal(e) == ext));
match ext {
Some(ext) if chosen.iter().any(|e| normal(e) == ext) => path.to_path_buf(),
Some(ext) if opened_ext.as_ref() == Some(&ext) => path.with_extension(first),
Some(ext) if lists(&ext) => path.to_path_buf(),
_ => {
let mut name = path.as_os_str().to_owned();
name.push(".");
name.push(first);
PathBuf::from(name)
}
}
}
/// Which file type's extensions belong on the name the panel returned: the one it reported, or,
/// when the panel offered only one type, that one. It reports no pick then, and the name it was
/// given is the stem, so a bare `Swatches` has to come back as `Swatches.aco`. `None` when the
/// answer names no type the panel offered.
// pc: apps/photocraft/src/portal_save.rs:163 chosen_type
fn chosen_type(filters: &[FileFilter], picked: Option<usize>) -> Option<usize> {
match picked {
Some(i) if i < filters.len() => Some(i),
None if filters.len() == 1 => Some(0),
_ => None,
}
}
/// Where a Save answer that would overwrite goes next: the panel already asked (macOS, Windows,
@@ -167,6 +201,9 @@ pub enum ReplaceGuard {
/// answer (the replace question).
struct Pending {
request: PickRequest,
/// The owner dropped the ticket while its panel may still be on screen: the entry stays so the
/// window stays held, and the panel's answer is dropped.
forgotten: bool,
/// The Save path waiting on the replace question's answer.
awaiting_replace: Option<ReplaceQuestion>,
}
@@ -177,7 +214,7 @@ struct Pending {
struct ReplaceQuestion {
answered: PathBuf,
settled: PathBuf,
#[allow(dead_code)] // P3(files-w1): fl.F7
/// The file type the panel reported, handed back with the settled path.
file_type: Option<usize>,
}
@@ -219,8 +256,6 @@ struct Inner {
pending: HashMap<PickId, Pending>,
answered: VecDeque<PickAnswer>,
last_folder: HashMap<String, PathBuf>,
/// A panel is on screen or queued (mirrored from the panels each pump).
panel_busy: bool,
}
impl FileService {
@@ -233,7 +268,6 @@ impl FileService {
pending: HashMap::new(),
answered: VecDeque::new(),
last_folder: HashMap::new(),
panel_busy: false,
}));
let (to_panels, requests) = std::sync::mpsc::channel();
let panels = FilePanels {
@@ -335,7 +369,6 @@ impl FilePanels {
}
}
}
self.mark_busy();
}
/// [`pump`](FilePanels::pump) with the replace question on the app's own dialog host: the
@@ -363,7 +396,6 @@ impl FilePanels {
}
}
self.open_prompts(dialogs);
self.mark_busy();
}
/// The dialog ids of the Replace questions open on the app's dialog host, for an app that lists
@@ -425,9 +457,6 @@ impl FilePanels {
}
}
fn mark_busy(&self) {
lock(&self.inner).panel_busy = self.dialogs.is_open() || self.dialogs.queued() > 0;
}
/// Translates a request into the panel builder: kind, title, filters, `request.directory`
/// (else the remembered folder, else `request.default_directory`) and the suggested name with
@@ -450,7 +479,9 @@ impl FilePanels {
dialog
}
/// The saved path after the extension policy: `"Photo"` becomes `"Photo.png"` with a
/// The saved path after the extension policy. First a name the panel left alone takes the
/// extension of the picked type (`file_type`, an index into `request.filters`; when
/// `picked_type`). Then `"Photo"` becomes `"Photo.png"` with a
/// suggested `png` (when `add_suggested`); `"Photo.PNG"` becomes `"Photo.png"` (when
/// `lowercase`) unless a file named `"Photo.PNG"` already exists; a path with another known
/// extension is kept.
@@ -460,24 +491,28 @@ impl FilePanels {
/// letter case apart is a second file, so the one the user picked would be left unchanged.
// pc: crates/ui-egui/src/file_dialog.rs:210 lowercased_extension, :365 saved_path
pub fn settled_save_path(policy: ExtensionPolicy, answered: &Path, request: &PickRequest, file_type: Option<usize>) -> PathBuf {
// P3(files-w1): fl.F7
let typed = if policy.picked_type {
let chosen = chosen_type(&request.filters, file_type).and_then(|at| request.filters.get(at)).map_or(&[][..], |f| f.extensions.as_slice());
with_chosen_type(answered, request.file_name.as_deref(), chosen, &request.filters)
} else {
answered.to_path_buf()
};
let suggested = request.suggested_extension.as_deref();
let _ = file_type;
match answered.extension().and_then(|e| e.to_str()) {
Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) && !answered.exists() => {
answered.with_extension(ext.to_ascii_lowercase())
match typed.extension().and_then(|e| e.to_str()) {
Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) && !typed.exists() => {
typed.with_extension(ext.to_ascii_lowercase())
}
Some(_) => answered.to_path_buf(),
Some(_) => typed,
None => match suggested {
Some(ext) if policy.add_suggested => answered.with_extension(ext),
_ => answered.to_path_buf(),
Some(ext) if policy.add_suggested => typed.with_extension(ext),
_ => typed,
},
}
}
/// Whether the settled path names an existing file the panel did not ask about: the panel
/// asked when the settled path equals the answered path, so only an extension change can
/// make a new collision.
/// asked when the settled path equals the answered path, so only an extension change (the
/// policy's or the picked type's) can make a new collision.
// pc: crates/ui-egui/src/file_dialog.rs:193 replaces_unasked
pub fn replaces_unasked(answered: &Path, settled: &Path) -> bool {
answered != settled && settled.exists() && !same_entry(answered, settled)
@@ -496,34 +531,36 @@ impl FilePanels {
}
}
/// Turns a panel answer into the pick's answer: `Cancelled` stays, `Paths` for Save go through
/// Turns a panel answer into the pick's answer: `Cancelled` stays, `Saved` goes through
/// the policy and guard, `Unavailable` stays `Unavailable` with the cause, and a `Cancelled` on a
/// system where the probe found no dialog backend becomes `Unavailable` with the probe's
/// cause. A Save that needs the replace
/// question stays pending and returns the question for the caller to ask.
/// question stays pending and returns the question for the caller to ask. The answer of a
/// forgotten pick is dropped.
fn finish(&mut self, id: PickId, answer: Answer) -> Option<ReplaceQuestion> {
let pending = lock(&self.inner).pending.remove(&id)?;
if pending.forgotten {
return None;
}
let picked = match (answer, pending.awaiting_replace) {
(Answer::Message(result), Some(question)) => {
let replace =
matches!(&result, MessageResult::Ok) || matches!(&result, MessageResult::Custom(label) if *label == self.replace_words.replace);
if replace { Picked::Paths(vec![question.settled]) } else { Picked::Cancelled }
if replace { Picked::Saved { path: question.settled, file_type: question.file_type } } else { Picked::Cancelled }
}
(Answer::Saved { .. }, _) => todo!("fl.F7"),
(Answer::Paths(paths), _) if paths.is_empty() => Picked::Cancelled,
(Answer::Paths(mut paths), _) => {
if pending.request.kind == PickKind::Save {
let answered = paths.swap_remove(0);
let settled = Self::settled_save_path(self.extension_policy, &answered, &pending.request, None); // P3(files-w1): fl.F7
if self.replace_guard == ReplaceGuard::AskWhenUnasked && Self::replaces_unasked(&answered, &settled) {
let question = ReplaceQuestion { answered, settled, file_type: None };
lock(&self.inner).pending.insert(id, Pending { request: pending.request, awaiting_replace: Some(question.clone()) });
return Some(question);
}
paths = vec![settled];
(Answer::Saved { path, filter }, _) => {
let settled = Self::settled_save_path(self.extension_policy, &path, &pending.request, filter);
if self.replace_guard == ReplaceGuard::AskWhenUnasked && Self::replaces_unasked(&path, &settled) {
let question = ReplaceQuestion { answered: path, settled, file_type: filter };
lock(&self.inner)
.pending
.insert(id, Pending { request: pending.request, awaiting_replace: Some(question.clone()), forgotten: false });
return Some(question);
}
Picked::Paths(paths)
Picked::Saved { path: settled, file_type: filter }
}
(Answer::Paths(paths), _) if paths.is_empty() => Picked::Cancelled,
(Answer::Paths(paths), _) => Picked::Paths(paths),
(Answer::Unavailable(why), _) => Picked::Unavailable(why),
// A panel that answers nothing on a system without a dialog backend did not get
// cancelled; the probe knows why.
@@ -538,15 +575,16 @@ impl FilePanels {
/// `Cancelled` otherwise. A forgotten pick has nothing to settle.
#[cfg(feature = "ui")]
fn settle_replace(&mut self, id: PickId, replace: bool) {
let Some(Pending { request, awaiting_replace: Some(question) }) = lock(&self.inner).pending.remove(&id) else { return };
self.complete(id, request, if replace { Picked::Paths(vec![question.settled]) } else { Picked::Cancelled });
let Some(Pending { request, awaiting_replace: Some(question), forgotten: false }) = lock(&self.inner).pending.remove(&id) else { return };
let picked = if replace { Picked::Saved { path: question.settled, file_type: question.file_type } } else { Picked::Cancelled };
self.complete(id, request, picked);
}
/// Remembers the folder of a chosen path and queues the answer.
fn complete(&self, id: PickId, request: PickRequest, picked: Picked) {
let mut inner = lock(&self.inner);
if let Picked::Paths(paths) = &picked
&& let Some(first) = paths.first()
if matches!(picked, Picked::Paths(_) | Picked::Saved { .. })
&& let Some(first) = picked.first_path()
{
let folder = if request.kind == PickKind::Folder { Some(first.as_path()) } else { first.parent() };
if let Some(folder) = folder.filter(|f| !f.as_os_str().is_empty()) {
@@ -564,7 +602,7 @@ impl Files for FileService {
let mut inner = lock(&self.inner);
inner.next += 1;
let id = PickId(inner.next);
inner.pending.insert(id, Pending { request: request.clone(), awaiting_replace: None });
inner.pending.insert(id, Pending { request: request.clone(), awaiting_replace: None, forgotten: false });
id
};
// The panels gone (the app is shutting down) leaves the ticket unanswered.
@@ -579,20 +617,20 @@ impl Files for FileService {
inner.answered.remove(at).map(|a| a.picked)
}
// A ticket still pending leaves `pending`, so the answer the panel gives later is dropped by `finish`.
// A ticket still pending stays in `pending`, marked: its panel may be on screen, and `finish` drops the answer it gives later.
fn forget(&self, id: PickId) {
let mut inner = lock(&self.inner);
inner.pending.remove(&id);
if let Some(pending) = inner.pending.get_mut(&id) {
pending.forgotten = true;
}
inner.answered.retain(|a| a.id != id);
}
fn pick_pending(&self) -> bool {
let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
inner.panel_busy || !inner.pending.is_empty()
}
fn pending_pick(&self) -> Option<craft_host::PendingPick> {
todo!("fl.F7")
// Tickets count up, so the smallest id is the oldest: the pick on screen.
fn pending_pick(&self) -> Option<PendingPick> {
let inner = lock(&self.inner);
let (_, pending) = inner.pending.iter().min_by_key(|(id, _)| **id)?;
Some(PendingPick { request: pending.request.clone(), sheet: cfg!(target_os = "macos") && pending.request.kind == PickKind::Save })
}
// pc: apps/photocraft/src/services.rs:359 write_atomic (read is plain `std::fs::read`)
@@ -688,7 +726,7 @@ mod service_tests {
// is kept, and a policy that does neither keeps the typed name.
#[trial]
fn a_saved_path_is_settled_by_the_extension_policy() {
let typed = |name: &str| Answer::Paths(vec![PathBuf::from(name)]);
let typed = |name: &str| Answer::Saved { path: PathBuf::from(name), filter: None };
let (service, mut panels, _) = service_with(vec![
typed("/x/Photo.PNG"),
typed("/x/Photo"),
@@ -698,15 +736,15 @@ mod service_tests {
typed("/x/Photo.PNG"),
typed("/x/Photo"),
]);
let path = |p: &str| Picked::Paths(vec![PathBuf::from(p)]);
let both = ExtensionPolicy { lowercase: true, add_suggested: true, picked_type: false }; // P3(files-w1): fl.F6
let path = |p: &str| Picked::Saved { path: PathBuf::from(p), file_type: None };
let both = ExtensionPolicy { lowercase: true, add_suggested: true, picked_type: false };
assert_eq!(saved_as(&service, &mut panels, both), path("/x/Photo.png"), "only the extension is lowercased");
assert_eq!(saved_as(&service, &mut panels, both), path("/x/Photo.png"), "a bare name gets the suggested extension");
assert_eq!(saved_as(&service, &mut panels, both), path("/x/Photo.jpg"), "another known extension is kept, lowercased");
let neither = ExtensionPolicy::AS_TYPED;
assert_eq!(saved_as(&service, &mut panels, neither), path("/x/Photo.PNG"));
assert_eq!(saved_as(&service, &mut panels, neither), path("/x/Photo"));
let add_only = ExtensionPolicy { lowercase: false, add_suggested: true, picked_type: false }; // P3(files-w1): fl.F6
let add_only = ExtensionPolicy { lowercase: false, add_suggested: true, picked_type: false };
assert_eq!(saved_as(&service, &mut panels, add_only), path("/x/Photo.PNG"), "adding does not lowercase");
assert_eq!(saved_as(&service, &mut panels, add_only), path("/x/Photo.png"));
}
@@ -719,8 +757,10 @@ mod service_tests {
let dir = std::env::temp_dir().join(format!("craft-dialogs-replace-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("scratch dir");
std::fs::write(dir.join("Photo.png"), b"old").expect("existing file");
let typed = |name: &str| Answer::Paths(vec![dir.join(name)]);
let (service, mut panels, log) = service_with(vec![typed("Photo"), Answer::Message(MessageResult::Cancel), typed("Photo.png")]);
let typed = |name: &str| Answer::Saved { path: dir.join(name), filter: None };
let typed_as_png = Answer::Saved { path: dir.join("Photo"), filter: Some(0) };
let (service, mut panels, log) =
service_with(vec![typed("Photo"), Answer::Message(MessageResult::Cancel), typed("Photo.png"), typed_as_png, Answer::Message(MessageResult::Ok)]);
let bare = service.pick(PickRequest::save("export").suggested_extension("png"));
panels.pump(NONE);
@@ -729,8 +769,17 @@ mod service_tests {
let asked = service.pick(PickRequest::save("export").suggested_extension("png"));
panels.pump(NONE);
assert_eq!(answered(&service, asked), Picked::Paths(vec![dir.join("Photo.png")]));
assert_eq!(answered(&service, asked), Picked::Saved { path: dir.join("Photo.png"), file_type: None });
assert_eq!(log.borrow().len(), 3, "no question for a path the panel asked about");
let by_type = service.pick(PickRequest::save("export").filter("PNG", &["png"]));
panels.pump(NONE);
assert_eq!(
answered(&service, by_type),
Picked::Saved { path: dir.join("Photo.png"), file_type: Some(0) },
"the picked type's rename names an existing file: asked, and the type is kept"
);
assert_eq!(log.borrow().len(), 5, "the save panel, then the question");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -742,13 +791,100 @@ mod service_tests {
let dir = std::env::temp_dir().join(format!("craft-dialogs-existing-case-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("scratch dir");
std::fs::write(dir.join("PHOTO.PNG"), b"old").expect("existing file");
let typed = |name: &str| Answer::Paths(vec![dir.join(name)]);
let typed = |name: &str| Answer::Saved { path: dir.join(name), filter: None };
let (service, mut panels, log) = service_with(vec![typed("PHOTO.PNG"), typed("Other.PNG")]);
let lowercase = ExtensionPolicy::default();
let saved = |name: &str| Picked::Saved { path: dir.join(name), file_type: None };
assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("PHOTO.PNG")]), "the existing file is replaced");
assert_eq!(saved_as(&service, &mut panels, lowercase), saved("PHOTO.PNG"), "the existing file is replaced");
assert_eq!(log.borrow().len(), 1, "no second question: the panel asked about this file");
assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("Other.png")]), "a new file is lowercased");
assert_eq!(saved_as(&service, &mut panels, lowercase), saved("Other.png"), "a new file is lowercased");
let _ = std::fs::remove_dir_all(&dir);
}
// The rename rule: the picked type decides a bare name's extension, and a typed extension wins
// unless it is the one the panel opened with.
#[trial]
fn the_picked_file_type_gives_a_bare_name_its_extension_and_a_typed_extension_wins() {
let two = [FileFilter::new("Photoshop", &["psd", "psb"]), FileFilter::new("PNG", &["png"])];
let only = [FileFilter::new("Swatches", &["aco"])];
// (path, opened with, filters, picked type, expected path)
type Case<'a> = (&'a str, Option<&'a str>, &'a [FileFilter], Option<usize>, &'a str);
let table: [Case; 8] = [
("/s/Untitled", Some("Untitled.psd"), &two, Some(1), "/s/Untitled.png"),
("/s/Untitled.psd", Some("Untitled.psd"), &two, Some(1), "/s/Untitled.png"),
("/s/art.png", Some("art.psd"), &two, Some(0), "/s/art.png"),
("/s/art.PSB", Some("art.psd"), &two, Some(0), "/s/art.PSB"),
("/s/scan.2024", None, &two, Some(1), "/s/scan.2024.png"),
("/s/Swatches", None, &only, None, "/s/Swatches.aco"),
("/s/Swatches.aco", None, &only, None, "/s/Swatches.aco"),
("/s/free", None, &two, None, "/s/free"),
];
for (path, opened, filters, picked, expected) in table {
let chosen: &[String] = match chosen_type(filters, picked) {
Some(at) => &filters[at].extensions,
None => &[],
};
assert_eq!(with_chosen_type(Path::new(path), opened, chosen, filters), PathBuf::from(expected), "{path} with type {picked:?}");
}
}
// A panel that reports the picked type gets its extension under the default policy; AS_TYPED keeps
// the typed name, and the type is reported either way.
#[trial]
fn a_save_answer_reports_the_picked_type_and_as_typed_keeps_the_typed_name() {
let answer = || Answer::Saved { path: PathBuf::from("/x/Photo"), filter: Some(1) };
let (service, mut panels, _) = service_with(vec![answer(), answer()]);
let request = || PickRequest::save("export").filter("Photoshop", &["psd"]).filter("PNG", &["png"]);
let mut save = |policy: ExtensionPolicy| {
panels.set_extension_policy(policy);
let id = service.pick(request());
panels.pump(NONE);
answered(&service, id)
};
assert_eq!(save(ExtensionPolicy::default()), Picked::Saved { path: PathBuf::from("/x/Photo.png"), file_type: Some(1) });
assert_eq!(save(ExtensionPolicy::AS_TYPED), Picked::Saved { path: PathBuf::from("/x/Photo"), file_type: Some(1) });
}
// The close gate reads `pending_pick`: the oldest ticket (a forgotten one while its panel may
// still show), and still `Some` while the Replace question is open.
#[trial]
fn the_pending_pick_is_the_oldest_until_answered_and_holds_through_the_replace_question() {
let (service, mut panels, _) = service_with(vec![]);
assert!(service.pending_pick().is_none(), "nothing asked");
let first = service.pick(PickRequest::open("a"));
let second = service.pick(PickRequest::save("b"));
let oldest = service.pending_pick().expect("a pick is pending");
assert_eq!((oldest.request.purpose.as_str(), oldest.sheet), ("a", false), "the oldest ticket, an Open pick: no sheet");
service.forget(first);
assert_eq!(service.pending_pick().expect("still pending").request.purpose, "a", "a forgotten pick holds until its panel answers");
panels.pump(NONE);
assert!(service.pending_pick().is_none(), "both panels answered");
assert!(service.take_answer(first).is_none(), "the forgotten answer is dropped");
assert_eq!(answered(&service, second), Picked::Cancelled);
let dir = std::env::temp_dir().join(format!("craft-dialogs-pending-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("scratch dir");
std::fs::write(dir.join("Photo.png"), b"old").expect("existing file");
let (service, mut panels) = FileService::new(Wake::none());
panels.backend_problem = || None;
let service = Rc::new(service);
let during: Rc<RefCell<Option<Option<PendingPick>>>> = Rc::default();
let (reader, slot) = (service.clone(), during.clone());
let mut files = vec![Answer::Saved { path: dir.join("Photo"), filter: None }].into_iter();
panels.dialogs.set_override(Some(Box::new(move |request| match request {
Request::Message(_) => {
*slot.borrow_mut() = Some(reader.pending_pick());
Answer::Message(MessageResult::Cancel)
}
Request::File(_) => files.next().unwrap_or(Answer::Cancelled),
})));
let id = service.pick(PickRequest::save("export").suggested_extension("png"));
panels.pump(NONE);
let asked = during.borrow().clone().expect("the Replace question was asked").expect("the pick is still pending during it");
assert_eq!((asked.request.kind, asked.sheet), (PickKind::Save, cfg!(target_os = "macos")), "a Save is a sheet on macOS only");
assert!(service.pending_pick().is_none(), "answered");
assert_eq!(answered(&service, id), Picked::Cancelled);
let _ = std::fs::remove_dir_all(&dir);
}
}
-5
View File
@@ -47,11 +47,6 @@ impl Files for StubFiles {
self.state.lock().unwrap_or_else(|e| e.into_inner()).answered.retain(|a| a.id != id);
}
fn pick_pending(&self) -> bool {
false
}
// P3(files-w1): fl.F2
fn pending_pick(&self) -> Option<craft_host::PendingPick> {
None
}
+10 -19
View File
@@ -5,7 +5,8 @@
//! arrives on a later pass through [`Files::take_answer`]. One picker shows at a time; later
//! requests wait in order. A request starts in its own [`PickRequest::directory`] when it names
//! one; otherwise the service starts it in the last folder it remembers for the
//! [`PickRequest::purpose`]. It applies the extension policy to a saved name before the app sees it.
//! [`PickRequest::purpose`]. It applies the extension policy to a saved name before the app sees it,
//! and a Save answer ([`Picked::Saved`]) reports the file type picked in the panel.
use std::collections::{HashMap, VecDeque};
use std::fmt;
@@ -150,10 +151,10 @@ pub struct PickId(pub u64);
pub enum Picked {
/// The user cancelled.
Cancelled,
/// One or more paths. For [`PickKind::Save`] the extension policy has been applied, and the
/// service has already asked about replacing an existing file the OS panel did not check.
/// One or more existing paths, the answer of an Open or Folder pick.
Paths(Vec<PathBuf>),
/// Every [`PickKind::Save`] answer. `file_type` is the index into the request's `filters` of the
/// Every [`PickKind::Save`] answer: the extension policy has been applied, and the service has
/// already asked about replacing an existing file the OS panel did not check. `file_type` is the index into the request's `filters` of the
/// type picked in the panel, when the panel reports one.
Saved {
/// The path chosen.
@@ -260,8 +261,6 @@ pub trait Files: Send + Sync {
/// Drops ticket `id`: its answer, if it has come, and the answer that has yet to come. An
/// owner that closes with a pick outstanding calls it.
fn forget(&self, id: PickId);
/// Whether a picker is on screen or waiting.
fn pick_pending(&self) -> bool;
/// The oldest pick not yet answered (the one on screen), including one waiting on the service's
/// Replace question; `None` when none.
fn pending_pick(&self) -> Option<PendingPick>;
@@ -300,10 +299,6 @@ impl Files for NoPickFiles {
self.answered.lock().unwrap_or_else(|e| e.into_inner()).retain(|a| a.id != id);
}
fn pick_pending(&self) -> bool {
false
}
fn pending_pick(&self) -> Option<PendingPick> {
None
}
@@ -359,7 +354,6 @@ struct ScriptState {
/// A Save is answered with the suggested name in the suggested folder.
save_suggested: bool,
/// Picks report `sheet: true` in [`PendingPick`].
#[allow(dead_code)] // P3(files-w1): fl.F4
sheets: bool,
/// Picks the test has not answered yet, oldest first.
open: Vec<(PickId, PickRequest)>,
@@ -398,8 +392,8 @@ impl ScriptedFiles {
/// Scripted picks report `sheet: on`.
pub fn sheets(self, on: bool) -> Self {
let _ = on;
todo!("fl.F4")
self.state().sheets = on;
self
}
/// Puts a file in memory, for [`Files::read`].
@@ -452,7 +446,7 @@ impl ScriptedFiles {
/// The suggested name of a Save in its suggested folder.
fn suggested(request: &PickRequest) -> Picked {
let name = PathBuf::from(request.file_name.clone().unwrap_or_default());
Picked::Paths(vec![request.directory.as_ref().map_or_else(|| name.clone(), |dir| dir.join(&name))])
Picked::Saved { path: request.directory.as_ref().map_or_else(|| name.clone(), |dir| dir.join(&name)), file_type: None }
}
}
@@ -484,12 +478,9 @@ impl Files for ScriptedFiles {
state.open.retain(|(open, _)| *open != id);
}
fn pick_pending(&self) -> bool {
!self.state().open.is_empty()
}
fn pending_pick(&self) -> Option<PendingPick> {
todo!("fl.F2")
let state = self.state();
state.open.first().map(|(_, request)| PendingPick { request: request.clone(), sheet: state.sheets })
}
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {