pdf-workflows-w4: net change of 3 commits

- pdf-workflows-w4: written from its sheet
- pdf-workflows-w4: review fixes (review-1)
- pdf-workflows-w4: drop the filled P3 marker in the dialogs test stub (lead applied the refused hunk)
This commit is contained in:
Dylan M. Taylor
2026-11-18 08:07:07 -05:00
parent 8a8115e1c3
commit 6a83eb7a0f
6 changed files with 295 additions and 50 deletions
+44 -4
View File
@@ -1,10 +1,50 @@
//! `ui.pick`: answers the next file picker of a running app.
use serde_json::Value;
use std::fmt::Display;
use std::path::PathBuf;
use craft_host::{FileError, Files, Picked};
use serde_json::{Value, json};
use crate::protocol::Params;
/// The fields of `ui.pick`, of which a request names exactly one.
const FIELDS: [&str; 4] = ["files", "folder", "save", "cancel"];
/// `None` for any method other than `ui.pick`. `ui.pick` takes exactly one of `{files: [path, ..]}`, `{folder: path}`,
/// `{save: path}` or `{cancel: true}` and answers through `Files::answer_next` with `Picked::Paths` or `Cancelled`.
pub fn pick_method(files: &dyn craft_host::Files, method: &str, params: &Value) -> Option<Result<Value, String>> {
let _ = (files, method, params);
todo!("WF-W17")
/// Paths are taken as given; the service settles them as it would a panel's answer.
pub fn pick_method(files: &dyn Files, method: &str, params: &Value) -> Option<Result<Value, String>> {
(method == "ui.pick").then(|| pick(files, params))
}
fn pick(files: &dyn Files, params: &Value) -> Result<Value, String> {
let params = Params(params).only(None, &FIELDS)?;
let read = Params(&params);
let given: Vec<&str> = FIELDS.iter().copied().filter(|field| params.get(*field).is_some()).collect();
let [field] = given.as_slice() else { return Err(refused("give exactly one field")) };
let picked = match *field {
"files" => Picked::Paths(paths(params.get("files"))?),
"cancel" => match read.bool_field("cancel").map_err(refused)? {
Some(true) => Picked::Cancelled,
_ => return Err(refused("cancel must be true")),
},
one => Picked::Paths(vec![PathBuf::from(read.str_field(one).map_err(refused)?.ok_or_else(|| refused(format!("missing `{one}`")))?)]),
};
files.answer_next(picked).map_err(|e| match e {
FileError::Unsupported => "this window's file service takes no automated answers".to_owned(),
other => other.to_string(),
})?;
Ok(json!({"answered": "next"}))
}
/// `files` as a non-empty list of paths.
fn paths(files: Option<&Value>) -> Result<Vec<PathBuf>, String> {
let list = files.and_then(Value::as_array).filter(|list| !list.is_empty());
let paths = list.and_then(|list| list.iter().map(|path| path.as_str().map(PathBuf::from)).collect::<Option<Vec<_>>>());
paths.ok_or_else(|| refused("files must be a non-empty array of path strings"))
}
fn refused(why: impl Display) -> String {
format!("{why}; ui.pick takes exactly one of: {}", FIELDS.join(", "))
}
+66
View File
@@ -0,0 +1,66 @@
//! `ui.pick` at the protocol boundary.
use std::path::PathBuf;
use craft_automation::files::pick_method;
use craft_host::{Files, NoPickFiles, PickRequest, Picked, ScriptedFiles};
use craft_ui::testing::trial;
use serde_json::{Value, json};
fn call(files: &dyn Files, params: Value) -> Result<Value, String> {
pick_method(files, "ui.pick", &params).expect("ui.pick is the pick method")
}
fn path(p: &str) -> PathBuf {
PathBuf::from(p)
}
/// Each field reaches the service as its `Picked`; with picks on screen the oldest is answered; a bad request is
/// refused with the field list and answers nothing; a service that takes no automated answers says so.
#[trial]
fn ui_pick_answers_the_next_picker_and_refuses_bad_params() {
let answered = Ok(json!({"answered": "next"}));
let files = ScriptedFiles::new();
assert_eq!(call(&files, json!({"files": ["/w/a.pdf", "/w/b.pdf"]})), answered);
assert_eq!(call(&files, json!({"folder": "/w/out"})), answered);
assert_eq!(call(&files, json!({"save": "/w/c.pdf"})), answered);
assert_eq!(call(&files, json!({"cancel": true, "files": null})), answered, "a null field is omitted");
let picked: Vec<Picked> = (0..4)
.map(|_| {
let id = files.pick(PickRequest::open("document"));
files.take_answer(id).expect("a queued answer comes at once")
})
.collect();
assert_eq!(
picked,
[Picked::Paths(vec![path("/w/a.pdf"), path("/w/b.pdf")]), Picked::Paths(vec![path("/w/out")]), Picked::Paths(vec![path("/w/c.pdf")]), Picked::Cancelled]
);
let held = ScriptedFiles::held();
let oldest = held.pick(PickRequest::open("first"));
let newest = held.pick(PickRequest::open("second"));
assert_eq!(call(&held, json!({"files": ["/w/first.pdf"]})), answered);
assert_eq!(held.take_answer(oldest), Some(Picked::Paths(vec![path("/w/first.pdf")])), "the oldest open pick is answered");
assert_eq!(held.take_answer(newest), None);
assert_eq!(held.open(), 1);
for bad in [
json!({"files": ["/w/a.pdf"], "save": "/w/b.pdf"}),
json!({}),
json!({"files": []}),
json!({"files": ["/w/a.pdf", 3]}),
json!({"save": 3}),
json!({"cancel": false}),
json!({"path": "/w/a.pdf"}),
] {
let error = call(&files, bad.clone()).expect_err("refused");
assert!(error.contains("files, folder, save, cancel"), "{bad}: {error}");
}
assert_eq!(call(&files, json!({"folder": "/w/after"})), answered);
let id = files.pick(PickRequest::folder("export"));
assert_eq!(files.take_answer(id), Some(Picked::Paths(vec![path("/w/after")])), "no refused request queued an answer");
let unsupported = call(&NoPickFiles::default(), json!({"cancel": true})).expect_err("a service without automated answers refuses");
assert!(!unsupported.contains("files, folder, save, cancel"), "an unsupported service is not a field-list refusal: {unsupported}");
assert!(pick_method(&files, "ui.click", &json!({})).is_none());
}
+96 -30
View File
@@ -160,6 +160,14 @@ struct ReplaceQuestion {
settled: PathBuf,
}
/// Where an answer to settle came from: a panel the user saw, or [`Files::answer_next`]. A
/// cancel only means "no dialog backend" when a panel gave it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Source {
Panel,
Forced,
}
/// A replace question shown on the app's `DialogHost`: the pick it settles and the prompt's id,
/// once the host has accepted the prompt.
#[cfg(feature = "ui")]
@@ -201,7 +209,6 @@ struct Inner {
/// A panel is on screen or queued (mirrored from the panels each pump).
panel_busy: bool,
/// The answers `Files::answer_next` gave, which the panels answer the next requests with.
#[allow(dead_code)] // P3(pdf-workflows-w4): WF-W16
forced: VecDeque<Answer>,
}
@@ -297,20 +304,20 @@ impl FilePanels {
/// the answer becomes a [`PickAnswer`].
// pc: crates/ui-egui/src/file_dialog.rs:310 poll_file_dialog, :349 finish_file_dialog, :365 saved_path
pub fn pump<W: HasWindowHandle + HasDisplayHandle>(&mut self, parent: Option<&W>) {
self.start_requests();
// A replace question queued by `finish` shows in the same pass, so the loop runs until no
// answer is left to settle.
// Forced answers settle first; a replace question queued by `finish` shows in the same
// pass, so the loop runs until no answer is left to settle.
let mut answers = self.start_requests();
loop {
self.dialogs.show_pending(parent);
let answers = self.dialogs.take_answers();
if answers.is_empty() {
break;
}
for (id, answer) in answers {
if let Some(question) = self.finish(id, answer) {
for (id, answer, source) in answers {
if let Some(question) = self.finish(id, answer, source) {
self.dialogs.ask_message(self.replace_message(&question.settled), id);
}
}
self.dialogs.show_pending(parent);
answers = self.panel_answers();
if answers.is_empty() {
break;
}
}
self.mark_busy();
}
@@ -326,18 +333,18 @@ impl FilePanels {
#[cfg(feature = "ui")]
pub fn pump_with<W: HasWindowHandle + HasDisplayHandle>(&mut self, dialogs: &mut craft_ui::dialog::DialogHost, parent: Option<&W>) {
self.collect_prompt_answers(dialogs);
self.start_requests();
let mut answers = self.start_requests();
loop {
self.dialogs.show_pending(parent);
let answers = self.dialogs.take_answers();
if answers.is_empty() {
break;
}
for (id, answer) in answers {
if let Some(question) = self.finish(id, answer) {
for (id, answer, source) in answers {
if let Some(question) = self.finish(id, answer, source) {
self.prompts.push(AskedPrompt { id, question, dialog: None });
}
}
self.dialogs.show_pending(parent);
answers = self.panel_answers();
if answers.is_empty() {
break;
}
}
self.open_prompts(dialogs);
self.mark_busy();
@@ -393,13 +400,32 @@ impl FilePanels {
}
}
/// Drains the requests the service queued into the native panels' queue.
fn start_requests(&mut self) {
/// Drains the requests the service queued into the native panels' queue. A request that finds
/// a forced answer waiting takes it instead of a panel; those answers are returned for the
/// caller to settle. A ticket forgotten before it got here leaves the forced answer for the
/// next request.
fn start_requests(&mut self) -> Vec<(PickId, Answer, Source)> {
let mut forced = Vec::new();
while let Ok((id, request)) = self.requests.try_recv() {
let folder = lock(&self.inner).last_folder.get(&request.purpose).cloned();
let folder = {
let mut inner = lock(&self.inner);
if inner.pending.contains_key(&id)
&& let Some(answer) = inner.forced.pop_front()
{
forced.push((id, answer, Source::Forced));
continue;
}
inner.last_folder.get(&request.purpose).cloned()
};
let dialog = self.file_dialog(&request, folder.as_deref());
self.dialogs.ask(dialog, id);
}
forced
}
/// The answers the native panels gave since the last call.
fn panel_answers(&mut self) -> Vec<(PickId, Answer, Source)> {
self.dialogs.take_answers().into_iter().map(|(id, answer)| (id, answer, Source::Panel)).collect()
}
fn mark_busy(&self) {
@@ -466,9 +492,9 @@ impl FilePanels {
/// Turns a panel answer into the pick's answer: `Cancelled` stays, `Paths` for Save go 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
/// cause when a panel gave it. A Save that needs the replace
/// question stays pending and returns the question for the caller to ask.
fn finish(&mut self, id: PickId, answer: Answer) -> Option<ReplaceQuestion> {
fn finish(&mut self, id: PickId, answer: Answer, source: Source) -> Option<ReplaceQuestion> {
let pending = lock(&self.inner).pending.remove(&id)?;
let picked = match (answer, pending.awaiting_replace) {
(Answer::Message(result), Some(question)) => {
@@ -493,7 +519,7 @@ impl FilePanels {
(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.
(Answer::Cancelled, None) => (self.backend_problem)().map_or(Picked::Cancelled, Picked::Unavailable),
(Answer::Cancelled, None) if source == Source::Panel => (self.backend_problem)().map_or(Picked::Cancelled, Picked::Unavailable),
(Answer::Cancelled | Answer::Message(_), _) => Picked::Cancelled,
};
self.complete(id, pending.request, picked);
@@ -548,8 +574,15 @@ impl Files for FileService {
/// Answers the next pick with `picked` instead of showing a panel, through the settling a native answer passes.
/// `Picked::Contents` has no `Answer` form: it is `Err(FileError::Unsupported)`.
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
let _ = picked;
todo!("WF-W16")
let answer = match picked {
Picked::Paths(paths) => Answer::Paths(paths),
Picked::Cancelled => Answer::Cancelled,
Picked::Unavailable(why) => Answer::Unavailable(why),
// A native service reads paths; it has no file contents to hand over.
Picked::Contents(_) => return Err(FileError::Unsupported),
};
lock(&self.inner).forced.push_back(answer);
Ok(())
}
// A ticket still pending leaves `pending`, so the answer the panel gives later is dropped by `finish`.
@@ -570,9 +603,8 @@ impl Files for FileService {
}
// pc: apps/photocraft/src/services.rs:359 write_atomic
// P3(pdf-workflows-w4): L-184 the intent and the page-took-it result.
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
let _ = intent;
// A desktop app has no host page: every intent writes the path, and no page took the bytes.
fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
craft_atomic::atomic_write(path, bytes).map_err(|e| file_error(e, path))?;
Ok(false)
}
@@ -683,6 +715,40 @@ mod service_tests {
assert_eq!(saved_as(&service, &mut panels, add_only), path("/x/Photo.png"));
}
// A forced answer answers the next pick with no panel, through the same settling: the folder
// is remembered and a Save gets the extension policy. The pick after it reaches the panel, and
// a forced cancel stays a cancel on a system without a dialog backend.
#[trial]
fn a_forced_answer_answers_the_next_pick_without_a_panel() {
let (service, mut panels, log) = service_with(vec![]);
let dir = PathBuf::from("/x/forced");
assert_eq!(service.answer_next(Picked::Paths(vec![dir.join("a.pdf")])), Ok(()));
let forced = service.pick(PickRequest::open("document"));
panels.pump(NONE);
assert_eq!(answered(&service, forced), Picked::Paths(vec![dir.join("a.pdf")]));
assert!(log.borrow().is_empty(), "no request reached a panel");
assert!(!service.pick_pending());
assert_eq!(service.last_folder("document"), Some(dir.clone()));
let shown = service.pick(PickRequest::open("document"));
panels.pump(NONE);
assert_eq!(log.borrow().len(), 1, "the next pick reaches the panel");
assert_eq!(answered(&service, shown), Picked::Cancelled);
assert_eq!(service.answer_next(Picked::Paths(vec![dir.join("Report")])), Ok(()));
let saved = service.pick(PickRequest::save("export").suggested_extension("pdf"));
panels.pump(NONE);
assert_eq!(answered(&service, saved), Picked::Paths(vec![dir.join("Report.pdf")]), "the extension policy completes it");
assert_eq!(log.borrow().len(), 1);
panels.backend_problem = || Some("no dialog backend".into());
assert_eq!(service.answer_next(Picked::Cancelled), Ok(()));
let cancelled = service.pick(PickRequest::open("document"));
panels.pump(NONE);
assert_eq!(answered(&service, cancelled), Picked::Cancelled);
assert_eq!(service.answer_next(Picked::Contents(vec![])), Err(FileError::Unsupported));
}
// The panel asked about the file it answered; the extension change can name another existing
// file, and that one is asked about here. Cancel ends the pick; an answer the panel already
// asked about is not asked again.
-1
View File
@@ -55,7 +55,6 @@ impl Files for StubFiles {
Err(FileError::Unsupported)
}
// P3(pdf-workflows-w4): L-184 the intent and the page-took-it result.
fn write(&self, _path: &Path, _bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
Err(FileError::Unsupported)
}
+58 -1
View File
@@ -1,6 +1,6 @@
//! `craft_docpath::names`.
use crate::names::{CopyNumbering, MAX_NAME_BYTES, safe_file_name, unique_file_name};
use crate::names::{CopyNumbering, MAX_NAME_BYTES, is_plain_file_name, safe_file_name, safe_file_stem, unique_file_name};
// Reserved and control characters become `_`, bidi controls go, trailing dots and spaces go,
// "NUL.txt" becomes "_NUL.txt", a 300-byte name is cut to 200 bytes on a char boundary keeping
@@ -19,6 +19,63 @@ fn user_text_becomes_a_safe_file_name() {
assert!(safe_file_name(&"a".repeat(300), "x").len() == MAX_NAME_BYTES);
}
// ".." leaves nothing; ".PDF" goes in any case; a path stays one name; a 900-byte CJK stem is cut
// to 198 bytes, the last whole character under the limit.
#[test]
fn user_text_becomes_a_safe_file_stem() {
assert_eq!(safe_file_stem("..", "pdf"), "");
assert_eq!(safe_file_stem("Report.PDF", "pdf"), "Report");
assert_eq!(safe_file_stem("Report.pdf.txt", "pdf"), "Report.pdf.txt");
assert_eq!(safe_file_stem("../../etc/passwd", "pdf"), ".._.._etc_passwd");
let long = safe_file_stem(&"文".repeat(300), "pdf");
assert!(long.len() <= MAX_NAME_BYTES && long.chars().all(|c| c == '文'), "{}", long.len());
assert_eq!(long.len(), 198);
}
// Device names, in any case, with any extension and with the superscript digits, get a `_`;
// longer names that start like one do not.
#[test]
fn windows_device_names_get_a_prefix() {
for name in ["NUL.tar.gz", "con.txt", "COM1.exe", "LPT9.txt", "COM¹.txt", "LPT³.pdf", "lpt9.tar", "nul"] {
assert_eq!(safe_file_name(name, "x"), format!("_{name}"));
assert_eq!(safe_file_stem(name, "zip"), format!("_{name}"));
}
assert_eq!(safe_file_stem("COM1.pdf", "pdf"), "_COM1");
assert_eq!(safe_file_stem("LPT³.pdf", "pdf"), "_LPT³");
for name in ["COM10", "Console", "COM10.txt", "LPT.txt"] {
assert_eq!(safe_file_name(name, "x"), name);
assert_eq!(safe_file_stem(name, "pdf"), name);
}
}
// Right-to-left scripts, joiners and double extensions are left alone; a name with nothing usable
// gives the fallback; a safe name is already safe.
#[test]
fn ordinary_names_pass_unchanged_and_making_safe_is_stable() {
for name in ["report.pdf", "archive.tar.gz", "مرحبا.pdf", "שלום.txt", "資料.pdf", "می\u{200c}روم.txt", "👩\u{200d}💻.png"] {
assert_eq!(safe_file_name(name, "attachment"), name);
}
for name in ["", " ", ".", "..", " . . ", "\u{202e}"] {
assert_eq!(safe_file_name(name, "attachment"), "attachment", "{name:?}");
}
let long = format!("{}.pdf", "é".repeat(150));
for name in ["invoice\u{202e}fdp.exe", "../a.pdf", "NUL.txt", " . . ", "report.pdf . ", "資料.pdf", "a\tb/c", long.as_str()] {
let once = safe_file_name(name, "attachment");
assert_eq!(safe_file_name(&once, "attachment"), once, "{name:?}");
}
}
// A plain name sits directly in its folder: no separator, no drive, no trailing dot or space.
#[test]
fn plain_file_names_stay_directly_in_the_folder() {
for good in ["report.pdf", "report", ".hidden", "a b.pdf", "資料.pdf"] {
assert!(is_plain_file_name(good), "{good}");
}
for bad in ["", "report.", "report.pdf.", "report.pdf ", "report. . ", " ", "...", ". ", "..", "C:x.pdf", "sub\\x.pdf", "sub/x.pdf"] {
assert!(!is_plain_file_name(bad), "{bad:?}");
}
}
// "a.txt", "a 2.txt" taken: Space gives "a 3.txt", Parenthesized "a (2).txt" when only "a.txt"
// is taken; "photo (2).jpg" counts on to "photo (3).jpg"; a name with no extension numbers its end.
#[test]
+31 -14
View File
@@ -192,8 +192,11 @@ pub struct PickAnswer {
pub picked: Picked,
}
/// Why a file is written: a Save to the document's own place, or a Save As to a new one.
/// Why a file is written: a Save to the document's own place, or a Save As to a new one. A
/// service that hands the bytes to an embedding page passes it on, so the page can tell the two
/// apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WriteIntent {
/// Save to the place the document already has.
Save,
@@ -308,9 +311,9 @@ impl Files for NoPickFiles {
Err(FileError::Unsupported)
}
// No page to hand the bytes to: every intent writes the path, and no page took them.
#[cfg(not(target_arch = "wasm32"))]
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
let _ = intent; // P3(pdf-workflows-w4): SH-C35
fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
let tmp = path.with_extension(format!("{}.tmp", path.extension().and_then(|e| e.to_str()).unwrap_or("")));
std::fs::write(&tmp, bytes).map_err(|e| with_path(e, path))?;
std::fs::rename(&tmp, path).map_err(|e| with_path(e, path))?;
@@ -370,8 +373,9 @@ impl ScriptedFiles {
}
/// A service whose picks stay open until the test answers them with
/// [`answer`](ScriptedFiles::answer) or [`answer_to`](ScriptedFiles::answer_to): the state of
/// a user who has the dialog on screen.
/// [`answer`](ScriptedFiles::answer), [`answer_to`](ScriptedFiles::answer_to) or
/// [`Files::answer_next`]: the state of a user who has the dialog on screen. A pick that finds
/// an answer queued takes it at once.
pub fn held() -> Self {
let files = Self::default();
files.state().held = true;
@@ -446,12 +450,15 @@ impl Files for ScriptedFiles {
let id = PickId(state.next);
let suggested = (state.save_suggested && request.kind == PickKind::Save).then(|| Self::suggested(&request));
state.asked.push(request.clone());
if state.held {
state.open.push((id, request));
return id;
let picked = if state.held {
state.queued.pop_front()
} else {
Some(suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled))
};
match picked {
Some(picked) => state.answered.push(PickAnswer { id, request, picked }),
None => state.open.push((id, request)),
}
let picked = suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled);
state.answered.push(PickAnswer { id, request, picked });
id
}
@@ -475,15 +482,24 @@ impl Files for ScriptedFiles {
self.file(path).ok_or_else(|| FileError::NotFound(path.to_owned()))
}
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
let _ = intent; // P3(pdf-workflows-w4): SH-C35
// Kept in memory whatever the intent; no page takes the bytes.
fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
self.state().files.insert(path.to_owned(), bytes.to_vec());
Ok(false)
}
/// Answers the oldest open pick of a [`held`](ScriptedFiles::held) service; otherwise the
/// answer is queued for the next pick. [`answer`](ScriptedFiles::answer) answers the newest
/// instead, so this does not go through it.
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
let _ = picked;
todo!("WF-W16")
let mut state = self.state();
if state.held && !state.open.is_empty() {
let (id, request) = state.open.remove(0);
state.answered.push(PickAnswer { id, request, picked });
} else {
state.queued.push_back(picked);
}
Ok(())
}
fn last_folder(&self, _purpose: &str) -> Option<PathBuf> {
@@ -499,3 +515,4 @@ fn with_path(e: std::io::Error, path: &Path) -> FileError {
other => other,
}
}