mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-17 11:22:56 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b78606c39b | ||
|
|
8a56c71fa0 |
+3
-1
File diff suppressed because one or more lines are too long
@@ -151,7 +151,7 @@ impl Launcher {
|
||||
name: Some(name.clone()),
|
||||
suggested: Some(name.clone()),
|
||||
folder: dir.clone().map(std::path::PathBuf::from),
|
||||
filters: save_filters(name),
|
||||
filters: wordcraft_ui_egui::save_filters(name),
|
||||
current: Some(0),
|
||||
cancel,
|
||||
timeout: None,
|
||||
@@ -224,7 +224,7 @@ fn picker(dialog: rfd::AsyncFileDialog, req: &FileDialogRequest) -> Picking {
|
||||
if let Some(dir) = dir.filter(|d| std::path::Path::new(d).is_dir()) {
|
||||
dialog = dialog.set_directory(dir);
|
||||
}
|
||||
for (label, exts) in save_filters(&name) {
|
||||
for (label, exts) in wordcraft_ui_egui::save_filters(&name) {
|
||||
dialog = dialog.add_filter(label, &exts);
|
||||
}
|
||||
Box::pin(async move { dialog.save_file().await.into_iter().collect() })
|
||||
@@ -324,62 +324,9 @@ fn on_path(program: &str) -> bool {
|
||||
std::env::var_os("PATH").is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(program).is_file()))
|
||||
}
|
||||
|
||||
/// The file types Save As offers: every format the engine saves, with the suggested name's own
|
||||
/// format first. rfd makes a filter's first extension the dialog's default, which the Windows,
|
||||
/// macOS and Linux panels append to a file name the user typed without one; with no filter at
|
||||
/// all the name came back bare and the save failed, since the format is chosen by extension
|
||||
/// (#689).
|
||||
fn save_exts(name: &str) -> Vec<String> {
|
||||
let suggested = std::path::Path::new(name)
|
||||
.extension()
|
||||
.and_then(std::ffi::OsStr::to_str)
|
||||
.map(str::to_ascii_lowercase)
|
||||
// A .markdown file is under Markdown's one entry in the list.
|
||||
.map(|e| if e == "markdown" { "md".to_string() } else { e })
|
||||
.filter(|e| wordcraft_engine::io::SAVE_EXTS.contains(&e.as_str()))
|
||||
.unwrap_or_else(|| "docx".to_string());
|
||||
let mut exts: Vec<String> = Vec::with_capacity(wordcraft_engine::io::SAVE_EXTS.len());
|
||||
exts.push(suggested.clone());
|
||||
exts.extend(wordcraft_engine::io::SAVE_EXTS.iter().filter(|e| **e != suggested).map(|e| (*e).to_string()));
|
||||
exts
|
||||
}
|
||||
|
||||
/// The "Save as type" list (#1399): one named entry per format, the suggested one first (see
|
||||
/// [`save_exts`] for why the order matters).
|
||||
///
|
||||
/// On Linux and the BSDs, [`crate::portal_save`] asks the portal directly over D-Bus and gives a
|
||||
/// name the dialog left alone the chosen type's extension (#6180). When falling back to `rfd`, the
|
||||
/// extension in the name wins, as `rfd` doesn't report which entry the user picked.
|
||||
fn save_filters(name: &str) -> Vec<(String, Vec<String>)> {
|
||||
save_exts(name).into_iter().map(|e| (format!("{} (*.{e})", format_name(&e)), vec![e])).collect()
|
||||
}
|
||||
|
||||
/// A readable name for a save format's extension.
|
||||
fn format_name(ext: &str) -> String {
|
||||
match ext {
|
||||
"docx" => "Word Document".into(),
|
||||
"docm" => "Word Macro-Enabled Document".into(),
|
||||
"dotx" => "Word Template".into(),
|
||||
"dotm" => "Word Macro-Enabled Template".into(),
|
||||
"pdf" => "PDF".into(),
|
||||
"txt" => "Plain Text".into(),
|
||||
"md" => "Markdown".into(),
|
||||
"html" => "Web Page".into(),
|
||||
"rtf" => "Rich Text Format".into(),
|
||||
"odt" => "OpenDocument Text".into(),
|
||||
"ott" => "OpenDocument Text Template".into(),
|
||||
"fodt" => "Flat OpenDocument Text".into(),
|
||||
"tex" => "LaTeX".into(),
|
||||
"png" => "PNG Image".into(),
|
||||
"json" => "JSON".into(),
|
||||
"xml" => "XML".into(),
|
||||
other => other.to_ascii_uppercase(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{pick, save_exts, save_filters};
|
||||
use super::pick;
|
||||
use std::time::Duration;
|
||||
|
||||
/// #2999: a dialog that "cancels" at once is a portal that failed: asked again without a
|
||||
@@ -430,44 +377,4 @@ mod tests {
|
||||
assert!(newer.token.is_cancelled(), "the newer request is still armed");
|
||||
assert!(!abandoned.token.is_cancelled(), "only the armed request is cancelled");
|
||||
}
|
||||
|
||||
/// #1399: the Save dialog's type list has one named entry per format, the suggested one first,
|
||||
/// every savable extension exactly once.
|
||||
#[test]
|
||||
fn save_dialog_lists_one_named_type_per_format() {
|
||||
let filters = save_filters("report.odt");
|
||||
assert_eq!(filters.len(), wordcraft_engine::io::SAVE_EXTS.len());
|
||||
assert_eq!(filters[0].1, vec!["odt".to_string()]);
|
||||
assert!(filters[0].0.contains("OpenDocument"), "{}", filters[0].0);
|
||||
let all: Vec<&String> = filters.iter().flat_map(|(_, e)| e).collect();
|
||||
for e in wordcraft_engine::io::SAVE_EXTS {
|
||||
assert_eq!(all.iter().filter(|x| x.as_str() == *e).count(), 1, "{e}");
|
||||
}
|
||||
assert!(filters.iter().all(|(l, e)| !l.trim().is_empty() && e.len() == 1));
|
||||
let mut labels: Vec<&String> = filters.iter().map(|(l, _)| l).collect();
|
||||
labels.sort();
|
||||
labels.dedup();
|
||||
assert_eq!(labels.len(), filters.len(), "labels are distinct");
|
||||
// Unknown names fall back to Word's format first.
|
||||
assert_eq!(save_filters("no extension")[0].1, vec!["docx".to_string()]);
|
||||
}
|
||||
|
||||
/// #689: the Save dialog's default extension is the suggested name's own format, so a file
|
||||
/// name the user types without one is saved in the document's format instead of coming back
|
||||
/// bare and failing.
|
||||
#[test]
|
||||
fn save_dialog_defaults_to_the_suggested_format() {
|
||||
assert_eq!(save_exts("novel.docx")[0], "docx");
|
||||
assert_eq!(save_exts("report.odt")[0], "odt");
|
||||
assert_eq!(save_exts("annual report.pdf")[0], "pdf");
|
||||
assert_eq!(save_exts("notes.md")[0], "md");
|
||||
assert_eq!(save_exts("notes.markdown")[0], "md");
|
||||
// A suggested name always has an extension; anything unreadable falls back to Word's.
|
||||
assert_eq!(save_exts("no extension")[0], "docx");
|
||||
assert_eq!(save_exts("mystery.rtf2")[0], "docx");
|
||||
// Every savable format is still offered, once.
|
||||
let exts = save_exts("novel.docx");
|
||||
assert!(wordcraft_engine::io::SAVE_EXTS.iter().all(|e| exts.iter().any(|x| x == e)));
|
||||
assert_eq!(exts.len(), wordcraft_engine::io::SAVE_EXTS.len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,48 @@ fn ext_of(name: &str) -> String {
|
||||
file.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The format a file extension (any case) saves as, named by its [`SAVE_EXTS`] entry, other
|
||||
/// spellings included (`htm` is `html`, `text` is `txt`); `None` for one WordCraft doesn't save.
|
||||
pub fn save_format(ext: &str) -> Option<&'static str> {
|
||||
let ext = ext.to_ascii_lowercase();
|
||||
let ext = match ext.as_str() {
|
||||
"text" => "txt",
|
||||
"markdown" => "md",
|
||||
"htm" | "xhtml" => "html",
|
||||
"latex" | "ltx" => "tex",
|
||||
other => other,
|
||||
};
|
||||
SAVE_EXTS.iter().copied().find(|e| *e == ext)
|
||||
}
|
||||
|
||||
/// The path Save As writes for a `path` the user named, in format `ext` (`docx`, `pdf`…): a file
|
||||
/// name with no extension, or with one WordCraft doesn't save (`Report v1.2`, `notes.final`),
|
||||
/// gets `.ext` added, as Word adds `.docx` (#5368). The format is chosen by the extension, so
|
||||
/// such a name used to fail to save at all.
|
||||
pub fn with_save_ext(path: &str, ext: &str) -> String {
|
||||
if save_format(&ext_of(path)).is_some() {
|
||||
return path.to_string();
|
||||
}
|
||||
add_ext(path, ext)
|
||||
}
|
||||
|
||||
/// The path an export in format `ext` writes for a `path` the user named: one whose extension
|
||||
/// isn't that format's (`Report`, `Report.docx` for a PDF) gets `.ext` added, so an export
|
||||
/// writes the format it was asked for (#5368).
|
||||
pub fn with_export_ext(path: &str, ext: &str) -> String {
|
||||
let current = ext_of(path);
|
||||
if current == ext.to_ascii_lowercase() || save_format(¤t).is_some_and(|f| save_format(ext) == Some(f)) {
|
||||
return path.to_string();
|
||||
}
|
||||
add_ext(path, ext)
|
||||
}
|
||||
|
||||
/// `path` with `.ext` after it. Windows drops a file name's trailing dots, so `Report.` is
|
||||
/// `Report.docx`, not `Report..docx`.
|
||||
fn add_ext(path: &str, ext: &str) -> String {
|
||||
format!("{}.{ext}", path.trim_end_matches('.'))
|
||||
}
|
||||
|
||||
/// Is `ext` one of Word's package formats (.docx/.docm/.dotx/.dotm), which save without loss?
|
||||
pub fn is_word_package(ext: &str) -> bool {
|
||||
wordcraft_docx::Flavor::from_ext(ext).is_some()
|
||||
|
||||
@@ -248,7 +248,9 @@ impl Session {
|
||||
/// `file.printPdf`: write the print job's PDF to `path` (no dialogs).
|
||||
pub(crate) fn print_pdf_to_file(s: &mut Session, v: &Value) -> Result<Value, CmdError> {
|
||||
let path = p::req_str(v, "path")?;
|
||||
let path = if path.to_ascii_lowercase().ends_with(".pdf") { path.to_string() } else { format!("{path}.pdf") };
|
||||
// `.pdf` after a name without it, by the rule exports follow (the built-in browser asks
|
||||
// about replacing this same name).
|
||||
let path = crate::io::with_export_ext(path, "pdf");
|
||||
let (bytes, plan) = s.print_pdf(v)?;
|
||||
// Through `io`, so an agent confined to an automation write root (#769) can't print elsewhere.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -13404,6 +13404,40 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
/// #5368: Save As adds the format's extension to a name with none, or with one WordCraft
|
||||
/// doesn't save, as Word adds .docx; a name with a format's extension (any case) is kept.
|
||||
#[test]
|
||||
fn save_as_adds_the_extension_to_a_name_without_a_format() {
|
||||
use crate::io::with_save_ext;
|
||||
assert_eq!(with_save_ext(r"C:\Docs\Report", "docx"), r"C:\Docs\Report.docx");
|
||||
assert_eq!(with_save_ext(r"C:\My.Docs\Report", "docx"), r"C:\My.Docs\Report.docx", "a Windows folder's dot doesn't count either");
|
||||
assert_eq!(with_save_ext("/home/me/Report v1.2", "docx"), "/home/me/Report v1.2.docx");
|
||||
assert_eq!(with_save_ext("/home/me/notes.final", "dotx"), "/home/me/notes.final.dotx");
|
||||
assert_eq!(with_save_ext("/home/me/Report.", "docx"), "/home/me/Report.docx");
|
||||
assert_eq!(with_save_ext("/home/my.docs/Report", "pdf"), "/home/my.docs/Report.pdf", "a dot in a folder name doesn't count");
|
||||
for kept in ["/a/Report.docx", "/a/Report.PDF", "/a/page.htm", "/a/notes.text", "/a/Report.odt"] {
|
||||
assert_eq!(with_save_ext(kept, "docx"), kept);
|
||||
}
|
||||
// Every name it gives saves.
|
||||
let doc = wordcraft_doc::Document::from_text("x");
|
||||
for name in ["Report", "Report v1.2", "Report."] {
|
||||
let path = with_save_ext(name, "docx");
|
||||
assert!(crate::io::save_bytes(&path, &doc).is_ok(), "{path}");
|
||||
}
|
||||
assert!(crate::io::save_bytes("Report v1.2", &doc).is_err(), "it used to fail");
|
||||
// Other spellings name the same format.
|
||||
assert_eq!(crate::io::save_format("HTM"), Some("html"));
|
||||
assert_eq!(crate::io::save_format("text"), Some("txt"));
|
||||
assert_eq!(crate::io::save_format("2"), None);
|
||||
// An export writes its own format, whatever format's extension the name has.
|
||||
use crate::io::with_export_ext;
|
||||
assert_eq!(with_export_ext("/a/Handout", "pdf"), "/a/Handout.pdf");
|
||||
assert_eq!(with_export_ext("/a/Handout.docx", "pdf"), "/a/Handout.docx.pdf");
|
||||
assert_eq!(with_export_ext("/a/Handout.PDF", "pdf"), "/a/Handout.PDF");
|
||||
assert_eq!(with_export_ext("/a/page.htm", "html"), "/a/page.htm");
|
||||
assert_eq!(with_export_ext("/a/shot.pdf", "png"), "/a/shot.pdf.png");
|
||||
}
|
||||
|
||||
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
|
||||
/// formats' are; one with a stated size keeps it, in line too.
|
||||
#[test]
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use egui::{Align2, Rect, Sense, Ui, pos2, vec2};
|
||||
|
||||
use crate::file_dialogs::{AfterPick, FileDialogRequest, open_filters};
|
||||
use crate::file_dialogs::{AfterPick, FileDialogRequest, format_name, open_filters, save_filters};
|
||||
use crate::print_page::{EXPORT_FORMATS, export_file_ext, export_name, is_document_ext};
|
||||
use crate::theme::{Tokens, regular};
|
||||
use crate::{WordApp, icons};
|
||||
@@ -154,9 +154,18 @@ impl FileBrowser {
|
||||
FileDialogRequest::Open { purpose } | FileDialogRequest::OpenMany { purpose } => {
|
||||
(String::new(), open_filters(purpose).iter().map(|(l, e)| ((*l).to_string(), e.iter().map(|x| (*x).to_string()).collect())).collect())
|
||||
}
|
||||
FileDialogRequest::Save { name, .. } => {
|
||||
// Print's Save as PDF writes a PDF whatever type is picked: only that one, then All
|
||||
// files. (An export's types are File › Export's formats, below.)
|
||||
FileDialogRequest::Save { name, .. } if matches!(after, AfterPick::PrintPdf { .. }) => {
|
||||
let ext = Path::new(name).extension().and_then(std::ffi::OsStr::to_str).filter(|e| !e.is_empty());
|
||||
let mut f: Vec<(String, Vec<String>)> = ext.map(|e| (format!("*.{e}"), vec![e.to_string()])).into_iter().collect();
|
||||
let mut f: Vec<(String, Vec<String>)> =
|
||||
ext.map(|e| (format!("{} (*.{e})", format_name(&e.to_ascii_lowercase())), vec![e.to_string()])).into_iter().collect();
|
||||
f.push(("All files".into(), vec!["*".into()]));
|
||||
(name.clone(), f)
|
||||
}
|
||||
// Every format WordCraft saves, the suggested one first, as the system dialog lists them (#5368).
|
||||
FileDialogRequest::Save { name, .. } => {
|
||||
let mut f = save_filters(name);
|
||||
f.push(("All files".into(), vec!["*".into()]));
|
||||
(name.clone(), f)
|
||||
}
|
||||
@@ -202,14 +211,27 @@ impl FileBrowser {
|
||||
self.note = Note::None;
|
||||
}
|
||||
|
||||
/// A type was chosen: when exporting it is the format, and the name's export extension follows it.
|
||||
/// A type was chosen: when exporting it is the format, and the name's export extension follows
|
||||
/// it. Saving, the name's extension changes to the type's when it is a format's
|
||||
/// (`Report.docx` → `Report.pdf`), so the type picked is the type saved (#5368).
|
||||
fn type_changed(&mut self) {
|
||||
let Some(format) = self.exports.get(self.filter).cloned() else { return };
|
||||
// Only a known document extension is replaced; `notes.v2` keeps its `.v2`.
|
||||
if Path::new(&self.name).extension().and_then(|e| e.to_str()).is_some_and(is_document_ext) {
|
||||
self.name = export_name(&self.name, &format);
|
||||
if let Some(format) = self.exports.get(self.filter).cloned() {
|
||||
// Only a known document extension is replaced; `notes.v2` keeps its `.v2`.
|
||||
if Path::new(&self.name).extension().and_then(|e| e.to_str()).is_some_and(is_document_ext) {
|
||||
self.name = export_name(&self.name, &format);
|
||||
}
|
||||
self.after = AfterPick::Export { ext: format };
|
||||
return;
|
||||
}
|
||||
if !matches!(self.req, FileDialogRequest::Save { .. }) {
|
||||
return;
|
||||
}
|
||||
let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*").cloned() else { return };
|
||||
let path = Path::new(&self.name);
|
||||
let typed = path.extension().and_then(std::ffi::OsStr::to_str);
|
||||
if typed.and_then(wordcraft_engine::io::save_format).is_some() {
|
||||
self.name = path.with_extension(ext).to_string_lossy().into_owned();
|
||||
}
|
||||
self.after = AfterPick::Export { ext: format };
|
||||
}
|
||||
|
||||
fn up(&mut self) {
|
||||
@@ -245,11 +267,13 @@ impl FileBrowser {
|
||||
// The chosen type is the format: its extension replaces a known document
|
||||
// extension on the name, and is added to any other.
|
||||
path = PathBuf::from(export_name(&path.to_string_lossy(), ext));
|
||||
} else if path.extension().is_none()
|
||||
&& let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*")
|
||||
{
|
||||
path.set_extension(ext);
|
||||
} else if let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*") {
|
||||
// A name with no extension WordCraft saves (`Report v1.2`) gets the type's (#5368).
|
||||
path = PathBuf::from(wordcraft_engine::io::with_save_ext(&path.to_string_lossy(), ext));
|
||||
}
|
||||
// Then the save's own rule (All files: the suggested format; Print's Save as PDF:
|
||||
// `.pdf`), so a file about to be replaced is asked about under its written name.
|
||||
path = PathBuf::from(self.after.written_path(&path.to_string_lossy()));
|
||||
if path.exists() && self.note != Note::Replace(path.clone()) {
|
||||
self.note = Note::Replace(path);
|
||||
return Step::Stay;
|
||||
@@ -300,6 +324,24 @@ impl WordApp {
|
||||
self.file_browser.open = Some(Box::new(FileBrowser::new(req, after, start, unavailable)));
|
||||
}
|
||||
|
||||
/// Ask whether to replace `path` before a save or export writes it: the built-in browser on
|
||||
/// its folder and name, saying it exists (#5368 review). The system dialog only asked about
|
||||
/// the name it returned, and the save added an extension to that. OK replaces the file,
|
||||
/// another name saves there, Cancel cancels the save.
|
||||
pub(crate) fn confirm_replace(&mut self, req: FileDialogRequest, after: AfterPick, path: PathBuf) {
|
||||
let req = match req {
|
||||
FileDialogRequest::Save { .. } => FileDialogRequest::Save {
|
||||
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
dir: path.parent().filter(|d| d.is_dir()).map(|d| d.to_string_lossy().into_owned()),
|
||||
},
|
||||
other => other,
|
||||
};
|
||||
self.show_file_browser(req, after, false);
|
||||
if let Some(b) = self.file_browser.open.as_mut() {
|
||||
b.note = Note::Replace(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save,
|
||||
/// export), even when a system dialog was asked for and never showed up (it is given up as cancelled).
|
||||
pub(crate) fn browse_builtin(&mut self, purpose: &str) {
|
||||
@@ -311,10 +353,11 @@ impl WordApp {
|
||||
let (req, after) = match purpose {
|
||||
"picture" => (FileDialogRequest::Open { purpose: "picture".into() }, AfterPick::Picture),
|
||||
"recipients" => (FileDialogRequest::Open { purpose: "recipients".into() }, AfterPick::Recipients),
|
||||
"save" => (
|
||||
FileDialogRequest::Save { name: self.default_save_name(), dir: None },
|
||||
AfterPick::SaveAs { after: crate::file_dialogs::AfterSave::Nothing, document: self.session.document_id() },
|
||||
),
|
||||
"save" => {
|
||||
let name = self.default_save_name();
|
||||
let after = AfterPick::save_as(crate::file_dialogs::AfterSave::Nothing, self.session.document_id(), &name);
|
||||
(FileDialogRequest::Save { name, dir: None }, after)
|
||||
}
|
||||
"export" => {
|
||||
let ext = pending.unwrap_or_else(|| "pdf".into());
|
||||
let name = format!("{}.{}", self.title_stem(), export_file_ext(&ext));
|
||||
@@ -602,6 +645,66 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #5368: the built-in Save As lists every format WordCraft saves, the suggested one first;
|
||||
/// picking a type changes the name's extension to it, a name with no format's extension gets
|
||||
/// the type's, and the replace prompt is about the file that will be written.
|
||||
#[test]
|
||||
fn save_lists_every_format_and_the_type_picked_is_saved() {
|
||||
let dir = scratch("save-types");
|
||||
let req = FileDialogRequest::Save { name: "Document1.docx".into(), dir: None };
|
||||
let after = AfterPick::save_as(crate::file_dialogs::AfterSave::Nothing, 0, "Document1.docx");
|
||||
let mut b = FileBrowser::new(req, after, dir.clone(), false);
|
||||
assert_eq!(b.filters.len(), wordcraft_engine::io::SAVE_EXTS.len() + 1, "every format, then All files");
|
||||
assert_eq!(b.filters[0].1, ["docx"]);
|
||||
assert_eq!(b.filters.last().map(|f| f.1.clone()), Some(vec!["*".to_string()]));
|
||||
let pdf = b.filters.iter().position(|(_, e)| e[0] == "pdf").unwrap();
|
||||
b.filter = pdf;
|
||||
b.type_changed();
|
||||
assert_eq!(b.name, "Document1.pdf");
|
||||
assert_eq!(b.accept(), Step::Pick(dir.join("Document1.pdf")));
|
||||
b.name = "Report v1.2".into();
|
||||
b.type_changed();
|
||||
assert_eq!(b.name, "Report v1.2", "a name with no format's extension isn't changed");
|
||||
assert_eq!(b.accept(), Step::Pick(dir.join("Report v1.2.pdf")));
|
||||
// Another spelling of a format is a format's extension too.
|
||||
b.name = "Page.htm".into();
|
||||
b.type_changed();
|
||||
assert_eq!(b.name, "Page.pdf");
|
||||
// All files: the suggested format, and a file of that name is asked about before it's replaced.
|
||||
b.filter = b.filters.len() - 1;
|
||||
b.type_changed();
|
||||
b.name = "Bare".into();
|
||||
assert_eq!(b.accept(), Step::Pick(dir.join("Bare.docx")));
|
||||
std::fs::write(dir.join("Bare.docx"), b"x").unwrap();
|
||||
assert_eq!(b.accept(), Step::Stay, "asks before replacing Bare.docx");
|
||||
assert_eq!(b.accept(), Step::Pick(dir.join("Bare.docx")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #5368 review: Print's Save as PDF writes a PDF whatever type is picked, so the built-in
|
||||
/// browser offers only that one and All files; the file asked about before it's replaced is
|
||||
/// the one written, `.pdf` added as `file.printPdf` adds it. (An export's types are File ›
|
||||
/// Export's formats, and the one picked is written: `export_types_choose_the_format_and_the_extension`.)
|
||||
#[test]
|
||||
fn print_to_pdf_lists_only_pdf() {
|
||||
let dir = scratch("export-types");
|
||||
let req = FileDialogRequest::Save { name: "Handout.pdf".into(), dir: None };
|
||||
let mut b = FileBrowser::new(req, AfterPick::PrintPdf { settings: serde_json::json!({}) }, dir.clone(), false);
|
||||
assert_eq!(b.filters.len(), 2, "{:?}", b.filters);
|
||||
assert_eq!(b.filters[0].1, ["pdf"]);
|
||||
assert!(b.filters[0].0.starts_with("PDF"), "{}", b.filters[0].0);
|
||||
assert_eq!(b.filters[1].1, ["*"]);
|
||||
b.filter = 1;
|
||||
b.type_changed();
|
||||
b.name = "Handout.docx".into();
|
||||
assert_eq!(b.accept(), Step::Pick(dir.join("Handout.docx.pdf")), "a PDF is written, named so");
|
||||
std::fs::write(dir.join("Notes.pdf"), b"x").unwrap();
|
||||
b.name = "Notes".into();
|
||||
assert_eq!(b.accept(), Step::Stay, "asks before replacing Notes.pdf");
|
||||
assert_eq!(b.accept(), Step::Pick(dir.join("Notes.pdf")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The host can't show a system dialog (#576): Save As carries on in the built-in browser,
|
||||
/// and its answer saves the document.
|
||||
#[test]
|
||||
|
||||
@@ -55,14 +55,69 @@ pub fn open_filters(purpose: &str) -> &'static [(&'static str, &'static [&'stati
|
||||
}
|
||||
}
|
||||
|
||||
/// The file types Save As offers: every format the engine saves, with the suggested name's own
|
||||
/// format first. rfd makes a filter's first extension the dialog's default, which the Windows,
|
||||
/// macOS and Linux panels append to a file name the user typed without one; with no filter at
|
||||
/// all the name came back bare and the save failed, since the format is chosen by extension
|
||||
/// (#689). The built-in browser lists them too (#5368).
|
||||
pub fn save_exts(name: &str) -> Vec<String> {
|
||||
let saves = wordcraft_engine::io::SAVE_EXTS;
|
||||
let suggested = std::path::Path::new(name)
|
||||
.extension()
|
||||
.and_then(std::ffi::OsStr::to_str)
|
||||
.map(str::to_ascii_lowercase)
|
||||
// A .markdown file is under Markdown's one entry in the list.
|
||||
.map(|e| if e == "markdown" { "md".to_string() } else { e })
|
||||
.filter(|e| saves.contains(&e.as_str()))
|
||||
.unwrap_or_else(|| "docx".to_string());
|
||||
let mut exts: Vec<String> = Vec::with_capacity(saves.len());
|
||||
exts.push(suggested.clone());
|
||||
exts.extend(saves.iter().filter(|e| **e != suggested).map(|e| (*e).to_string()));
|
||||
exts
|
||||
}
|
||||
|
||||
/// The "Save as type" list (#1399): one named entry per format, the suggested one first (see
|
||||
/// [`save_exts`] for why the order matters).
|
||||
///
|
||||
/// On Linux and the BSDs, the app asks the desktop portal directly over D-Bus and gives a name
|
||||
/// the dialog left alone the chosen type's extension (#6180). When falling back to `rfd`, the
|
||||
/// extension in the name wins, as `rfd` doesn't report which entry the user picked.
|
||||
pub fn save_filters(name: &str) -> Vec<(String, Vec<String>)> {
|
||||
save_exts(name).into_iter().map(|e| (format!("{} (*.{e})", format_name(&e)), vec![e])).collect()
|
||||
}
|
||||
|
||||
/// A readable name for a save format's extension.
|
||||
pub(crate) fn format_name(ext: &str) -> String {
|
||||
match ext {
|
||||
"docx" => "Word Document".into(),
|
||||
"docm" => "Word Macro-Enabled Document".into(),
|
||||
"dotx" => "Word Template".into(),
|
||||
"dotm" => "Word Macro-Enabled Template".into(),
|
||||
"pdf" => "PDF".into(),
|
||||
"txt" => "Plain Text".into(),
|
||||
"md" => "Markdown".into(),
|
||||
"html" => "Web Page".into(),
|
||||
"rtf" => "Rich Text Format".into(),
|
||||
"odt" => "OpenDocument Text".into(),
|
||||
"ott" => "OpenDocument Text Template".into(),
|
||||
"fodt" => "Flat OpenDocument Text".into(),
|
||||
"tex" => "LaTeX".into(),
|
||||
"png" => "PNG Image".into(),
|
||||
"json" => "JSON".into(),
|
||||
"xml" => "XML".into(),
|
||||
other => other.to_ascii_uppercase(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What to do with the path picked in a dialog.
|
||||
pub(crate) enum AfterPick {
|
||||
/// Open the picked document from the window showing `document` ([`WordApp::open_file`]).
|
||||
OpenDocument { document: u64 },
|
||||
/// Insert the picked picture, or replace the pending Change Picture target.
|
||||
Picture,
|
||||
/// Save the document there, then carry on.
|
||||
SaveAs { after: AfterSave, document: u64 },
|
||||
/// Save the document there, then carry on. A name with no extension WordCraft saves gets
|
||||
/// `ext`, the suggested name's (#5368).
|
||||
SaveAs { after: AfterSave, document: u64, ext: String },
|
||||
/// Save a copy there in this format (`pdf`, `docx`, `png`…).
|
||||
Export { ext: String },
|
||||
/// Write the PDF of these print settings there (File › Print › Save these pages as PDF).
|
||||
@@ -82,6 +137,30 @@ pub(crate) enum AfterPick {
|
||||
ComparePath { revised: bool },
|
||||
}
|
||||
|
||||
impl AfterPick {
|
||||
/// Save As for `document`, suggested as `name`: its extension is the format a name typed
|
||||
/// without one is saved in (`.docx` when it has none).
|
||||
pub(crate) fn save_as(after: AfterSave, document: u64, name: &str) -> Self {
|
||||
let ext = std::path::Path::new(name).extension().and_then(std::ffi::OsStr::to_str).filter(|e| !e.is_empty()).unwrap_or("docx");
|
||||
AfterPick::SaveAs { after, document, ext: ext.to_ascii_lowercase() }
|
||||
}
|
||||
|
||||
/// The path a save or export writes for the `path` picked (#5368): Save As adds the format's
|
||||
/// extension to a name with none it saves; an export names the file as the built-in browser
|
||||
/// does (`print_page::export_name`: its format's extension replaces a known document one and
|
||||
/// is added to any other); Print's Save as PDF adds `.pdf` to a name without it, as
|
||||
/// `file.printPdf` does. Applied before asking to replace a file too, so the file asked about
|
||||
/// is the one written.
|
||||
pub(crate) fn written_path(&self, path: &str) -> String {
|
||||
match self {
|
||||
AfterPick::SaveAs { ext, .. } => wordcraft_engine::io::with_save_ext(path, ext),
|
||||
AfterPick::Export { ext } => crate::print_page::export_name(path, ext),
|
||||
AfterPick::PrintPdf { .. } => wordcraft_engine::io::with_export_ext(path, "pdf"),
|
||||
_ => path.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What to do once Save As has written the document.
|
||||
pub(crate) enum AfterSave {
|
||||
Nothing,
|
||||
@@ -149,7 +228,7 @@ impl WordApp {
|
||||
}
|
||||
FileDialogRequest::Save { name, .. } => self.services.pick_save.as_ref().and_then(|f| f(name)),
|
||||
};
|
||||
Asked::Done(self.finish_pick(after, picked))
|
||||
self.finish_system_pick(req, after, picked.into_iter().collect()).map_or(Asked::Pending, Asked::Done)
|
||||
}
|
||||
|
||||
/// Pick up the answer of an open file dialog, if it has arrived (every frame, from `logic`),
|
||||
@@ -163,7 +242,7 @@ impl WordApp {
|
||||
};
|
||||
let d = self.file_dialog.take()?;
|
||||
match answer {
|
||||
Ok(picked) => Some(self.finish_picks(d.after, picked)),
|
||||
Ok(picked) => self.finish_system_pick(d.req, d.after, picked),
|
||||
Err(reason) => {
|
||||
log::warn!("no system file dialog ({reason}); showing the built-in file browser");
|
||||
self.dialog_unavailable(d.req, d.after)
|
||||
@@ -198,6 +277,24 @@ impl WordApp {
|
||||
Some(self.finish_pick(after, None))
|
||||
}
|
||||
|
||||
/// Finish what the system dialog was for with its answer. A save or export that writes another
|
||||
/// name than the one picked (its extension added, #5368) asks first when a file of that name
|
||||
/// exists: the system dialog only asked about the name it returned (#5368 review). `None`
|
||||
/// while that question is open in the built-in browser.
|
||||
fn finish_system_pick(&mut self, req: FileDialogRequest, after: AfterPick, picked: Vec<String>) -> Option<Result<Value, String>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(p) = picked.first() {
|
||||
let written = after.written_path(p);
|
||||
if written != *p && std::path::Path::new(&written).exists() {
|
||||
self.confirm_replace(req, after, std::path::PathBuf::from(written));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = req;
|
||||
Some(self.finish_picks(after, picked))
|
||||
}
|
||||
|
||||
/// Do what the dialog was for with the picked paths (none: the user cancelled). Only Add Font
|
||||
/// takes more than one; the others use the first.
|
||||
fn finish_picks(&mut self, after: AfterPick, picked: Vec<String>) -> Result<Value, String> {
|
||||
@@ -247,6 +344,8 @@ impl WordApp {
|
||||
|
||||
/// Do what the dialog was for with the picked path (`None`: the user cancelled).
|
||||
pub(crate) fn finish_pick(&mut self, after: AfterPick, picked: Option<String>) -> Result<Value, String> {
|
||||
// An export names its file itself, below, and won't replace a file under a new name.
|
||||
let picked = if matches!(after, AfterPick::Export { .. }) { picked } else { picked.map(|p| after.written_path(&p)) };
|
||||
match after {
|
||||
AfterPick::OpenDocument { document } => {
|
||||
let Some(path) = picked else { return Ok(json!({"cancelled": true})) };
|
||||
@@ -302,21 +401,22 @@ impl WordApp {
|
||||
self.clear_export_error();
|
||||
return Ok(json!({"cancelled": true}));
|
||||
};
|
||||
// A system Save dialog lets the user type any name, and the engine picks the format
|
||||
// by the extension (an explicit format only for an .xml path): the file is named as
|
||||
// the built-in browser names it (`notes.docx` as PDF is `notes.pdf`, `notes.v2`
|
||||
// `notes.v2.pdf`, #5368). A file of that name the dialog never confirmed isn't
|
||||
// replaced (the system dialog's answer asks first, `finish_system_pick`).
|
||||
let named = crate::print_page::export_name(&path, &ext);
|
||||
if named != path {
|
||||
path = named;
|
||||
if std::path::Path::new(&path).exists() {
|
||||
// Callers drop the result, so say it where the person sees it.
|
||||
return Err(self.fail_export(format!("{path} already exists; choose another name")));
|
||||
}
|
||||
}
|
||||
let r = if ext == "png" {
|
||||
self.run("file.exportPng", json!({"path": path}))
|
||||
} else if ext == "xml" || ext == crate::print_page::EXPORT_WORD_2003 {
|
||||
// The engine takes an explicit format only for an .xml path, and a system Save
|
||||
// dialog lets the user type any name: give it the extension, as the built-in
|
||||
// browser does (`notes.docx` becomes `notes.xml`, `notes.v2` `notes.v2.xml`).
|
||||
let named = crate::print_page::export_name(&path, "xml");
|
||||
if named != path {
|
||||
path = named;
|
||||
// The dialog only confirmed the name it was given, not this one.
|
||||
if std::path::Path::new(&path).exists() {
|
||||
// Callers drop the result, so say it where the person sees it.
|
||||
return Err(self.fail_export(format!("{path} already exists; choose another name")));
|
||||
}
|
||||
}
|
||||
// Word XML even over a Word 2003 XML file, which a save by path would keep.
|
||||
let format = if ext == "xml" { wordcraft_engine::cmd::file::FORMAT_FLAT_OPC } else { crate::print_page::EXPORT_WORD_2003 };
|
||||
self.run("file.saveAs", json!({"path": path, "format": format}))
|
||||
@@ -344,7 +444,7 @@ impl WordApp {
|
||||
}
|
||||
r
|
||||
}
|
||||
AfterPick::SaveAs { after, document } => {
|
||||
AfterPick::SaveAs { after, document, .. } => {
|
||||
// The document it was for may wait behind another one: it is shown and saved.
|
||||
if document != self.session.document_id() {
|
||||
if !self.session.is_open(document) {
|
||||
@@ -431,7 +531,8 @@ impl WordApp {
|
||||
/// Ask where to save, save there, then do `after`.
|
||||
pub(crate) fn save_as(&mut self, after: AfterSave) -> Asked {
|
||||
let name = self.default_save_name();
|
||||
self.ask_file(FileDialogRequest::Save { name, dir: None }, AfterPick::SaveAs { after, document: self.session.document_id() })
|
||||
let after = AfterPick::save_as(after, self.session.document_id(), &name);
|
||||
self.ask_file(FileDialogRequest::Save { name, dir: None }, after)
|
||||
}
|
||||
|
||||
/// The user templates folder (#2852): the one File › Options names, else the app's own.
|
||||
@@ -467,7 +568,7 @@ impl WordApp {
|
||||
}
|
||||
let dir = dir.filter(|d| d.is_dir()).map(|d| d.to_string_lossy().into_owned());
|
||||
let name = format!("{}.dotx", self.title_stem());
|
||||
let after = AfterPick::SaveAs { after: AfterSave::Nothing, document: self.session.document_id() };
|
||||
let after = AfterPick::save_as(AfterSave::Nothing, self.session.document_id(), &name);
|
||||
let _ = self.ask_file(FileDialogRequest::Save { name, dir: dir.clone() }, after);
|
||||
dir
|
||||
}
|
||||
|
||||
@@ -826,3 +826,118 @@ fn many_failed_fonts_end_with_a_count() {
|
||||
let msg = a.status_msg.as_ref().map(|(m, _)| m.clone()).unwrap_or_default();
|
||||
assert_eq!(msg, "Added 0 fonts; 5 couldn't be read: f0.ttf, f1.ttf, f2.ttf and 2 more");
|
||||
}
|
||||
|
||||
/// #5368: a name typed without an extension WordCraft saves is saved in the suggested format, as
|
||||
/// Word adds .docx, instead of failing (the format is chosen by extension); a template keeps
|
||||
/// .dotx and an export its own format.
|
||||
#[test]
|
||||
fn save_as_adds_the_format_to_a_name_without_one() {
|
||||
let dir = scratch("save-as-ext");
|
||||
let (mut a, shown) = async_app();
|
||||
typed(&mut a);
|
||||
for (name, saved) in [("Report", "Report.docx"), ("Report v1.2", "Report v1.2.docx"), ("Notes.", "Notes.docx"), ("Kept.DOCX", "Kept.DOCX")] {
|
||||
a.save_as_dialog();
|
||||
answer(&shown, Some(&dir.join(name).to_string_lossy()));
|
||||
assert_eq!(a.poll_file_dialog().unwrap().unwrap()["saved"], true, "{name}");
|
||||
let path = dir.join(saved);
|
||||
assert_eq!(a.session.path.as_deref(), Some(path.as_path()), "{name}");
|
||||
assert_eq!(saved_text(&path), UNSAVED, "{name}");
|
||||
}
|
||||
|
||||
a.services.templates_dir = Some(dir.join("Templates"));
|
||||
a.run("ui.saveAsTemplate", json!({})).unwrap();
|
||||
answer(&shown, Some(&dir.join("Templates").join("Memo").to_string_lossy()));
|
||||
assert_eq!(a.poll_file_dialog().unwrap().unwrap()["saved"], true);
|
||||
assert!(dir.join("Templates").join("Memo.dotx").is_file(), "a template stays a template");
|
||||
|
||||
a.export_dialog("pdf");
|
||||
answer(&shown, Some(&dir.join("Handout").to_string_lossy()));
|
||||
assert!(a.poll_file_dialog().unwrap().is_ok());
|
||||
assert!(std::fs::read(dir.join("Handout.pdf")).unwrap().starts_with(b"%PDF"), "an export keeps its format");
|
||||
// A name with another document format's extension is still a PDF, named as the built-in
|
||||
// browser names it (`print_page::export_name`).
|
||||
a.export_dialog("pdf");
|
||||
answer(&shown, Some(&dir.join("Flyer.docx").to_string_lossy()));
|
||||
assert!(a.poll_file_dialog().unwrap().is_ok());
|
||||
assert!(std::fs::read(dir.join("Flyer.pdf")).unwrap().starts_with(b"%PDF"));
|
||||
assert!(!dir.join("Flyer.docx").exists(), "no Word file written for a PDF export");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #5368 (review): the system dialog asks only about the name it returns. When the save adds an
|
||||
/// extension to it and a file of that name exists, the built-in browser asks before replacing
|
||||
/// it: Cancel leaves the file alone, OK replaces it. A new name is written straight away.
|
||||
#[test]
|
||||
fn a_name_the_save_extends_asks_before_replacing_its_file() {
|
||||
use crate::file_browser::Step;
|
||||
let dir = scratch("save-as-ext-replace");
|
||||
let (mut a, shown) = async_app();
|
||||
typed(&mut a);
|
||||
let target = dir.join("Handout.pdf");
|
||||
std::fs::write(&target, b"old").unwrap();
|
||||
let export = |a: &mut WordApp| {
|
||||
a.export_dialog("pdf");
|
||||
answer(&shown, Some(&dir.join("Handout.docx").to_string_lossy()));
|
||||
a.poll_file_dialog()
|
||||
};
|
||||
assert!(export(&mut a).is_none(), "nothing written yet: the question is open");
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"old");
|
||||
assert!(a.file_browser.open.is_some(), "the built-in browser asks");
|
||||
a.close_file_browser(None);
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"old", "Cancel keeps the file");
|
||||
assert!(export(&mut a).is_none());
|
||||
let step = a.file_browser.open.as_mut().map(|b| b.accept());
|
||||
assert_eq!(step, Some(Step::Pick(target.clone())), "OK on the name asked about replaces it");
|
||||
a.close_file_browser(Some(target.clone()));
|
||||
assert!(std::fs::read(&target).unwrap().starts_with(b"%PDF"), "replaced by the export");
|
||||
// A name whose extended form doesn't exist yet: no question.
|
||||
a.export_dialog("pdf");
|
||||
answer(&shown, Some(&dir.join("Fresh.docx").to_string_lossy()));
|
||||
assert!(a.poll_file_dialog().is_some_and(|r| r.is_ok()));
|
||||
assert!(std::fs::read(dir.join("Fresh.pdf")).unwrap().starts_with(b"%PDF"));
|
||||
assert!(a.file_browser.open.is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #1399: the Save dialog's type list has one named entry per format, the suggested one first,
|
||||
/// every savable extension exactly once.
|
||||
#[test]
|
||||
fn save_dialog_lists_one_named_type_per_format() {
|
||||
let filters = save_filters("report.odt");
|
||||
assert_eq!(filters.len(), wordcraft_engine::io::SAVE_EXTS.len());
|
||||
assert_eq!(filters[0].1, vec!["odt".to_string()]);
|
||||
assert!(filters[0].0.contains("OpenDocument"), "{}", filters[0].0);
|
||||
let all: Vec<&String> = filters.iter().flat_map(|(_, e)| e).collect();
|
||||
for e in wordcraft_engine::io::SAVE_EXTS {
|
||||
assert_eq!(all.iter().filter(|x| x.as_str() == *e).count(), 1, "{e}");
|
||||
}
|
||||
assert!(filters.iter().all(|(l, e)| !l.trim().is_empty() && e.len() == 1));
|
||||
let mut labels: Vec<&String> = filters.iter().map(|(l, _)| l).collect();
|
||||
labels.sort();
|
||||
labels.dedup();
|
||||
assert_eq!(labels.len(), filters.len(), "labels are distinct");
|
||||
// Unknown names fall back to Word's format first.
|
||||
assert_eq!(save_filters("no extension")[0].1, vec!["docx".to_string()]);
|
||||
// The OpenDocument template and flat file have their own names.
|
||||
assert!(save_filters("plan.fodt")[0].0.starts_with("Flat OpenDocument Text"));
|
||||
assert!(save_filters("form.ott")[0].0.starts_with("OpenDocument Text Template"));
|
||||
}
|
||||
|
||||
/// #689: the Save dialog's default extension is the suggested name's own format, so a file
|
||||
/// name the user types without one is saved in the document's format instead of coming back
|
||||
/// bare and failing.
|
||||
#[test]
|
||||
fn save_dialog_defaults_to_the_suggested_format() {
|
||||
assert_eq!(save_exts("novel.docx")[0], "docx");
|
||||
assert_eq!(save_exts("report.odt")[0], "odt");
|
||||
assert_eq!(save_exts("annual report.pdf")[0], "pdf");
|
||||
assert_eq!(save_exts("notes.md")[0], "md");
|
||||
assert_eq!(save_exts("notes.markdown")[0], "md");
|
||||
// A suggested name always has an extension; anything unreadable falls back to Word's.
|
||||
assert_eq!(save_exts("no extension")[0], "docx");
|
||||
assert_eq!(save_exts("mystery.rtf2")[0], "docx");
|
||||
// Every savable format is still offered, once.
|
||||
let exts = save_exts("novel.docx");
|
||||
assert!(wordcraft_engine::io::SAVE_EXTS.iter().all(|e| exts.iter().any(|x| x == e)));
|
||||
assert_eq!(exts.len(), wordcraft_engine::io::SAVE_EXTS.len());
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ pub use dialogs::dialogs_ribbon;
|
||||
pub use dialogs::dialogs_smart_art;
|
||||
pub use dialogs::dialogs_table_style;
|
||||
pub use dialogs::dialogs_templates;
|
||||
pub use file_dialogs::{FileDialogAnswer, FileDialogRequest, open_filters};
|
||||
pub use file_dialogs::{FileDialogAnswer, FileDialogRequest, open_filters, save_filters};
|
||||
|
||||
mod app;
|
||||
mod clock;
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
+3
-2
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user