diff --git a/Cargo.lock b/Cargo.lock index b5981722e0..4fc09a2805 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5142,6 +5142,7 @@ dependencies = [ "pdfcraft-testkit", "pdfcraft-xfa", "pdfcraft-xfdf", + "rustix 1.1.6", "thiserror 2.0.21", "unicode-segmentation", "url", diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 212664a37a..866f441562 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -64,6 +64,7 @@ impl Automation { } "doc_close" => self.doc_close(&a)?, "doc_save" => self.doc_save(&a)?, + "doc_rename" => self.doc_rename(&a)?, "doc_set_info" => { let edit = Edit::SetInfo { key: a.str("key")?.into(), value: a.str("value")?.into() }; self.apply(&a, edit)? diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index 7dd78cff98..47ffb8583f 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -1,7 +1,7 @@ use super::error::{Result, ToolError, failed}; use super::json::{Args, nest_rows, security, summary}; use super::paths::{child, read_input, write_atomic}; -use super::{Arc, Automation, BlockKey, DocId, Document, Edit, Path, TextBlock, Value, comments, json}; +use super::{Arc, Automation, BlockKey, DocId, Document, Edit, Path, PathBuf, TextBlock, Value, comments, file_access, json}; /// How far a watermark may be moved from the page centre, in points (a page is at most 14,400). const WATERMARK_MAX_OFFSET: f64 = 20_000.0; @@ -183,6 +183,33 @@ impl Automation { Ok(out) } + /// Rename the document's file in its own folder (#2102). Both the old and the new name are + /// writes there, so the automation write root must allow the folder; unsaved changes are refused + /// rather than left behind in a file that no longer matches the document. + pub(crate) fn doc_rename(&mut self, a: &Args) -> Result { + let doc = self.doc(a)?; + let id = doc.id; + let own = doc.path.clone().ok_or_else(|| failed("the document has no file yet: save it with doc_save and a path first"))?; + let name = a.str("name")?; + let own_path = PathBuf::from(&own); + self.resolve_for(&own, file_access::Access::Write, true)?; + if let Some(target) = pdfcraft_engine::rename_target(&own_path, name).map_err(failed)? { + let shown = target.to_string_lossy().into_owned(); + self.resolve_for(&shown, file_access::Access::Write, true)?; + } + // The move is made below the write folder where the system allows it (Linux: no link on the + // way is followed, so a folder swapped for a link after the checks above can't carry the + // file out). macOS and Windows keep the check-then-rename model. + let root = match (self.roots.as_ref().and_then(|r| r.write_root()), self.root.as_deref()) { + (Some(w), Some(r)) => Some(if r.starts_with(w) { r } else { w }), + (w, r) => w.or(r), + } + .map(Path::to_path_buf); + let path = self.session.rename_file_in(id, name, root.as_deref()).map_err(failed)?; + let doc = self.session.get(id).ok_or_else(|| failed("the renamed document is no longer open"))?; + Ok(json!({ "path": path, "name": doc.name.clone(), "document": summary(doc) })) + } + /// Validate the prepared bytes before publishing them or marking the document saved. pub(crate) fn publish_save( &mut self, diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs index 1f3a13cbf0..64c100961b 100644 --- a/crates/automation/src/tests.rs +++ b/crates/automation/src/tests.rs @@ -548,6 +548,34 @@ fn invalid_save_bytes_never_reach_publication_or_mark_saved() { std::fs::remove_dir_all(dir).unwrap(); } +#[test] +fn doc_rename_moves_the_file_and_refuses_with_reasons() { + let dir = staging_dir("rename"); + let mut a = Automation::new().with_root(&dir).unwrap(); + let id = search_document(&mut a, 2); + let err = |a: &mut Automation, args: Value| a.call("doc_rename", &args).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(err(&mut a, json!({"doc": id.0, "name": "x"})).contains("no file yet"), "never saved"); + json(&mut a, "doc_save", json!({"doc": id.0, "path": "first.pdf"})); + std::fs::write(dir.join("taken.pdf"), b"other").unwrap(); + assert!(err(&mut a, json!({"doc": id.0, "name": "taken"})).contains("already exists")); + assert!(err(&mut a, json!({"doc": id.0, "name": "CON"})).contains("reserves")); + assert!(err(&mut a, json!({"doc": id.0, "name": "a/b"})).contains("can't contain")); + let out = json(&mut a, "doc_rename", json!({"doc": id.0, "name": "Second"})); + assert_eq!(out["name"], "Second.pdf"); + assert!(dir.join("Second.pdf").exists() && !dir.join("first.pdf").exists()); + assert_eq!(listing(&dir), ["Second.pdf", "taken.pdf"]); + // Unsaved changes are never left behind in a renamed file. + json(&mut a, "page_rotate", json!({"doc": id.0, "pages": [1], "degrees": 90})); + assert!(err(&mut a, json!({"doc": id.0, "name": "third"})).contains("unsaved changes")); + json(&mut a, "doc_save", json!({"doc": id.0})); + json(&mut a, "doc_rename", json!({"doc": id.0, "name": "third.pdf"})); + assert_eq!( + a.session.get(id).unwrap().path.as_deref().map(Path::new).and_then(Path::file_name).map(|n| n.to_string_lossy().into_owned()).as_deref(), + Some("third.pdf") + ); + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn a_failed_save_sync_keeps_the_document_dirty_and_can_be_retried() { let dir = staging_dir("sync-dirty"); diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index eeca6bce38..719fb7e6b8 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -210,6 +210,13 @@ pub fn tools() -> Vec { }), &["doc"], )), + t( + "doc_rename", + "Rename a document's file", + "Rename the open document's file on disk, in its own folder; the document stays open with its undo history. The extension is kept (added back when left out). Refused, with the reason, when the document has unsaved changes (save first), has no file yet, the name is taken, the file is in use, or the name can't be a file name on Windows, macOS or Linux (no / \\ : * ? \" < > |, no device names such as CON, no trailing dot, at most 255 bytes, a full path within the system limit).", + ) + .destructive() + .with(schema(json!({ "doc": doc(), "name": { "type": "string", "description": "The new file name, with or without the extension." } }), &["doc", "name"])), t("doc_set_info", "Set document metadata", "Set a document information entry such as Title, Author, Subject or Keywords, or a custom property under any other name (no spaces, delimiters, / or #; at most 127 bytes; doc_info lists them under custom); an empty value removes it. When the file has XMP metadata, the matching XMP property (dc:title, dc:creator, dc:description, pdf:Keywords, xmp:CreatorTool, pdf:Producer) is changed too, so viewers that read XMP first show the new value, and a custom property is kept there as pdfx: when its name can be an XML name (in a PDF/A file only one already there is changed). Undoable.") .with(schema(json!({ "doc": doc(), "key": { "type": "string" }, "value": { "type": "string" } }), &["doc", "key", "value"])), t("page_render", "Render a page", "Render one page to a PNG image (default 96 dpi, at most 600). When the picture is incomplete or approximate (content cut at the page's safety budget, a picture left out because its JBIG2 mask is past a decoder limit, a colour painted in a fallback colour), a JSON part follows the image: { page, warnings: [sentence, ...] }.") diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index c059a256f3..d64a59ed93 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -51,6 +51,11 @@ unicode-segmentation = "1.13" chrono = { workspace = true, features = ["clock"] } getrandom = "0.4" +[target.'cfg(target_os = "linux")'.dependencies] +# Already in the graph (platform, automation): the rename an automation root confines is made +# below the root's open folder (rename::rooted). +rustix = { version = "1", features = ["fs"] } + [target.'cfg(target_arch = "wasm32")'.dependencies] getrandom = { version = "0.4", features = ["wasm_js"] } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3f5f1c4e54..8acd2e0f97 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -49,6 +49,7 @@ mod pictures; pub mod print_raster; pub mod printcheck; mod protection; +mod rename; mod rich_copy; pub mod scan_clean; mod scan_colours; @@ -169,6 +170,7 @@ pub use pictures::{MarkFile, image_dimensions}; use pictures::{embed_image, fit_picture, mark_source, model_poster}; use protection::unrestricted; pub use protection::{Changes, Printing, Protection, SecuritySummary}; +pub use rename::{RenameError, new_file_name, rename_target}; pub use session::Session; pub use sources::{CombineSource, Combined, combine_source_check, office_to_pdf, source_page_count}; use sources::{open_source, open_source_with}; diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs new file mode 100644 index 0000000000..e2e93db27d --- /dev/null +++ b/crates/engine/src/rename.rs @@ -0,0 +1,505 @@ +//! Renaming an open document's file on disk (#2102, #2867): the checks a new name has to pass, +//! then the move, after which the document keeps its tab, undo history and everything else; only +//! its file name and path change. +//! +//! The rules are the same on every system, so a file renamed on one keeps working when the folder +//! is synced to another: no path separators or `< > : " | ? *`, no control characters, no Windows +//! device names (`CON`, `NUL`, `COM0`-`COM9`, `LPT0`-`LPT9` and the superscript-digit forms), +//! no name ending in a dot or a space, at most 255 bytes of UTF-8 and 255 UTF-16 code units, and +//! a full path within this system's limit. The file keeps its extension: a name typed without it gets it back. + +use std::path::{Path, PathBuf}; + +use crate::{DocId, Session}; + +/// Why a file could not be renamed. The messages say what to do instead. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RenameError { + /// The document was never saved, so there is no file to rename. + NoFile, + /// The document has unsaved changes: save them first (the file on disk is not this version). + Unsaved, + /// The new name is empty. + Empty, + /// The new name can't be used as a file name; the reason says why. + Invalid(String), + /// Another file already has that name. + Exists(String), + /// The operating system refused (in use by another program, no permission, …). + Failed(String), +} + +impl std::fmt::Display for RenameError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NoFile => write!(f, "the document has no file yet: save it first"), + Self::Unsaved => write!(f, "the document has unsaved changes: save them before renaming"), + Self::Empty => write!(f, "the name is empty"), + Self::Invalid(why) => write!(f, "{why}"), + Self::Exists(name) => write!(f, "a file named {name} already exists in that folder"), + Self::Failed(why) => write!(f, "the file could not be renamed: {why}"), + } + } +} + +impl std::error::Error for RenameError {} + +/// Characters no file name may hold on Windows, refused everywhere. +const RESERVED_CHARS: [char; 9] = ['<', '>', ':', '"', '/', '\\', '|', '?', '*']; +/// Windows device names, refused as a name's stem on every system. +const DEVICE_NAMES: [&str; 33] = [ + "CON", + "PRN", + "AUX", + "NUL", + "COM0", + "COM1", + "COM2", + "COM3", + "COM4", + "COM5", + "COM6", + "COM7", + "COM8", + "COM9", + "COM\u{b9}", + "COM\u{b2}", + "COM\u{b3}", + "LPT0", + "LPT1", + "LPT2", + "LPT3", + "LPT4", + "LPT5", + "LPT6", + "LPT7", + "LPT8", + "LPT9", + "LPT\u{b9}", + "LPT\u{b2}", + "LPT\u{b3}", + "CONIN$", + "CONOUT$", + "CLOCK$", +]; +/// The longest full path this system takes, where it can be known: Windows' `MAX_PATH` (260 with +/// the closing NUL, in UTF-16 units; a `\\?\` path is exempt), Linux's `PATH_MAX` (4096 bytes) and +/// macOS's (1024 bytes). Elsewhere there is no limit to check. +#[cfg(windows)] +const MAX_PATH_LEN: Option = Some(259); +#[cfg(target_os = "macos")] +const MAX_PATH_LEN: Option = Some(1023); +#[cfg(target_os = "linux")] +const MAX_PATH_LEN: Option = Some(4095); +#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] +const MAX_PATH_LEN: Option = None; + +/// The length of `path` in the unit this system limits it in. +fn path_len(path: &Path) -> usize { + #[cfg(windows)] + { + path.as_os_str().encode_wide().count() + } + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + path.as_os_str().as_bytes().len() + } + // Neither (the browser build): the encoded length, which only its tests see. + #[cfg(not(any(unix, windows)))] + { + path.as_os_str().len() + } +} +#[cfg(windows)] +use std::os::windows::ffi::OsStrExt; +/// The longest file name the common file systems take: 255 bytes of UTF-8 (ext4, APFS) and 255 +/// UTF-16 code units (NTFS), so a name is checked against both, never by its characters. +const MAX_NAME_LEN: usize = 255; + +/// The file name `typed` gives the document now at `current`: trimmed, checked, with +/// `current`'s extension added back when it was left out. +pub fn new_file_name(current: &Path, typed: &str) -> Result { + let typed = typed.trim(); + if typed.is_empty() { + return Err(RenameError::Empty); + } + if let Some(c) = typed.chars().find(|c| RESERVED_CHARS.contains(c)) { + return Err(RenameError::Invalid(format!("a file name can't contain {c}"))); + } + if typed.chars().any(char::is_control) { + return Err(RenameError::Invalid("a file name can't contain control characters".into())); + } + if typed.ends_with('.') { + return Err(RenameError::Invalid("a file name can't end with a dot".into())); + } + let ext = current.extension().map(|e| e.to_string_lossy().into_owned()); + let name = match &ext { + Some(ext) if !typed.to_lowercase().ends_with(&format!(".{}", ext.to_lowercase())) => format!("{typed}.{ext}"), + _ => typed.to_owned(), + }; + let stem = name.split('.').next().unwrap_or_default().trim_end(); + if DEVICE_NAMES.iter().any(|d| d.eq_ignore_ascii_case(stem)) { + return Err(RenameError::Invalid(format!("{stem} is a name Windows reserves for a device"))); + } + if name.len() > MAX_NAME_LEN || name.encode_utf16().count() > MAX_NAME_LEN { + return Err(RenameError::Invalid(format!("a file name can be at most {MAX_NAME_LEN} bytes"))); + } + if let Some(limit) = MAX_PATH_LEN { + let full = current.with_file_name(&name); + // Windows' `\\?\` prefix lifts the limit. + let extended = cfg!(windows) && full.to_string_lossy().starts_with(r"\\?\"); + if !extended && path_len(&full) > limit { + return Err(RenameError::Invalid(format!("the full path would be over this system's limit of {limit} characters: use a shorter name"))); + } + } + Ok(name) +} + +/// The path the document now at `current` moves to when renamed to `typed`: the same folder, +/// [`new_file_name`]. `Ok(None)` when nothing would change. +pub fn rename_target(current: &Path, typed: &str) -> Result, RenameError> { + let name = new_file_name(current, typed)?; + let target = current.with_file_name(&name); + if target == current { + return Ok(None); + } + // A name that only changes letter case is the same file on Windows and macOS: let it through. + let same_file = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) { + (Ok(a), Ok(b)) => a == b, + _ => false, + }; + if target.exists() && !same_file(current, &target) { + return Err(RenameError::Exists(name)); + } + Ok(Some(target)) +} + +/// Whether `a` and `b` are one file: a rename that only changes letter case on a case-insensitive +/// file system. +fn same_file(a: &Path, b: &Path) -> bool { + matches!((a.canonicalize(), b.canonicalize()), (Ok(a), Ok(b)) if a == b) +} + +/// Move `old` to `new`, never replacing a file that already has that name (`AlreadyExists`). +/// +/// `std::fs::rename` replaces its target on every system and std has no no-replace rename, so the +/// move is a hard link (which fails atomically when `new` exists) and then the removal of `old`; +/// if `old` can't be removed the new name is taken away again, so a failure never leaves both. Where +/// hard links are not available (FAT/exFAT, some network shares, or any other error that means the +/// link can't be made) it falls back to checking and then renaming: a file created in between is +/// replaced, a window that remains only there. The same file under another letter case is plainly +/// renamed (nothing to replace). +fn move_no_replace(old: &Path, new: &Path) -> std::io::Result<()> { + if same_file(old, new) { + return std::fs::rename(old, new); + } + match std::fs::hard_link(old, new) { + Ok(()) => std::fs::remove_file(old).inspect_err(|_| { + let _ = std::fs::remove_file(new); + }), + Err(e) if matches!(e.kind(), std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::NotFound) => Err(e), + Err(_) => { + if new.symlink_metadata().is_ok() { + return Err(std::io::ErrorKind::AlreadyExists.into()); + } + std::fs::rename(old, new) + } + } +} + +/// The move made below a folder, without following a link (Linux only; see +/// [`Session::rename_file_in`]). +#[cfg(target_os = "linux")] +mod rooted { + use rustix::fs::{AtFlags, Mode, OFlags, RenameFlags, linkat, openat, renameat, renameat_with, statat, unlinkat}; + use rustix::io::Errno; + use std::io::{Error, ErrorKind, Result}; + use std::os::fd::OwnedFd; + use std::path::{Component, Path}; + + fn refused(what: &str) -> Error { + Error::other(format!("the move can't be kept inside the allowed folder: {what}")) + } + + fn open_dir(parent: &OwnedFd, name: &std::ffi::OsStr) -> Result { + openat(parent, name, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty()).map_err(|e| match e { + Errno::LOOP | Errno::NOTDIR => refused("a folder on the way is a link"), + e => e.into(), + }) + } + + /// `path` relative to `root`: as written, or else with its folder's links resolved (the file + /// itself is never resolved). Names below `root` only; `..` and the like are refused. + fn below(root: &Path, path: &Path) -> Result { + let rel = match path.strip_prefix(root) { + Ok(rel) => rel.to_path_buf(), + Err(_) => { + let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else { return Err(refused("no folder")) }; + let dir = dir.canonicalize()?; + dir.strip_prefix(root.canonicalize()?).map_err(|_| refused("the file is outside it"))?.join(name) + } + }; + if rel.components().any(|c| !matches!(c, Component::Normal(_))) { + return Err(refused("an odd name on the way")); + } + Ok(rel) + } + + /// Same as [`super::move_no_replace`], with `old` and `new` (one folder, below `root`) reached + /// from an open `root` by names opened without following links. + pub(super) fn move_no_replace(root: &Path, old: &Path, new: &Path) -> Result<()> { + let (old, new) = (below(root, old)?, below(root, new)?); + let (Some(folder), Some(from), Some(to)) = (old.parent(), old.file_name(), new.file_name()) else { return Err(refused("no file name")) }; + if new.parent() != Some(folder) { + return Err(refused("the new name is in another folder")); + } + let mut dir = openat(rustix::fs::CWD, root, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?; + for part in folder.components() { + dir = open_dir(&dir, part.as_os_str())?; + } + let kept = |e: Errno| -> Error { e.into() }; + match renameat_with(&dir, from, &dir, to, RenameFlags::NOREPLACE) { + Ok(()) => Ok(()), + Err(Errno::EXIST) => { + // The same file under another letter case (case-insensitive folders) is renamed. + let at = |n: &std::ffi::OsStr| statat(&dir, n, AtFlags::SYMLINK_NOFOLLOW); + match (at(from), at(to)) { + (Ok(a), Ok(b)) + if (a.st_dev, a.st_ino) == (b.st_dev, b.st_ino) + && from.to_string_lossy().to_lowercase() == to.to_string_lossy().to_lowercase() => + { + renameat(&dir, from, &dir, to).map_err(kept) + } + _ => Err(ErrorKind::AlreadyExists.into()), + } + } + // No renameat2 / NOREPLACE here: a hard link refuses a taken name atomically, then the + // old name goes (and the new one is taken away again if it can't). + Err(Errno::INVAL | Errno::NOSYS | Errno::OPNOTSUPP) => match linkat(&dir, from, &dir, to, AtFlags::empty()) { + Ok(()) => unlinkat(&dir, from, AtFlags::empty()).map_err(|e| { + let _ = unlinkat(&dir, to, AtFlags::empty()); + kept(e) + }), + Err(e @ (Errno::EXIST | Errno::NOENT)) => Err(e.into()), + Err(_) => { + if statat(&dir, to, AtFlags::SYMLINK_NOFOLLOW).is_ok() { + return Err(ErrorKind::AlreadyExists.into()); + } + renameat(&dir, from, &dir, to).map_err(kept) + } + }, + Err(e) => Err(e.into()), + } + } +} + +impl Session { + /// Rename the file of document `id` to `typed` (see [`rename_target`]), in its own folder. The + /// document must have a file and no unsaved changes. Returns the new path; the document keeps + /// its undo history, only its name and path change. + pub fn rename_file(&mut self, id: DocId, typed: &str) -> Result { + self.rename_file_in(id, typed, None) + } + + /// [`rename_file`](Self::rename_file) for an automation caller confined to the write folder + /// `root`: on Linux the move itself is made below that folder, with no link followed on the way + /// (the folder is opened, each name down to the file's folder is opened with `O_NOFOLLOW`, and + /// the file is renamed with `renameat` there), so a folder swapped for a link between the + /// caller's check and the move can't carry the file out of `root`. Where that can't be done the + /// rename is refused rather than made unconfined. + /// + /// macOS and Windows keep the check-then-rename model the repo documents for confined paths + /// (the caller's check, then a plain rename); `root` is ignored there, as it is when `None`. + pub fn rename_file_in(&mut self, id: DocId, typed: &str, root: Option<&Path>) -> Result { + #[cfg(not(target_os = "linux"))] + let _ = root; + let doc = self.get(id).ok_or_else(|| RenameError::Failed("the document is no longer open".into()))?; + let current = PathBuf::from(doc.path.clone().ok_or(RenameError::NoFile)?); + if doc.dirty { + return Err(RenameError::Unsaved); + } + let Some(target) = rename_target(¤t, typed)? else { + return Ok(current.to_string_lossy().into_owned()); + }; + // Whether the file itself is marked read-only is not checked: renaming needs write access + // to the folder, not to the file, and the system says so when it refuses. + // `rename_target` checked that the name is free, but a file may appear under it before the + // move (a sync client, another program): `move_no_replace` refuses to replace it. + #[cfg(target_os = "linux")] + let moved = match root { + Some(root) => rooted::move_no_replace(root, ¤t, &target), + None => move_no_replace(¤t, &target), + }; + #[cfg(not(target_os = "linux"))] + let moved = move_no_replace(¤t, &target); + moved.map_err(|e| match e.kind() { + std::io::ErrorKind::AlreadyExists => { + RenameError::Exists(target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()) + } + std::io::ErrorKind::PermissionDenied => RenameError::Failed("it is open in another program, or you don't have permission".into()), + std::io::ErrorKind::NotFound => RenameError::Failed("it is no longer where it was opened from".into()), + _ => RenameError::Failed(e.to_string()), + })?; + let path = target.to_string_lossy().into_owned(); + if let Ok(doc) = self.doc_mut(id) { + doc.name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.clone()); + doc.path = Some(path.clone()); + } + Ok(path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn name(typed: &str) -> Result { + new_file_name(Path::new("/docs/report.pdf"), typed) + } + + #[test] + fn the_extension_comes_back_when_left_out() { + assert_eq!(name("Budget 2026"), Ok("Budget 2026.pdf".into())); + assert_eq!(name("Budget.PDF"), Ok("Budget.PDF".into())); + assert_eq!(name(" spaced "), Ok("spaced.pdf".into()), "surrounding spaces are trimmed"); + assert_eq!(name("notes.txt"), Ok("notes.txt.pdf".into()), "another extension is part of the name"); + assert_eq!(name("年度 report"), Ok("年度 report.pdf".into())); + } + + #[test] + fn names_windows_or_other_systems_refuse_are_refused() { + assert_eq!(name(""), Err(RenameError::Empty)); + assert_eq!(name(" "), Err(RenameError::Empty)); + for bad in ["a/b", "a\\b", "a:b", "a*b", "a?b", "a\"b", "ab", "a|b", "tab\there"] { + assert!(matches!(name(bad), Err(RenameError::Invalid(_))), "{bad:?}"); + } + for device in ["CON", "con", "Nul", "COM1", "lpt9", "aux.notes", "PRN "] { + assert!(matches!(name(device), Err(RenameError::Invalid(_))), "{device:?}"); + } + assert!(name("CONSOLE").is_ok(), "only the exact device names are reserved"); + assert!(matches!(name("trailing."), Err(RenameError::Invalid(_)))); + // A trailing space goes with the trim, which leaves the dot at the end to be refused. + assert!(matches!(name("a. "), Err(RenameError::Invalid(_)))); + assert!(matches!(name("report.pdf."), Err(RenameError::Invalid(_)))); + assert!(matches!(name(&"x".repeat(252)), Err(RenameError::Invalid(_))), "252 + .pdf is over 255"); + assert!(name(&"x".repeat(251)).is_ok()); + } + + #[test] + fn renaming_moves_the_file_and_refuses_what_it_must() { + let dir = std::env::temp_dir().join(format!("pdfcraft-rename-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("first.pdf"); + let mut session = Session::new(); + let bytes = session.create_blank(200.0, 300.0, 1).unwrap(); + std::fs::write(&file, bytes.as_ref()).unwrap(); + let id = session.open(file.to_string_lossy().into_owned(), Some(file.to_string_lossy().into_owned()), bytes.clone(), None).unwrap(); + std::fs::write(dir.join("taken.pdf"), b"other").unwrap(); + + assert_eq!(session.rename_file(id, "taken"), Err(RenameError::Exists("taken.pdf".into()))); + assert_eq!(session.rename_file(id, "first"), Ok(file.to_string_lossy().into_owned()), "the same name changes nothing"); + + let renamed = session.rename_file(id, "second").unwrap(); + assert!(!file.exists() && Path::new(&renamed).exists()); + let doc = session.get(id).unwrap(); + assert_eq!(doc.name, "second.pdf"); + assert_eq!(doc.path.as_deref(), Some(renamed.as_str())); + + // A case-only rename is the same file where the file system ignores case. + let cased = session.rename_file(id, "Second").unwrap(); + assert!(Path::new(&cased).exists()); + assert_eq!(session.get(id).unwrap().name, "Second.pdf"); + + // A read-only file in a writable folder renames, as it does in the file manager. + let mut perms = std::fs::metadata(&cased).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&cased, perms.clone()).unwrap(); + let third = session.rename_file(id, "third"); + let moved = third.clone().unwrap_or_else(|_| cased.clone()); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&moved, perms).unwrap(); + assert!(third.is_ok(), "{third:?}"); + session.rename_file(id, "second").unwrap(); + + session.doc_mut(id).unwrap().dirty = true; + assert_eq!(session.rename_file(id, "third"), Err(RenameError::Unsaved)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_file_that_appears_under_the_new_name_is_never_replaced() { + let dir = std::env::temp_dir().join(format!("pdfcraft-rename-race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (old, new) = (dir.join("old.pdf"), dir.join("new.pdf")); + std::fs::write(&old, b"mine").unwrap(); + // Created after rename_target's check, before the move. + std::fs::write(&new, b"theirs").unwrap(); + let err = move_no_replace(&old, &new).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&new).unwrap(), b"theirs", "the other file is untouched"); + assert_eq!(std::fs::read(&old).unwrap(), b"mine", "and nothing was moved"); + std::fs::remove_file(&new).unwrap(); + move_no_replace(&old, &new).unwrap(); + assert!(!old.exists(), "the old name is gone"); + assert_eq!(std::fs::read(&new).unwrap(), b"mine"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "one name is left"); + // The same file under another letter case is renamed, not refused. + move_no_replace(&new, &dir.join("NEW.pdf")).unwrap(); + assert_eq!(std::fs::read(dir.join("NEW.pdf")).unwrap(), b"mine"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn more_device_names_and_a_path_too_long_are_refused() { + for device in ["COM0", "lpt0", "COM\u{b9}", "com\u{b2}.txt", "LPT\u{b3}"] { + assert!(matches!(name(device), Err(RenameError::Invalid(_))), "{device:?}"); + } + assert!(name("COM10").is_ok()); + if let Some(limit) = MAX_PATH_LEN { + let folder = Path::new(if cfg!(windows) { "C:\\docs" } else { "/docs" }); + let mut dir = folder.to_path_buf(); + while path_len(&dir) < limit - 60 { + dir.push("d".repeat(50)); + } + let current = dir.join("report.pdf"); + assert!(new_file_name(¤t, "short").is_ok()); + let long = "x".repeat(limit - path_len(&dir) - ".pdf".len()); + assert!(matches!(new_file_name(¤t, &long), Err(RenameError::Invalid(_))), "one past the limit"); + assert!(new_file_name(¤t, &long[1..]).is_ok(), "exactly at the limit"); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn a_folder_swapped_for_a_link_out_of_the_root_is_refused_on_linux() { + let base = std::env::temp_dir().join(format!("pdfcraft-rename-root-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (root, outside) = (base.join("root"), base.join("outside")); + std::fs::create_dir_all(root.join("sub")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let (inside_file, outside_file) = (root.join("sub/a.pdf"), outside.join("a.pdf")); + std::fs::write(&inside_file, b"in").unwrap(); + std::fs::write(&outside_file, b"out").unwrap(); + let root = root.canonicalize().unwrap(); + // Plain move below the root works. + rooted::move_no_replace(&root, &root.join("sub/a.pdf"), &root.join("sub/b.pdf")).unwrap(); + assert!(root.join("sub/b.pdf").exists() && !inside_file.exists()); + // A taken name is refused, nothing replaced. + std::fs::write(root.join("sub/c.pdf"), b"c").unwrap(); + let err = rooted::move_no_replace(&root, &root.join("sub/b.pdf"), &root.join("sub/c.pdf")).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists); + // `sub` is swapped for a link to a folder outside the root after the caller's check. + std::fs::remove_dir_all(root.join("sub")).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap(); + let err = rooted::move_no_replace(&root, &root.join("sub/a.pdf"), &root.join("sub/z.pdf")).unwrap_err(); + assert!(err.to_string().contains("allowed folder"), "{err}"); + assert!(outside_file.exists() && !outside.join("z.pdf").exists(), "nothing moved outside"); + // A file outside the root is refused too. + assert!(rooted::move_no_replace(&root, &outside_file, &outside.join("y.pdf")).is_err()); + let _ = std::fs::remove_dir_all(&base); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index a94c5914d2..e81eef6445 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,4 +13,5 @@ mod office_export_images; mod page_templates; mod private_image_resize; mod private_text_glyphs; +mod rename_name_length; mod xfa_repeat; diff --git a/crates/engine/tests/it/rename_name_length.rs b/crates/engine/tests/it/rename_name_length.rs new file mode 100644 index 0000000000..0e8c30e727 --- /dev/null +++ b/crates/engine/tests/it/rename_name_length.rs @@ -0,0 +1,32 @@ +//! A file name is limited in bytes (UTF-8 on ext4 and APFS) and UTF-16 units (NTFS), not in +//! characters, so a long name of wide characters has to be refused before the rename fails. + +use std::path::Path; + +use pdfcraft_engine::{RenameError, new_file_name}; + +fn name(typed: &str) -> Result { + new_file_name(Path::new("/docs/report.pdf"), typed) +} + +#[test] +fn a_name_over_255_bytes_is_refused() { + // 94 characters of 3 bytes each: 282 bytes, then ".pdf" makes 286. Under 255 characters. + let cjk = "年".repeat(94); + assert!(cjk.chars().count() < 255); + assert!(matches!(name(&cjk), Err(RenameError::Invalid(_))), "282 bytes of CJK must be refused"); + + // 251 ASCII characters + ".pdf" is exactly 255 bytes: accepted. + let exact = "x".repeat(251); + assert_eq!(name(&exact), Ok(format!("{exact}.pdf"))); + + // One more byte is refused. + assert!(matches!(name(&"x".repeat(252)), Err(RenameError::Invalid(_)))); + + // 80 CJK characters + ".pdf" is 244 bytes: accepted. + let short = "年".repeat(80); + assert_eq!(name(&short), Ok(format!("{short}.pdf"))); + + // Characters outside the BMP take 2 UTF-16 units and 4 bytes: 63 + ".pdf" is 256 bytes. + assert!(matches!(name(&"😀".repeat(63)), Err(RenameError::Invalid(_)))); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8c31013b79..d74ed942fb 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -72,6 +72,8 @@ impl PdfCraftApp { status_captions_lang: None, views: Vec::new(), closed_tabs: Vec::new(), + rename_draft: None, + rename_returned: rename_ui::Returned::default(), active: None, mode: Mode::AllTools, default_mode: Mode::AllTools, @@ -807,6 +809,7 @@ impl PdfCraftApp { self.process_file_requests(); #[cfg(not(target_arch = "wasm32"))] self.process_picked(); + self.reopen_returned_rename(); self.settle_presign(); // Last, after everything that can open or answer the "save changes?" question. self.attend_save_prompt(ctx); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 4c632d39e7..689c847807 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -214,6 +214,10 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { response.scroll_to_me(Some(Align::Center)); } response.context_menu(|ui| tab_menu(app, ui, i, &mut action)); + // Double-clicking the tab's name renames its file, as in Finder and File Explorer. + if response.double_clicked() && cfg!(not(target_arch = "wasm32")) && doc.path.is_some() { + action = Some(crate::tab_context::Action::Rename(app.views[i].id)); + } if response.clicked() { app.active = Some(i); } @@ -404,6 +408,10 @@ fn tab_menu(app: &PdfCraftApp, ui: &mut egui::Ui, index: usize, action: &mut Opt *action = Some(Action::Reveal(id)); ui.close(); } + if ui.add_enabled(reveal, egui::Button::new(tl!("Rename…"))).clicked() { + *action = Some(Action::Rename(id)); + ui.close(); + } } /// A tab of `place`'s strip (its tabs `slots`) being dragged (`dragged`: its index, and whether it diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0d98079bc2..53aa66a47d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -20,6 +20,7 @@ pub(super) mod preferences; pub(super) mod printer_marks_ui; mod prompts; pub(super) mod protect; +pub(super) mod rename_ui; pub(super) mod standards_ui; pub(super) mod word_count_ui; @@ -69,6 +70,7 @@ struct Pending { import_words: bool, print_go: bool, revert_now: bool, + rename_now: bool, overwrite_now: bool, overwrite_elsewhere: bool, lock_answer: Option, @@ -306,6 +308,12 @@ fn dialog_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, dialog: Dialog, req: &m return false; } } + Dialog::RenameFile => { + let (shut, go) = crate::rename_ui::body(app, ui); + req.close |= shut; + req.rename_now = go; + return false; + } Dialog::LockSignatures => { if !dialog_lock_signatures(ui, app, req) { return false; @@ -2231,6 +2239,12 @@ fn finish_close(app: &mut PdfCraftApp, dialog: Dialog, modal_closed: bool, req: if req.alt_now { app.save_alt_text(); } + // After the dialog has gone: Save and Rename may ask about a file changed on disk. + if req.rename_now { + app.rename_with_draft(); + } else if app.dialog.is_none() { + app.rename_draft = None; + } if req.stamp_now { app.save_custom_stamp(); } diff --git a/crates/ui-egui/src/dialogs/rename_ui.rs b/crates/ui-egui/src/dialogs/rename_ui.rs new file mode 100644 index 0000000000..bea98e0d0c --- /dev/null +++ b/crates/ui-egui/src/dialogs/rename_ui.rs @@ -0,0 +1,298 @@ +//! Rename… on a document tab (#2102, #2867): rename the file on disk, in its own folder, without +//! closing it. The tab, the undo history and the view stay as they are; Recent files, Reopen Closed +//! Tab and the file watcher follow the new name. A document with unsaved changes is saved first +//! ("Save and Rename"), so the renamed file is always the version on screen (Acrobat on macOS asks +//! the same). The name's rules are the engine's ([`pdfcraft_engine::new_file_name`]). + +use egui::{Align, Layout}; +use pdfcraft_engine::DocId; + +use crate::{Dialog, PdfCraftApp, theme, widgets}; + +/// The Rename dialog's state: the document and the name being typed. +pub(crate) struct RenameDraft { + pub id: DocId, + pub name: String, + /// Select the name and focus the field on the dialog's first frame. + pub fresh: bool, +} + +/// Where a "Save and Rename" hands the typed name back when its save does not go through. +pub(crate) type Returned = std::sync::Arc>>; + +/// Held by the step that follows the save. If that step is dropped without running (the save +/// failed, the Save As picker was cancelled, the overwrite question was declined), the name goes +/// back to the app so the dialog can open again with it. +struct Pending { + draft: Option, + back: Returned, +} + +impl Pending { + /// The save went through: the rename takes the name. + fn take(&mut self) -> Option { + self.draft.take() + } +} + +impl Drop for Pending { + fn drop(&mut self) { + if let Some(mut draft) = self.draft.take() { + draft.fresh = false; + *self.back.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(draft); + } + } +} + +impl PdfCraftApp { + /// Opens Rename again with the name that was typed, once a save that was to precede the + /// rename has come to nothing. Called every frame. + pub(crate) fn reopen_returned_rename(&mut self) { + if self.dialog.is_some() { + return; + } + let Some(draft) = self.rename_returned.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { return }; + if self.views.iter().any(|v| v.id == draft.id) { + self.rename_draft = Some(draft); + self.dialog = Some(Dialog::RenameFile); + } + } + + /// Rename… for document `id` (tab menu, double-click on the tab): the dialog opens with the + /// name selected, without its extension. Nothing happens for a document that has no file. + pub(crate) fn start_rename(&mut self, id: DocId) { + let Some(path) = self.session.get(id).and_then(|d| d.path.clone()) else { return }; + let name = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + self.rename_draft = Some(RenameDraft { id, name, fresh: true }); + self.dialog = Some(Dialog::RenameFile); + } + + /// The dialog's Rename (or Save and Rename). + pub(crate) fn rename_with_draft(&mut self) { + let Some(draft) = self.rename_draft.take() else { return }; + let Some(index) = self.views.iter().position(|v| v.id == draft.id) else { return }; + if self.has_unsaved_work(index) { + // Saved in place first; the rename follows only if the save went through. + let mut pending = Pending { draft: Some(draft), back: self.rename_returned.clone() }; + self.save_then(index, crate::editing::SaveTarget::InPlace, move |app| { + if let Some(draft) = pending.take() { + app.rename_now(draft.id, &draft.name); + } + }); + } else { + self.rename_now(draft.id, &draft.name); + } + } + + fn rename_now(&mut self, id: DocId, typed: &str) { + let Some(old) = self.session.get(id).and_then(|d| d.path.clone()) else { return }; + match self.session.rename_file(id, typed) { + Ok(new) if new != old => { + let name = self.session.get(id).map(|d| d.name.clone()).unwrap_or_default(); + for recent in self.recent.iter_mut().filter(|r| r.path == old) { + recent.path = new.clone(); + recent.name = name.clone(); + } + for closed in self.closed_tabs.iter_mut().filter(|p| **p == old) { + *closed = new.clone(); + } + // The renamed file is the version the document came from: not a change on disk. + #[cfg(not(target_arch = "wasm32"))] + self.watch.known_now(id, &new); + self.notify_fmt("Renamed to {name}", &[("name", &name)]); + } + Ok(_) => {} + Err(e) => { + let name = self.session.get(id).map(|d| d.name.clone()).unwrap_or_default(); + self.notify_fmt("Couldn't rename {name}: {e}", &[("name", &name), ("e", &e.to_string())]); + } + } + } +} + +/// The Rename dialog. Returns `(close, rename)`. +pub(crate) fn body(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> (bool, bool) { + let (mut close, mut go) = (false, false); + let Some(doc_id) = app.rename_draft.as_ref().map(|d| d.id) else { return (true, false) }; + let Some((path, current)) = app.session.get(doc_id).and_then(|d| d.path.clone().map(|p| (p, d.name.clone()))) else { return (true, false) }; + let unsaved = app.views.iter().position(|v| v.id == doc_id).is_some_and(|i| app.has_unsaved_work(i)); + let Some(draft) = app.rename_draft.as_mut() else { return (true, false) }; + let heading = ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Rename “{name}”"), &[("name", ¤t)])).font(theme::semibold(18.0))); + ui.add_space(8.0); + let id = ui.make_persistent_id("rename-file-name"); + if draft.fresh { + let mut state = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default(); + let end = egui::text::CCursor::new(draft.name.chars().count()); + state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), end))); + state.store(ui.ctx(), id); + } + let field = + ui.add(egui::TextEdit::singleline(&mut draft.name).id(id).desired_width(f32::INFINITY).hint_text(tl!("File name"))).labelled_by(heading.id); + if std::mem::take(&mut draft.fresh) { + field.request_focus(); + } + // Checked as it is typed: the reason shows under the field and Rename waits for a usable name. + let check = pdfcraft_engine::rename_target(std::path::Path::new(&path), &draft.name); + let t = theme::Tokens::get(ui.ctx()); + match &check { + Err(e) => { + ui.add_space(4.0); + ui.label(egui::RichText::new(e.to_string()).color(ui.visuals().error_fg_color).font(theme::regular(12.0))); + } + Ok(Some(target)) => { + ui.add_space(4.0); + let new = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + ui.label(egui::RichText::new(new).color(t.text_muted).font(theme::regular(12.0))); + } + Ok(None) => {} + } + if unsaved { + ui.add_space(8.0); + ui.label(tl!("This document has unsaved changes. They are saved first, then the file is renamed.")); + } + let ready = matches!(check, Ok(Some(_))); + if ready && field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + go = true; + close = true; + } + ui.add_space(12.0); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let label = if unsaved { tl!("Save and Rename") } else { tl!("Rename") }; + if ui.add_enabled_ui(ready, |ui| widgets::pill_button(ui, label, true)).inner.clicked() { + go = true; + close = true; + } + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { + close = true; + } + }); + (close, go) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use crate::PdfCraftApp; + use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, + }; + + fn harness(dir: &std::path::Path) -> Harness<'static, PdfCraftApp> { + let file = dir.join("first.pdf"); + std::fs::write(&file, include_bytes!("../../tests/data/form.pdf")).unwrap(); + let path = file.to_string_lossy().into_owned(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("first.pdf", Some(path), include_bytes!("../../tests/data/form.pdf").to_vec()).unwrap(); + app + }); + h.run_steps(8); + h + } + + fn open_rename(h: &mut Harness<'static, PdfCraftApp>, tab: &str) { + h.get_by_role_and_label(egui::accesskit::Role::Tab, tab).click_secondary(); + h.run_steps(2); + h.get_by_label("Rename…").click(); + h.run_steps(6); + } + + fn type_name(h: &mut Harness<'static, PdfCraftApp>, name: &str) { + h.state_mut().rename_draft.as_mut().unwrap().name = name.to_string(); + h.run_steps(3); + } + + #[test] + fn rename_from_the_tab_menu_moves_the_file_and_keeps_the_tab() { + let dir = std::env::temp_dir().join(format!("pdfcraft-rename-ui-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("taken.pdf"), b"other").unwrap(); + let mut h = harness(&dir); + let id = h.state().views[0].id; + open_rename(&mut h, "first.pdf"); + assert_eq!(h.state().rename_draft.as_ref().unwrap().name, "first", "the name opens without its extension"); + // Refusals show under the field and keep Rename disabled. + type_name(&mut h, "taken"); + h.get_by_label_contains("already exists"); + assert!(h.get_by_label("Rename").accesskit_node().is_disabled()); + type_name(&mut h, "CON"); + h.get_by_label_contains("reserves"); + type_name(&mut h, "Budget 2026"); + h.get_by_label("Budget 2026.pdf"); + h.get_by_label("Rename").click(); + h.run_steps(4); + assert!(dir.join("Budget 2026.pdf").exists() && !dir.join("first.pdf").exists()); + assert_eq!(h.state().views.len(), 1, "the tab stays"); + assert_eq!(h.state().views[0].id, id); + let doc = h.state().session.get(id).unwrap(); + assert_eq!(doc.name, "Budget 2026.pdf"); + assert!(h.state().recent.iter().any(|r| r.name == "Budget 2026.pdf" && r.path.ends_with("Budget 2026.pdf"))); + assert!(!h.state().recent.iter().any(|r| r.path.ends_with("first.pdf")), "Recent files follow the rename"); + h.get_by_role_and_label(egui::accesskit::Role::Tab, "Budget 2026.pdf"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn unsaved_changes_are_saved_before_the_rename() { + let dir = std::env::temp_dir().join(format!("pdfcraft-rename-ui-save-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut h = harness(&dir); + let id = h.state().views[0].id; + h.state_mut().apply_edit(pdfcraft_engine::Edit::SetInfo { key: "Title".into(), value: "Saved first".into() }); + h.run_steps(3); + assert!(h.state().session.get(id).unwrap().dirty); + open_rename(&mut h, "first.pdf (edited)"); // an edited tab says so to assistive technology + type_name(&mut h, "second"); + h.get_by_label("This document has unsaved changes. They are saved first, then the file is renamed."); + h.get_by_label("Save and Rename").click(); + h.run_steps(6); + assert!(h.state().rename_draft.is_none() && h.state().dialog.is_none()); + let doc = h.state().session.get(id).unwrap(); + assert!(!doc.dirty, "saved"); + assert_eq!(doc.name, "second.pdf"); + let saved = std::fs::read(dir.join("second.pdf")).unwrap(); + assert!(String::from_utf8_lossy(&saved).contains("Saved first"), "the renamed file is the saved version"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_save_that_fails_keeps_the_typed_name() { + let dir = std::env::temp_dir().join(format!("pdfcraft-rename-ui-fail-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut h = harness(&dir); + let id = h.state().views[0].id; + h.state_mut().apply_edit(pdfcraft_engine::Edit::SetInfo { key: "Title".into(), value: "Unsaved".into() }); + h.run_steps(3); + open_rename(&mut h, "first.pdf (edited)"); + type_name(&mut h, "second"); + // The save cannot be written: the file's place is now a folder. + std::fs::remove_file(dir.join("first.pdf")).unwrap(); + std::fs::create_dir(dir.join("first.pdf")).unwrap(); + h.get_by_label("Save and Rename").click(); + h.run_steps(6); + assert!(matches!(h.state().dialog, Some(crate::Dialog::RenameFile)), "the dialog is back"); + assert_eq!(h.state().rename_draft.as_ref().unwrap().name, "second", "with the name that was typed"); + assert!(h.state().session.get(id).unwrap().dirty, "nothing was saved"); + assert!(dir.join("first.pdf").is_dir() && !dir.join("second.pdf").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_document_without_a_file_offers_no_rename() { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("unsaved.pdf", None, include_bytes!("../../tests/data/form.pdf").to_vec()).unwrap(); + app + }); + h.run_steps(8); + h.get_by_role_and_label(egui::accesskit::Role::Tab, "unsaved.pdf").click_secondary(); + h.run_steps(2); + assert!(h.get_by_label("Rename…").accesskit_node().is_disabled()); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6a6062093e..3ab85e0c4f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -128,6 +128,7 @@ use dialogs::pageboxes; use dialogs::palette; use dialogs::printer_marks_ui; use dialogs::protect; +use dialogs::rename_ui; use dialogs::standards_ui; use dialogs::word_count_ui; pub use home::folders_ui; @@ -315,6 +316,11 @@ pub struct PdfCraftApp { pub(crate) status_captions_lang: Option, pub views: Vec, pub(crate) closed_tabs: Vec, + /// The Rename dialog's name being typed. + pub(crate) rename_draft: Option, + /// A name typed in Rename whose "Save and Rename" save did not go through; the dialog opens + /// again with it on the next frame. + pub(crate) rename_returned: rename_ui::Returned, /// `None` shows the Home tab. pub active: Option, pub mode: Mode, diff --git a/crates/ui-egui/src/menus/tab_context.rs b/crates/ui-egui/src/menus/tab_context.rs index 3d42f9a95d..7fcdf1e24d 100644 --- a/crates/ui-egui/src/menus/tab_context.rs +++ b/crates/ui-egui/src/menus/tab_context.rs @@ -7,6 +7,7 @@ pub(crate) enum Action { Close(u64), Reopen, Reveal(DocId), + Rename(DocId), /// Split right (or down) with a tab, by its view key. Split { tab: u64, @@ -86,6 +87,7 @@ impl crate::PdfCraftApp { #[cfg(target_arch = "wasm32")] let _ = id; } + Action::Rename(id) => self.start_rename(id), } } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8d524ad85b..fa9a79c7ee 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -199,6 +199,8 @@ pub enum Dialog { AuditSpace, /// Signatures ▸ Show certificate. CertificateViewer, + /// Rename… on a document tab. + RenameFile, /// Pin tools to Home: selection modal. PinTool, } diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 18963f935b..938ef650bd 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -25,6 +25,17 @@ tools = ["text_word_count"] evidence = ["crates/engine/src/word_count.rs::word_count_filters_are_independent_and_do_not_change_normal_extraction", "crates/automation/tests/it/automation.rs::word_count_reads_selected_pages_and_unsaved_edits_without_mutating", "crates/ui-egui/src/dialogs/word_count_ui.rs::word_count_dialog_counts_changes_pages_and_closes"] notes = "Unicode words and characters for the current snapshot; all or current page in GUI, selected pages headlessly. Desktop background work with cancellation. Optional semantic table/code/Figure and invisible-text exclusions; no OCR or visual layout classification. Unsupported structure remains counted and is reported. Mixed ActualText exclusions fail explicitly. See docs/word-count.md." +[[feature]] +id = "core.rename-file" +title = "Rename the file from its tab" +area = "A" +tier = "P2" +milestone = "M2" +status = "shipped" +tools = ["doc_rename"] +evidence = ["crates/engine/src/rename.rs::names_windows_or_other_systems_refuse_are_refused", "crates/engine/src/rename.rs::renaming_moves_the_file_and_refuses_what_it_must", "crates/automation/src/tests.rs::doc_rename_moves_the_file_and_refuses_with_reasons", "crates/ui-egui/src/dialogs/rename_ui.rs::rename_from_the_tab_menu_moves_the_file_and_keeps_the_tab", "crates/ui-egui/src/dialogs/rename_ui.rs::unsaved_changes_are_saved_before_the_rename"] +notes = "Tab context menu Rename… (or a double-click on the tab) renames the open document's file in its own folder; the tab, undo history and view stay, and Recent files, Reopen Closed Tab and the file watcher follow the new name (#2102, #2867). The name is checked as it is typed, with the same rules on every system so a synced folder stays usable: no separators or < > : \" | ? *, no control characters, no Windows device names, no trailing dot, at most 255 characters and a full path within the system limit; the extension is kept. Refused with the reason when the name is taken (a file that appears under it meanwhile is never replaced), the file is in use, or the document was never saved; unsaved changes are saved first (Save and Rename)." + [[feature]] id = "core.open-pdf" title = "Open PDF files"