From d64a597d5165d3e8db134573ac1a3f154e70f143 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran <338149330+regendorf-ux@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:18:10 -0400 Subject: [PATCH 01/11] =?UTF-8?q?feat(tabs):=20rename=20the=20file=20from?= =?UTF-8?q?=20its=20tab=20(Rename=E2=80=A6=20/=20double-click)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tab context menu gets Rename…, and a double-click on a document tab does the same: a small dialog opens with the name selected (without its extension) and renames the file on disk in its own folder. The document stays open in its tab with its undo history and view; Recent files, Reopen Closed Tab and the file watcher follow the new name (#2102, #2867). - Engine: pdfcraft_engine::new_file_name / rename_target (the checks) and Session::rename_file (the move). The rules are the same on every system, so a synced folder keeps working: no path separators or < > : " | ? *, no control characters, no Windows device names (CON, NUL, COM1…), no trailing dot, at most 255 characters; the extension is kept and added back when left out; a case-only rename is allowed. Refused with the reason when the name is taken, the file is read-only or in use, the document was never saved, or it has unsaved changes. - Window: the name is checked as it is typed (the reason shows under the field; Rename waits for a usable name). A document with unsaved changes gets Save and Rename: it is saved in place first, and renamed only if the save went through. - Automation: doc_rename {doc, name}, held to the write root for both names. - 6 labels in all 22 catalogs (Rename and File name already had rows); parity core.rename-file. Tests: engine rename::tests (names, refusals, the move incl. read-only and unsaved), automation doc_rename_moves_the_file_and_refuses_with_reasons, window rename_ui::tests (menu, live refusals, Save and Rename, no Rename for a document without a file). Co-Authored-By: Claude Opus 5.5 --- ATTRIBUTION.toml | 44 +++--- crates/automation/src/lib.rs | 51 +++++++ crates/automation/src/tools.rs | 7 + crates/engine/src/lib.rs | 2 + crates/engine/src/rename.rs | 213 ++++++++++++++++++++++++++ crates/ui-egui/src/chrome.rs | 8 + crates/ui-egui/src/dialogs.rs | 13 ++ crates/ui-egui/src/i18n/ar.tsv | 7 + crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/kk.tsv | 7 + crates/ui-egui/src/i18n/lt.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sl.tsv | 7 + crates/ui-egui/src/i18n/te.tsv | 7 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/lib.rs | 6 + crates/ui-egui/src/rename_ui.rs | 229 ++++++++++++++++++++++++++++ crates/ui-egui/src/tab_context.rs | 2 + parity/acrobat-features.toml | 11 ++ 33 files changed, 718 insertions(+), 22 deletions(-) create mode 100644 crates/engine/src/rename.rs create mode 100644 crates/ui-egui/src/rename_ui.rs diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index be9e2c448e..4089df6277 100644 --- a/ATTRIBUTION.toml +++ b/ATTRIBUTION.toml @@ -7,7 +7,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "cefa955aa92790d6773cb1d1e15e19019b3165a00528d57d6617362e1d1988ab" +sha256 = "d40df72f84f99201a1ffc6a44153bd33ad9ab61bf4c99c44d6dd1833f7d9b79d" # ATTRIBUTION.toml: one entry per asset (AGENTS.md §1). The source of truth for provenance and licences. # ATTRIBUTION.md is generated from this file: `cargo xtask assets --write`. Checked by `cargo xtask assets` (part of `xtask ci`). @@ -30,7 +30,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "dbfebf4e9b2e9ac31ecf72202c2098173e72ebfaf90e9fee8f0563a6734fe31f" +sha256 = "7ac9aa854970d2e7915e9b10671151dba52c427f39d19cf831bfd45d37674f31" [[asset]] path = "crates/ui-egui/src/i18n/zh-hant.tsv" @@ -41,7 +41,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "0b0dafa3806a6b3508684f64e1f07b435113f8efd0e59201d12250c63c1d9547" +sha256 = "5ff89153eed9e6400fc9d7a6df9b1b254014413b7508d1ed8ae12f2d8d10fdf5" [[asset]] path = "crates/ui-egui/src/i18n/cs.tsv" @@ -52,7 +52,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "898a5240fa59cac42ef6b99cb60bcfca0094ac27370e1c8d020bd27936b56517" +sha256 = "2c4d6949a8c20bb810029e9bf50894ff7b186a659048f7f6b0136edca3811716" [[asset]] path = "crates/ui-egui/src/i18n/pt-br.tsv" @@ -63,7 +63,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "b4745c94797575529cd0e78c18c71fa2c0dfddfbf19b9c40b41dc2057c6f6543" +sha256 = "c4bfd236e8bd534f92b2aa7d43547deb9b829aa8edc82c6c9b34dd29b988e6e2" [[asset]] path = "crates/ui-egui/src/i18n/es.tsv" @@ -74,7 +74,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "2acb3f6522d6d1f744343f474fe4c51ebec610a888a7fa83fc9422228e6fa3c1" +sha256 = "60b75278f1165a83789c1740bad7ba7286c9700c17f25556fda9829fd3eb1911" [[asset]] path = "crates/ui-egui/src/i18n/fr.tsv" @@ -85,7 +85,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "1b739478a4f186a49900cce84edbe136206a53b46340322df4caf77bb3fb5b12" +sha256 = "9168e7c7aa96f7685a68f3f5f33d33de2174d559df0f017dc3e82de7cf836691" [[asset]] path = "crates/ui-egui/src/i18n/de.tsv" @@ -96,7 +96,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "da3b71608ff7fe6e230b076207cee96ac01f66e068ca1be83af1ad56ac9c60eb" +sha256 = "afb4da8508534e4d54d08a07b1587e2e34c5f819d014d6db008a547d0a8dea4e" [[asset]] path = "crates/ui-egui/src/i18n/te.tsv" @@ -107,7 +107,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "989d2e5f57cf22c21a85951835ca9fbd05e314da67eb4c17332df1f03679fa00" +sha256 = "19f4f070f4367d9043fe8df05e545ad23b312c552ec08e6fc820af269146af4e" [[asset]] path = "crates/ui-egui/src/i18n/it.tsv" @@ -118,7 +118,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "5e84916e3ad8670216360695689fe8fd624365a29886f66a3c655ba126892f5b" +sha256 = "04a38fab1e0635723993392e85c4c569dbfc41b4e0cd754633387f8f10d50d59" [[asset]] path = "crates/ui-egui/src/i18n/pl.tsv" @@ -129,7 +129,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "988bcf2e0322a46c0464ff7b91ab5d90193b0ea7f454812d12595eb843de6fc7" +sha256 = "ca2ba6a173333f5a5fcfb3d6c94f2c6e957745c25206155ef380bdc02e5319db" [[asset]] path = "crates/ui-egui/src/i18n/ru.tsv" @@ -140,7 +140,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "084f4ea06f31c632ad90b0e87f66240ce5b5dc012ac7770987d44918ee66f452" +sha256 = "c37464b3f48625af91d675ce54a567fa59abdad69daa3b39b9138f83cd63fdf8" [[asset]] path = "crates/ui-egui/src/i18n/hu.tsv" @@ -151,7 +151,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "973cd90ec34c8a973d146a0e2c73c1d632e17357c3d87ccf10c59e64d12c1587" +sha256 = "123816b8389029848d1023c8fead568bf5dd7c1b96908829ad790d49164b7e10" [[asset]] path = "crates/ui-egui/src/i18n/bg.tsv" @@ -162,7 +162,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "485f85d4053c9661ddda2ed9394a0644c77b489feb598d02f12ef209e11f2ee3" +sha256 = "8fe9d210c51f85658119aa67d485d8c29ac3ca50230a1668d498e22eee095f92" [[asset]] path = "crates/ui-egui/src/i18n/kk.tsv" @@ -173,7 +173,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "24524864022ab2abeff68b5979519eee4e92134d0c4053d40c741bc7f01c249c" +sha256 = "dd468e7f86082bbc7e8ea2cd294bb102d0f4b677a0c8995ecc705eadcb9f7772" [[asset]] path = "crates/ui-egui/src/i18n/ja.tsv" @@ -184,7 +184,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "bc6d123bdb34d5d7c22717fed1a86ff20e7e493acc1e155e61e61e2dc74459aa" +sha256 = "29807508dd9973269dfb61da4422ee8845d1af246d8bdc6a06f35ba37cd52c58" [[asset]] path = "crates/ui-egui/src/i18n/uk.tsv" @@ -195,7 +195,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "82678dbe730f56062037ea78de165b2c016b3fa670fb1cbfc7cd713eca900bac" +sha256 = "6757013ebe79cac8379ba354fe8427cb60137017a5ec1a050eb8424817c9f2e0" [[asset]] path = "crates/ui-egui/src/i18n/ar.tsv" @@ -206,7 +206,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "304d661b27cdb5246f6b2974b4b5e78667f0928cda3588440be3d8f35f254679" +sha256 = "8acf4a5ec5164d6dcb63abad4f4a9cfa2395e9e0305ace354348aa1ff2b162fa" [[asset]] path = "crates/ui-egui/src/i18n/tr.tsv" @@ -217,7 +217,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "05e2b7d5401166d362ba055120fba9a1645d6ec324997cf670e19fafcb0c54cf" +sha256 = "2d6c28a19795bab80ba768e8518b8dd4739304c33e4755bd39f29297de0dfda3" [[asset]] path = "crates/ui-egui/src/i18n/lt.tsv" @@ -228,7 +228,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "17c8579e0e9d1524ffbeb87e7b30c14562dbaac64400826ee786cecfe31648fa" +sha256 = "a98ec67c96f99cf219da086a5a13a76c0bc4561b452c4c83028a40ac1a735d79" [[asset]] @@ -3352,7 +3352,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "2d1c4b4276d02512a4e20101be95a1671de5c4f5cdfd661887af5ebab0db06a6" +sha256 = "7d7d8b0e89e9e949264a1ac964500a289739242b74b3d2b24469356d05f0758b" [[asset]] path = "crates/ui-egui/src/i18n/sl.tsv" @@ -3363,7 +3363,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "8f8a259264cda06eb6d9a9bf91dc7d873a8561213a9a9e7acbd32623bef40be0" +sha256 = "476399afa847390602242be4864c8aa79e531b2adb2e6c1d29f933eb8a3ba055" [[asset]] diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 88856305b2..d201f55ef6 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -202,6 +202,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)? @@ -935,6 +936,28 @@ impl Automation { self.publish_save(id, &target, bytes, incremental, write) } + /// 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. + 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.check_roots(&own, &own_path, file_access::Access::Write)?; + if let Some(target) = pdfcraft_engine::rename_target(&own_path, name).map_err(failed)? { + let shown = target.to_string_lossy().into_owned(); + self.check_roots(&shown, &target, file_access::Access::Write)?; + if self.root.is_some() { + self.resolve_in_root(&shown, true)?; + } + } + let path = self.session.rename_file(id, name).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. fn publish_save( &mut self, @@ -3002,6 +3025,34 @@ mod tests { 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 5e89aef78a..14f44c455b 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -156,6 +156,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 read-only or 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 characters).", + ) + .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; 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. 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).") diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3432cd868e..a54acd7cbf 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod ocr; pub mod optimizer; pub mod print_raster; pub mod printcheck; +mod rename; mod scan_colours; mod scan_fields; pub mod signature_image; @@ -40,6 +41,7 @@ mod upright_image; pub mod word_count; pub mod xfa; +pub use rename::{RenameError, new_file_name, rename_target}; pub use signature_image::{ImageSignaturePreview, SignatureImage}; pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn}; pub use text_preview::TextEditPreview; diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs new file mode 100644 index 0000000000..717a48e301 --- /dev/null +++ b/crates/engine/src/rename.rs @@ -0,0 +1,213 @@ +//! 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`, `COM1`…), no name ending in a dot or a space, at most 255 +//! characters. 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 file is marked read-only. + ReadOnly, + /// 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::ReadOnly => write!(f, "the file is read-only"), + 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; 22] = [ + "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", + "LPT6", "LPT7", "LPT8", "LPT9", +]; +/// The longest file name the common file systems take. +const MAX_NAME_CHARS: 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.chars().count() > MAX_NAME_CHARS { + return Err(RenameError::Invalid(format!("a file name can be at most {MAX_NAME_CHARS} characters"))); + } + 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)) +} + +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 { + 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()); + }; + if std::fs::metadata(¤t).is_ok_and(|m| m.permissions().readonly()) { + return Err(RenameError::ReadOnly); + } + std::fs::rename(¤t, &target).map_err(|e| { + RenameError::Failed(match e.kind() { + std::io::ErrorKind::PermissionDenied => "it is open in another program, or you don't have permission".into(), + std::io::ErrorKind::NotFound => "it is no longer where it was opened from".into(), + _ => 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(_)))); + 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"); + + let mut perms = std::fs::metadata(&cased).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&cased, perms.clone()).unwrap(); + assert_eq!(session.rename_file(id, "third"), Err(RenameError::ReadOnly)); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&cased, perms).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); + } +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 84e62622fb..eec52b289f 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -167,7 +167,15 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) { action = Some(crate::tab_context::Action::Reveal(id)); ui.close(); } + if ui.add_enabled(reveal, egui::Button::new(tl!("Rename…"))).clicked() { + action = Some(crate::tab_context::Action::Rename(id)); + ui.close(); + } }); + // Double-clicking the tab's name renames its file, as in Finder and File Explorer. + if response.double_clicked() && reveal { + action = Some(crate::tab_context::Action::Rename(id)); + } if response.clicked() { app.active = Some(i); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2d2407629c..2a71ba7604 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -63,6 +63,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { let mut import_words = false; let mut print_go = false; let mut revert_now = false; + let mut rename_now = false; let mut overwrite_now = false; let mut overwrite_elsewhere = false; let mut summarize_now = false; @@ -784,6 +785,12 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { }); return; } + Dialog::RenameFile => { + let (shut, go) = crate::rename_ui::body(app, ui); + close |= shut; + rename_now = go; + return; + } Dialog::Revert => { let name = app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|d| d.name.clone()).unwrap_or_default(); ui.label(egui::RichText::new(tl!("Revert")).font(theme::semibold(18.0))); @@ -1397,6 +1404,12 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { if alt_now { app.save_alt_text(); } + // After the dialog has gone: Save and Rename may ask about a file changed on disk. + if rename_now { + app.rename_with_draft(); + } else if app.dialog.is_none() { + app.rename_draft = None; + } if stamp_now { app.save_custom_stamp(); } diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 5a0e6e9c96..8e2e42f977 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -2709,3 +2709,10 @@ certificate Version الإصدار Make properties default جعل الخصائص افتراضية Pages selected الصفحات المحددة Page properties خصائص الصفحة +# Rename… on a document tab (#2102). + Rename… إعادة التسمية… + Rename “{name}” إعادة تسمية «{name}» + This document has unsaved changes. They are saved first, then the file is renamed. يحتوي هذا المستند على تغييرات غير محفوظة. تُحفظ أولًا، ثم تُعاد تسمية الملف. + Save and Rename حفظ وإعادة التسمية + Renamed to {name} أُعيدت التسمية إلى {name} + Couldn't rename {name}: {e} تعذّرت إعادة تسمية {name}: {e} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 90791f4a86..3c40700d00 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2395,3 +2395,10 @@ animation effects Off Изключени Make properties default Задаване като свойства по подразбиране Pages selected Избрани страници Page properties Свойства на страницата +# Rename… on a document tab (#2102). + Rename… Преименуване… + Rename “{name}” Преименуване на „{name}“ + This document has unsaved changes. They are saved first, then the file is renamed. Този документ има незапазени промени. Първо се запазват, след това файлът се преименува. + Save and Rename Запазване и преименуване + Renamed to {name} Преименуван на {name} + Couldn't rename {name}: {e} {name} не може да бъде преименуван: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4bbb9a5e77..969bdcc202 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2506,3 +2506,10 @@ animation effects Off Vypnuto Make properties default Nastavit vlastnosti jako výchozí Pages selected Vybrané stránky Page properties Vlastnosti stránky +# Rename… on a document tab (#2102). + Rename… Přejmenovat… + Rename “{name}” Přejmenovat „{name}“ + This document has unsaved changes. They are saved first, then the file is renamed. Tento dokument má neuložené změny. Nejprve se uloží, potom se soubor přejmenuje. + Save and Rename Uložit a přejmenovat + Renamed to {name} Přejmenováno na {name} + Couldn't rename {name}: {e} {name} nelze přejmenovat: {e} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7965435257..6d94be3a41 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2433,3 +2433,10 @@ animation effects Off Aus Make properties default Eigenschaften als Standard festlegen Pages selected Ausgewählte Seiten Page properties Seiteneigenschaften +# Rename… on a document tab (#2102). + Rename… Umbenennen… + Rename “{name}” „{name}“ umbenennen + This document has unsaved changes. They are saved first, then the file is renamed. Dieses Dokument hat nicht gespeicherte Änderungen. Sie werden zuerst gespeichert, dann wird die Datei umbenannt. + Save and Rename Speichern und umbenennen + Renamed to {name} Umbenannt in {name} + Couldn't rename {name}: {e} {name} konnte nicht umbenannt werden: {e} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 57de6eef07..0929d4e705 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2438,3 +2438,10 @@ animation effects Off Ανενεργά Make properties default Ορισμός ιδιοτήτων ως προεπιλογή Pages selected Επιλεγμένες σελίδες Page properties Ιδιότητες σελίδας +# Rename… on a document tab (#2102). + Rename… Μετονομασία… + Rename “{name}” Μετονομασία «{name}» + This document has unsaved changes. They are saved first, then the file is renamed. Αυτό το έγγραφο έχει μη αποθηκευμένες αλλαγές. Αποθηκεύονται πρώτα και μετά μετονομάζεται το αρχείο. + Save and Rename Αποθήκευση και μετονομασία + Renamed to {name} Μετονομάστηκε σε {name} + Couldn't rename {name}: {e} Δεν ήταν δυνατή η μετονομασία του {name}: {e} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e4eb634468..3860f3598d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2572,3 +2572,10 @@ animation effects Off Desactivados # Historical snapshot notice bar (View signed version / View revision). You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original. Estás viendo la versión firmada de «{from}» (revisión {rev}). Es una instantánea: los cambios aquí no afectarán al original. You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original. Estás viendo la revisión {rev} de «{from}». Es una instantánea: los cambios aquí no afectarán al original. +# Rename… on a document tab (#2102). + Rename… Cambiar nombre… + Rename “{name}” Cambiar el nombre de «{name}» + This document has unsaved changes. They are saved first, then the file is renamed. Este documento tiene cambios sin guardar. Primero se guardan y después se cambia el nombre del archivo. + Save and Rename Guardar y cambiar nombre + Renamed to {name} Nombre cambiado a {name} + Couldn't rename {name}: {e} No se pudo cambiar el nombre de {name}: {e} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 62acea1da8..9e3f3de907 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2432,3 +2432,10 @@ animation effects Off Désactivés Make properties default Définir comme propriétés par défaut Pages selected Pages sélectionnées Page properties Propriétés de la page +# Rename… on a document tab (#2102). + Rename… Renommer… + Rename “{name}” Renommer « {name} » + This document has unsaved changes. They are saved first, then the file is renamed. Ce document contient des modifications non enregistrées. Elles sont d’abord enregistrées, puis le fichier est renommé. + Save and Rename Enregistrer et renommer + Renamed to {name} Renommé en {name} + Couldn't rename {name}: {e} Impossible de renommer {name} : {e} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2238e1ade5..219ca0cd00 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2431,3 +2431,10 @@ animation effects Off Ki Make properties default Tulajdonságok beállítása alapértelmezettként Pages selected Kijelölt oldalak Page properties Oldaltulajdonságok +# Rename… on a document tab (#2102). + Rename… Átnevezés… + Rename “{name}” „{name}” átnevezése + This document has unsaved changes. They are saved first, then the file is renamed. A dokumentumban nem mentett módosítások vannak. Először ezek mentése történik meg, majd a fájl átnevezése. + Save and Rename Mentés és átnevezés + Renamed to {name} Átnevezve erre: {name} + Couldn't rename {name}: {e} Nem sikerült átnevezni ezt: {name}: {e} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 3fa2263a0b..3a62cd64f0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2644,3 +2644,10 @@ certificate Key usage Utilizzo chiave certificate Self-signed Autofirmato certificate SHA-1 digest Impronta SHA-1 certificate SHA-256 digest Impronta SHA-256 +# Rename… on a document tab (#2102). + Rename… Rinomina… + Rename “{name}” Rinomina «{name}» + This document has unsaved changes. They are saved first, then the file is renamed. Questo documento ha modifiche non salvate. Vengono salvate prima, poi il file viene rinominato. + Save and Rename Salva e rinomina + Renamed to {name} Rinominato in {name} + Couldn't rename {name}: {e} Impossibile rinominare {name}: {e} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ee9439e311..730e83c3cb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2432,3 +2432,10 @@ animation effects Off オフ Make properties default プロパティをデフォルトに設定 Pages selected 選択したページ Page properties ページのプロパティ +# Rename… on a document tab (#2102). + Rename… 名前を変更… + Rename “{name}” 「{name}」の名前を変更 + This document has unsaved changes. They are saved first, then the file is renamed. この書類には保存されていない変更があります。先に保存してから、ファイル名を変更します。 + Save and Rename 保存して名前を変更 + Renamed to {name} {name} に名前を変更しました + Couldn't rename {name}: {e} {name} の名前を変更できませんでした: {e} diff --git a/crates/ui-egui/src/i18n/kk.tsv b/crates/ui-egui/src/i18n/kk.tsv index 827165ae3a..76237cedcf 100644 --- a/crates/ui-egui/src/i18n/kk.tsv +++ b/crates/ui-egui/src/i18n/kk.tsv @@ -2430,3 +2430,10 @@ animation effects Off Өшірулі Make properties default Қасиеттерді әдепкі ету Pages selected Таңдалған беттер Page properties Бет қасиеттері +# Rename… on a document tab (#2102). + Rename… Атын өзгерту… + Rename “{name}” «{name}» атын өзгерту + This document has unsaved changes. They are saved first, then the file is renamed. Бұл құжатта сақталмаған өзгерістер бар. Алдымен олар сақталады, содан кейін файлдың аты өзгертіледі. + Save and Rename Сақтау және атын өзгерту + Renamed to {name} Аты {name} болып өзгертілді + Couldn't rename {name}: {e} {name} атын өзгерту мүмкін болмады: {e} diff --git a/crates/ui-egui/src/i18n/lt.tsv b/crates/ui-egui/src/i18n/lt.tsv index 56a785cd3e..568200dff7 100644 --- a/crates/ui-egui/src/i18n/lt.tsv +++ b/crates/ui-egui/src/i18n/lt.tsv @@ -2683,3 +2683,10 @@ key Space Tarpas The password must have at least 6 characters. Slaptažodį turi sudaryti bent 6 simboliai. This file changed on disk. Reload it to see the new version; your unsaved changes will be lost. Šis failas diske pasikeitė. Įkelkite jį iš naujo, kad pamatytumėte naują versiją; neįrašyti pakeitimai bus prarasti. theme Appearance Išvaizda +# Rename… on a document tab (#2102). + Rename… Pervardyti… + Rename “{name}” Pervardyti „{name}“ + This document has unsaved changes. They are saved first, then the file is renamed. Šiame dokumente yra neįrašytų pakeitimų. Pirmiausia jie įrašomi, tada failas pervardijamas. + Save and Rename Įrašyti ir pervardyti + Renamed to {name} Pervardyta į {name} + Couldn't rename {name}: {e} Nepavyko pervardyti {name}: {e} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3dbb247056..1fd7a15c09 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2408,3 +2408,10 @@ animation effects Off Wyłączone Make properties default Ustaw właściwości jako domyślne Pages selected Zaznaczone strony Page properties Właściwości strony +# Rename… on a document tab (#2102). + Rename… Zmień nazwę… + Rename “{name}” Zmień nazwę „{name}” + This document has unsaved changes. They are saved first, then the file is renamed. Ten dokument ma niezapisane zmiany. Najpierw zostaną zapisane, a potem nazwa pliku zostanie zmieniona. + Save and Rename Zapisz i zmień nazwę + Renamed to {name} Zmieniono nazwę na {name} + Couldn't rename {name}: {e} Nie można zmienić nazwy {name}: {e} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8b3baa2d39..6cd8a80e9b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2446,3 +2446,10 @@ animation effects Off Desativados Make properties default Tornar propriedades padrão Pages selected Páginas selecionadas Page properties Propriedades da página +# Rename… on a document tab (#2102). + Rename… Renomear… + Rename “{name}” Renomear “{name}” + This document has unsaved changes. They are saved first, then the file is renamed. Este documento tem alterações não salvas. Elas são salvas primeiro e depois o arquivo é renomeado. + Save and Rename Salvar e renomear + Renamed to {name} Renomeado para {name} + Couldn't rename {name}: {e} Não foi possível renomear {name}: {e} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d0f8fc239c..352a53e7ca 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2345,3 +2345,10 @@ animation effects Off Выкл Make properties default Сделать свойства стандартными Pages selected Выделенные страницы Page properties Свойства страницы +# Rename… on a document tab (#2102). + Rename… Переименовать… + Rename “{name}” Переименовать «{name}» + This document has unsaved changes. They are saved first, then the file is renamed. В этом документе есть несохранённые изменения. Сначала они будут сохранены, затем файл будет переименован. + Save and Rename Сохранить и переименовать + Renamed to {name} Переименовано в {name} + Couldn't rename {name}: {e} Не удалось переименовать {name}: {e} diff --git a/crates/ui-egui/src/i18n/sl.tsv b/crates/ui-egui/src/i18n/sl.tsv index 92d9c9a6e3..5c91a1fbb0 100644 --- a/crates/ui-egui/src/i18n/sl.tsv +++ b/crates/ui-egui/src/i18n/sl.tsv @@ -2437,3 +2437,10 @@ animation effects Off Izklopljeni Make properties default Nastavi lastnosti kot privzete Pages selected Izbrane strani Page properties Lastnosti strani +# Rename… on a document tab (#2102). + Rename… Preimenuj… + Rename “{name}” Preimenuj »{name}« + This document has unsaved changes. They are saved first, then the file is renamed. Ta dokument ima neshranjene spremembe. Najprej se shranijo, nato se datoteka preimenuje. + Save and Rename Shrani in preimenuj + Renamed to {name} Preimenovano v {name} + Couldn't rename {name}: {e} Datoteke {name} ni bilo mogoče preimenovati: {e} diff --git a/crates/ui-egui/src/i18n/te.tsv b/crates/ui-egui/src/i18n/te.tsv index 07b716eac1..2a98e81254 100644 --- a/crates/ui-egui/src/i18n/te.tsv +++ b/crates/ui-egui/src/i18n/te.tsv @@ -2341,3 +2341,10 @@ animation effects Off ఆఫ్ Make properties default లక్షణాలను డిఫాల్ట్‌గా చేయి Pages selected ఎంచుకున్న పేజీలు Page properties పేజీ లక్షణాలు +# Rename… on a document tab (#2102). + Rename… పేరు మార్చు… + Rename “{name}” “{name}” పేరు మార్చు + This document has unsaved changes. They are saved first, then the file is renamed. ఈ పత్రంలో సేవ్ చేయని మార్పులు ఉన్నాయి. ముందుగా అవి సేవ్ చేయబడతాయి, ఆపై ఫైల్ పేరు మార్చబడుతుంది. + Save and Rename సేవ్ చేసి పేరు మార్చు + Renamed to {name} {name}గా పేరు మార్చబడింది + Couldn't rename {name}: {e} {name} పేరు మార్చలేకపోయాం: {e} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 30e19f2132..6083f2aac1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2428,3 +2428,10 @@ animation effects Off Kapalı Make properties default Özellikleri varsayılan yap Pages selected Seçilen sayfalar Page properties Sayfa özellikleri +# Rename… on a document tab (#2102). + Rename… Yeniden adlandır… + Rename “{name}” “{name}” öğesini yeniden adlandır + This document has unsaved changes. They are saved first, then the file is renamed. Bu belgede kaydedilmemiş değişiklikler var. Önce kaydedilir, ardından dosya yeniden adlandırılır. + Save and Rename Kaydet ve yeniden adlandır + Renamed to {name} {name} olarak yeniden adlandırıldı + Couldn't rename {name}: {e} {name} yeniden adlandırılamadı: {e} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c60799ef1f..6ee21bae88 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2454,3 +2454,10 @@ animation effects Off Вимкнено Make properties default Зробити властивості типовими Pages selected Вибрані сторінки Page properties Властивості сторінки +# Rename… on a document tab (#2102). + Rename… Перейменувати… + Rename “{name}” Перейменувати «{name}» + This document has unsaved changes. They are saved first, then the file is renamed. У цьому документі є незбережені зміни. Спершу їх буде збережено, потім файл буде перейменовано. + Save and Rename Зберегти й перейменувати + Renamed to {name} Перейменовано на {name} + Couldn't rename {name}: {e} Не вдалося перейменувати {name}: {e} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b072755236..229dcffa4d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2685,3 +2685,10 @@ key Space Space # Historical snapshot notice bar (View signed version / View revision). You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original. Bạn đang xem phiên bản đã ký của “{from}” (bản sửa đổi {rev}). Đây là ảnh nhanh: các thay đổi ở đây không được áp dụng đến bản gốc. You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original. Bạn đang xem bản sửa đổi {rev} của “{from}”. Đây là ảnh nhanh: các thay đổi ở đây không được áp dụng đến bản gốc. +# Rename… on a document tab (#2102). + Rename… Đổi tên… + Rename “{name}” Đổi tên “{name}” + This document has unsaved changes. They are saved first, then the file is renamed. Tài liệu này có thay đổi chưa lưu. Các thay đổi sẽ được lưu trước, sau đó tệp được đổi tên. + Save and Rename Lưu và đổi tên + Renamed to {name} Đã đổi tên thành {name} + Couldn't rename {name}: {e} Không thể đổi tên {name}: {e} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2297d1269a..e4b21f5b04 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2396,3 +2396,10 @@ animation effects Off 关 Make properties default 将属性设为默认 Pages selected 选定的页面 Page properties 页面属性 +# Rename… on a document tab (#2102). + Rename… 重命名… + Rename “{name}” 重命名“{name}” + This document has unsaved changes. They are saved first, then the file is renamed. 此文档有未保存的更改。会先保存,然后再重命名文件。 + Save and Rename 保存并重命名 + Renamed to {name} 已重命名为 {name} + Couldn't rename {name}: {e} 无法重命名 {name}:{e} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2ddb33dd6d..20c286ecfe 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2382,3 +2382,10 @@ animation effects Off 關 Make properties default 將內容設為預設 Pages selected 選取的頁面 Page properties 頁面屬性 +# Rename… on a document tab (#2102). + Rename… 重新命名… + Rename “{name}” 重新命名「{name}」 + This document has unsaved changes. They are saved first, then the file is renamed. 此文件有未儲存的變更。會先儲存,然後再重新命名檔案。 + Save and Rename 儲存並重新命名 + Renamed to {name} 已重新命名為 {name} + Couldn't rename {name}: {e} 無法重新命名 {name}:{e} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 79464624c6..3bfba61e42 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -132,6 +132,7 @@ mod organize_panel; pub mod portable; mod protect; mod recovery; +mod rename_ui; pub mod scroll_speed; #[cfg(not(target_arch = "wasm32"))] mod system_fonts; @@ -351,6 +352,8 @@ pub enum Dialog { AuditSpace, /// Signatures ▸ Show certificate. CertificateViewer, + /// Rename… on a document tab. + RenameFile, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -486,6 +489,8 @@ pub struct PdfCraftApp { pub session: Session, pub views: Vec, pub(crate) closed_tabs: Vec, + /// The Rename dialog's name being typed. + pub(crate) rename_draft: Option, /// `None` shows the Home tab. pub active: Option, pub mode: Mode, @@ -887,6 +892,7 @@ impl PdfCraftApp { session: Session::new(), views: Vec::new(), closed_tabs: Vec::new(), + rename_draft: None, active: None, mode: Mode::AllTools, default_mode: Mode::AllTools, diff --git a/crates/ui-egui/src/rename_ui.rs b/crates/ui-egui/src/rename_ui.rs new file mode 100644 index 0000000000..1737f096f1 --- /dev/null +++ b/crates/ui-egui/src/rename_ui.rs @@ -0,0 +1,229 @@ +//! 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, +} + +impl PdfCraftApp { + /// 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 (id, name) = (draft.id, draft.name); + self.save_then(index, crate::editing::SaveTarget::InPlace, move |app| app.rename_now(id, &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) }; + 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"))); + 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); + 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_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/tab_context.rs b/crates/ui-egui/src/tab_context.rs index aa16ef7105..045a8e45d5 100644 --- a/crates/ui-egui/src/tab_context.rs +++ b/crates/ui-egui/src/tab_context.rs @@ -5,6 +5,7 @@ pub(crate) enum Action { Close(DocId), Reopen, Reveal(DocId), + Rename(DocId), } impl crate::PdfCraftApp { @@ -43,6 +44,7 @@ impl crate::PdfCraftApp { #[cfg(target_arch = "wasm32")] let _ = id; } + Action::Rename(id) => self.start_rename(id), } } } diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c3d319f94f..7cd5bfe323 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/automation.rs::word_count_reads_selected_pages_and_unsaved_edits_without_mutating", "crates/ui-egui/src/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/lib.rs::doc_rename_moves_the_file_and_refuses_with_reasons", "crates/ui-egui/src/rename_ui.rs::rename_from_the_tab_menu_moves_the_file_and_keeps_the_tab", "crates/ui-egui/src/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; the extension is kept. Refused with the reason when the name is taken, the file is read-only or 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" From 5171da2d03f109f7b4431ddab7cdf3b68b345dff Mon Sep 17 00:00:00 2001 From: Osvaldo Duran <338149330+regendorf-ux@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:59:42 -0400 Subject: [PATCH 02/11] Count a file name's bytes, not its characters, when renaming The rename check limited a new file name to 255 characters, but file systems limit bytes (ext4, APFS: 255 bytes of UTF-8; NTFS: 255 UTF-16 units). A 94 character CJK name passed the check and the rename then failed. The name is now refused when it is over 255 UTF-8 bytes or over 255 UTF-16 code units, with the same error type; the message and the tool description say bytes. The limit constant is renamed to MAX_NAME_LEN (it had no other users). Test: crates/engine/tests/rename_name_length.rs::a_name_over_255_bytes_is_refused; before this change it fails because a 94-character CJK name (286 bytes with the extension) was accepted. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/tools.rs | 2 +- crates/engine/src/rename.rs | 11 ++++---- crates/engine/tests/rename_name_length.rs | 32 +++++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 crates/engine/tests/rename_name_length.rs diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index de8da1e9bf..1ebf6a071a 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -159,7 +159,7 @@ pub fn tools() -> Vec { 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 read-only or 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 characters).", + "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 read-only or 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).", ) .destructive() .with(schema(json!({ "doc": doc(), "name": { "type": "string", "description": "The new file name, with or without the extension." } }), &["doc", "name"])), diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index 717a48e301..3b55af55de 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -5,7 +5,7 @@ //! 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`, `COM1`…), no name ending in a dot or a space, at most 255 -//! characters. The file keeps its extension: a name typed without it gets it back. +//! bytes of UTF-8 and 255 UTF-16 code units. The file keeps its extension: a name typed without it gets it back. use std::path::{Path, PathBuf}; @@ -53,8 +53,9 @@ const DEVICE_NAMES: [&str; 22] = [ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", ]; -/// The longest file name the common file systems take. -const MAX_NAME_CHARS: usize = 255; +/// 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. @@ -81,8 +82,8 @@ pub fn new_file_name(current: &Path, typed: &str) -> Result 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.chars().count() > MAX_NAME_CHARS { - return Err(RenameError::Invalid(format!("a file name can be at most {MAX_NAME_CHARS} characters"))); + 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"))); } Ok(name) } diff --git a/crates/engine/tests/rename_name_length.rs b/crates/engine/tests/rename_name_length.rs new file mode 100644 index 0000000000..0e8c30e727 --- /dev/null +++ b/crates/engine/tests/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(_)))); +} From e84bce9acaaf9b89da0c34e78d9fed6112fa4330 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran <338149330+regendorf-ux@users.noreply.github.com> Date: Fri, 23 Oct 2026 03:55:14 -0400 Subject: [PATCH 03/11] i18n(ui): carry this PR's new wordings in the catalogues that must cover them Catalan, Finnish, Hindi, Korean, Indonesian, Romanian and Albanian get the strings this PR adds (AI-assisted translations from English, not separately native-reviewed), so the catalogue coverage tests pass. ATTRIBUTION.toml's sha256 for each file is refreshed. Co-Authored-By: Claude Sonnet 5.5 --- ATTRIBUTION.toml | 14 +++++++------- crates/ui-egui/src/i18n/ca.tsv | 6 ++++++ crates/ui-egui/src/i18n/fi.tsv | 6 ++++++ crates/ui-egui/src/i18n/hi.tsv | 6 ++++++ crates/ui-egui/src/i18n/id.tsv | 6 ++++++ crates/ui-egui/src/i18n/ko.tsv | 6 ++++++ crates/ui-egui/src/i18n/ro.tsv | 6 ++++++ crates/ui-egui/src/i18n/sq.tsv | 6 ++++++ 8 files changed, 49 insertions(+), 7 deletions(-) diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index d65b25a89f..c5f28b05d1 100644 --- a/ATTRIBUTION.toml +++ b/ATTRIBUTION.toml @@ -261,7 +261,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "09d2840c02b40a6049b86c2cb68151d863913e8c91c22226f25d07496c6366aa" +sha256 = "436d3771fc4a2d6c2006924ac8a44e43a553b42afcf538f03818859f40f873f0" [[asset]] path = "crates/ui-egui/src/i18n/id.tsv" title = "Indonesian interface translation catalog" @@ -271,7 +271,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "0dc1abdb262e4568f19ffb2233bfeb3686ae42df8a8d8bec2951351a50e6a886" +sha256 = "d375f01d92274c0f253805079fb6cdd491a088447545c0ca7a17e0040a45211f" [[asset]] path = "crates/ui-egui/src/i18n/ko.tsv" title = "Korean interface translation catalog" @@ -281,7 +281,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "a3e67cee4f3fff776e816523f810b2bb6353235dbdf85181c3f12896604a3339" +sha256 = "68259e7a8848fae64ad9b272e492c325c68ad46b4509dc8ed2d580c3b67322dc" [[asset]] path = "crates/ui-egui/src/i18n/ro.tsv" @@ -292,7 +292,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "00a2153c20a191fbe04f1ce61f140fd9628cfe2f8f75dad5bce8a7406e1bd091" +sha256 = "fb7888d18e8adf6a02b0bfab29dd9929265577ce592ef147e3f3593f0bd9dae3" [[asset]] @@ -304,7 +304,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "609efa92054aa76de4bb6062c0fcc0a8b450519f4b253b4c0f395b3cbb34d2ba" +sha256 = "644d0e4602b351be889206b3d00534ff866f31d7290910898f5b14c6fcc8cfec" [[asset]] path = "assets/icons/accessibility.svg" @@ -3515,7 +3515,7 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "ebd177262d8fe20f960f06df084f8a03c9504bcd9990dded3a006e35bd8ef7c9" +sha256 = "ccbf606c55b9bee52e8b47db203c6bdb9e970723b76739ebe66845a8c8567aa0" [[asset]] path = "crates/ui-egui/src/i18n/th.tsv" @@ -3537,4 +3537,4 @@ licence = "MIT OR Apache-2.0" licence_file = "LICENSE-MIT" kind = "translation" usage = "Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs" -sha256 = "5879ee3540ffb630fc83d0f2cb293cc6cbf2e081ea4577161a770794e8cbd22c" +sha256 = "21e5e8f727a070d808685c94b4d35b35e3989e61ed1584aa9431a65be6d0ae75" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index dd2f497b84..fb79d709f3 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2774,3 +2774,9 @@ theme Appearance Aspecte field names can't contain a period: {name} els noms dels camps no poden contenir cap punt: {name} two cells would both be named {name} dues cel·les es dirien {name} a field named {name} already exists ja existeix un camp anomenat {name} + Couldn't rename {name}: {e} No s'ha pogut canviar el nom de {name}: {e} + Rename “{name}” Canvia el nom de «{name}» + Renamed to {name} S'ha canviat el nom a {name} + Rename… Canvia el nom… + Save and Rename Desa i canvia el nom + This document has unsaved changes. They are saved first, then the file is renamed. Aquest document té canvis sense desar. Es desen primer i després es canvia el nom del fitxer. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index efcf3e3c6e..9481d87d11 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2783,3 +2783,9 @@ theme Appearance Teema field names can't contain a period: {name} kenttien nimissä ei voi olla pistettä: {name} two cells would both be named {name} kahdella solulla olisi sama nimi {name} a field named {name} already exists kenttä nimeltä {name} on jo olemassa + Couldn't rename {name}: {e} Kohteen {name} nimeäminen uudelleen epäonnistui: {e} + Rename “{name}” Nimeä uudelleen “{name}” + Renamed to {name} Uusi nimi: {name} + Rename… Nimeä uudelleen… + Save and Rename Tallenna ja nimeä uudelleen + This document has unsaved changes. They are saved first, then the file is renamed. Tässä asiakirjassa on tallentamattomia muutoksia. Ne tallennetaan ensin, ja sitten tiedosto nimetään uudelleen. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 7be5ec6883..f8a286df1b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2750,3 +2750,9 @@ theme Appearance स्वरूप field names can't contain a period: {name} फ़ील्ड के नामों में पूर्ण विराम (.) नहीं हो सकता: {name} two cells would both be named {name} दो सेल का नाम {name} हो जाएगा a field named {name} already exists {name} नाम का फ़ील्ड पहले से मौजूद है + Couldn't rename {name}: {e} {name} का नाम बदला नहीं जा सका: {e} + Rename “{name}” “{name}” का नाम बदलें + Renamed to {name} नाम बदलकर {name} किया गया + Rename… नाम बदलें… + Save and Rename सहेजें और नाम बदलें + This document has unsaved changes. They are saved first, then the file is renamed. इस दस्तावेज़ में बिना सहेजे बदलाव हैं। पहले उन्हें सहेजा जाता है, फिर फ़ाइल का नाम बदला जाता है। diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 3585b344e1..5f34a69437 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2751,3 +2751,9 @@ theme Appearance Tampilan field names can't contain a period: {name} nama kolom tidak boleh berisi titik: {name} two cells would both be named {name} dua sel akan sama-sama bernama {name} a field named {name} already exists kolom bernama {name} sudah ada + Couldn't rename {name}: {e} Tidak dapat mengganti nama {name}: {e} + Rename “{name}” Ganti nama “{name}” + Renamed to {name} Diganti namanya menjadi {name} + Rename… Ganti nama… + Save and Rename Simpan dan Ganti Nama + This document has unsaved changes. They are saved first, then the file is renamed. Dokumen ini memiliki perubahan yang belum disimpan. Perubahan disimpan lebih dulu, lalu file diganti namanya. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 48ef31e19b..a4b8516e95 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2750,3 +2750,9 @@ theme Appearance 모양 field names can't contain a period: {name} 필드 이름에는 마침표를 쓸 수 없습니다: {name} two cells would both be named {name} 두 셀의 이름이 모두 {name}이(가) 됩니다 a field named {name} already exists {name}(이)라는 필드가 이미 있습니다 + Couldn't rename {name}: {e} {name}의 이름을 바꿀 수 없습니다: {e} + Rename “{name}” “{name}” 이름 바꾸기 + Renamed to {name} {name}(으)로 이름을 바꿨습니다 + Rename… 이름 바꾸기… + Save and Rename 저장 후 이름 바꾸기 + This document has unsaved changes. They are saved first, then the file is renamed. 이 문서에 저장되지 않은 변경 사항이 있습니다. 먼저 저장한 후 파일 이름을 바꿉니다. diff --git a/crates/ui-egui/src/i18n/ro.tsv b/crates/ui-egui/src/i18n/ro.tsv index 0003e38519..6d44da2b15 100644 --- a/crates/ui-egui/src/i18n/ro.tsv +++ b/crates/ui-egui/src/i18n/ro.tsv @@ -2774,3 +2774,9 @@ theme Appearance Aspect field names can't contain a period: {name} numele câmpurilor nu pot conține punct: {name} two cells would both be named {name} două celule s-ar numi amândouă {name} a field named {name} already exists există deja un câmp numit {name} + Couldn't rename {name}: {e} Nu s-a putut redenumi {name}: {e} + Rename “{name}” Redenumire „{name}” + Renamed to {name} Redenumit în {name} + Rename… Redenumire… + Save and Rename Salvare și redenumire + This document has unsaved changes. They are saved first, then the file is renamed. Acest document are modificări nesalvate. Acestea se salvează mai întâi, apoi fișierul este redenumit. diff --git a/crates/ui-egui/src/i18n/sq.tsv b/crates/ui-egui/src/i18n/sq.tsv index c93efee5a3..acc6366d6b 100644 --- a/crates/ui-egui/src/i18n/sq.tsv +++ b/crates/ui-egui/src/i18n/sq.tsv @@ -2500,3 +2500,9 @@ animation effects Off Joaktiv field names can't contain a period: {name} emrat e fushave nuk mund të përmbajnë pikë: {name} two cells would both be named {name} dy qeliza do të kishin të dyja emrin {name} a field named {name} already exists ekziston tashmë një fushë me emrin {name} + Couldn't rename {name}: {e} Nuk u riemërtua dot {name}: {e} + Rename “{name}” Riemërto “{name}” + Renamed to {name} U riemërtua në {name} + Rename… Riemërto… + Save and Rename Ruaj dhe riemërto + This document has unsaved changes. They are saved first, then the file is renamed. Ky dokument ka ndryshime të paruajtura. Ruhen së pari, pastaj skedari riemërtohet. From b19b22c0e19c5c18d725ed5563309f7ce257c3ec Mon Sep 17 00:00:00 2001 From: Osvaldo Duran Melendez Date: Fri, 23 Oct 2026 19:16:26 -0400 Subject: [PATCH 04/11] Rename: confine the old path to the root too, pin the trailing-space case, note the overwrite window (review) Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/lib.rs | 3 +++ crates/engine/src/rename.rs | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index d295f888de..fba518017c 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -1102,6 +1102,9 @@ impl Automation { let name = a.str("name")?; let own_path = PathBuf::from(&own); self.check_roots(&own, &own_path, file_access::Access::Write)?; + if self.root.is_some() { + self.resolve_in_root(&own, true)?; + } if let Some(target) = pdfcraft_engine::rename_target(&own_path, name).map_err(failed)? { let shown = target.to_string_lossy().into_owned(); self.check_roots(&shown, &target, file_access::Access::Write)?; diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index 3b55af55de..ba73bb3732 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -123,6 +123,9 @@ impl Session { if std::fs::metadata(¤t).is_ok_and(|m| m.permissions().readonly()) { return Err(RenameError::ReadOnly); } + // `rename_target` checked that the name is free, but this move still replaces a file that + // appeared in between (a sync client, another program): the window is small, and std has no + // no-replace rename on every system. std::fs::rename(¤t, &target).map_err(|e| { RenameError::Failed(match e.kind() { std::io::ErrorKind::PermissionDenied => "it is open in another program, or you don't have permission".into(), @@ -168,6 +171,8 @@ mod tests { } 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()); From 7e5dfb94f89833c47058d2032bdeeebf174b9929 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran <338149330+regendorf-ux@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:08:33 -0400 Subject: [PATCH 05/11] fix(rename): keep the typed name when Save and Rename's save does not go through Save and Rename took the typed name and closed the dialog before the save ran. If the save then failed, the Save As picker was cancelled, or the "changed on disk" question was declined, the name was lost and the dialog gone. The step that follows the save now holds the name and hands it back if it is dropped without running, which covers every way the save can end without success, including the ones that answer on a later frame. The next frame opens Rename again with the name as typed, to try again or cancel. A save that goes through renames exactly as before. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/lib.rs | 5 +++ crates/ui-egui/src/rename_ui.rs | 72 ++++++++++++++++++++++++++++++++- 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0899890736..cc22994609 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -633,6 +633,9 @@ pub struct PdfCraftApp { 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, @@ -1101,6 +1104,7 @@ impl PdfCraftApp { 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, @@ -3653,6 +3657,7 @@ impl eframe::App for PdfCraftApp { self.process_file_requests(); #[cfg(not(target_arch = "wasm32"))] self.process_picked(); + self.reopen_returned_rename(); // Last, after everything that can open or answer the "save changes?" question. self.attend_save_prompt(ctx); } diff --git a/crates/ui-egui/src/rename_ui.rs b/crates/ui-egui/src/rename_ui.rs index 1737f096f1..fea410525b 100644 --- a/crates/ui-egui/src/rename_ui.rs +++ b/crates/ui-egui/src/rename_ui.rs @@ -17,7 +17,47 @@ pub(crate) struct RenameDraft { 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) { @@ -33,8 +73,12 @@ impl PdfCraftApp { 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 (id, name) = (draft.id, draft.name); - self.save_then(index, crate::editing::SaveTarget::InPlace, move |app| app.rename_now(id, &name)); + 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); } @@ -205,6 +249,7 @@ mod tests { 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"); @@ -213,6 +258,29 @@ mod tests { 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(|_| { From 4e59a322abb5f0203687fb32247f01fbfdb09886 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran <338149330+regendorf-ux@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:24 -0400 Subject: [PATCH 06/11] rustfmt Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/rename_ui.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/rename_ui.rs b/crates/ui-egui/src/rename_ui.rs index 9e8063711a..0af6cbf318 100644 --- a/crates/ui-egui/src/rename_ui.rs +++ b/crates/ui-egui/src/rename_ui.rs @@ -126,7 +126,8 @@ pub(crate) fn body(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> (bool, bool) { 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); + 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(); } From ab9835e368761617cadeed20e6527b3993ee5184 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran Melendez Date: Sun, 8 Nov 2026 22:44:47 -0500 Subject: [PATCH 07/11] Fix the merge with upstream/main: the new fields and imports it needs Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/documents.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index cdeb551cd9..b86537865e 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; From 53d04754df73b1e4885a2cdc0c5f62ec61804ea8 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran Melendez Date: Mon, 9 Nov 2026 22:22:45 -0500 Subject: [PATCH 08/11] Rename: never replace a file that appears under the new name (hard link then unlink, rename where links are unavailable); refuse COM0/LPT0, superscript device names and over-long full paths; a read-only file renames like in the file manager Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/tools.rs | 2 +- crates/engine/src/rename.rs | 187 +++++++++++++++++++++++++++++---- parity/acrobat-features.toml | 2 +- 3 files changed, 167 insertions(+), 24 deletions(-) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 8934811ca3..935f191ab8 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -213,7 +213,7 @@ pub fn tools() -> Vec { 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 read-only or 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).", + "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"])), diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index ba73bb3732..ed2efa9f6a 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -4,8 +4,9 @@ //! //! 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`, `COM1`…), no name ending in a dot or a space, at most 255 -//! bytes of UTF-8 and 255 UTF-16 code units. The file keeps its extension: a name typed without it gets it back. +//! 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}; @@ -24,8 +25,6 @@ pub enum RenameError { Invalid(String), /// Another file already has that name. Exists(String), - /// The file is marked read-only. - ReadOnly, /// The operating system refused (in use by another program, no permission, …). Failed(String), } @@ -38,7 +37,6 @@ impl std::fmt::Display for RenameError { 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::ReadOnly => write!(f, "the file is read-only"), Self::Failed(why) => write!(f, "the file could not be renamed: {why}"), } } @@ -49,10 +47,67 @@ 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; 22] = [ - "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", - "LPT6", "LPT7", "LPT8", "LPT9", +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(not(windows))] + { + use std::os::unix::ffi::OsStrExt; + path.as_os_str().as_bytes().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; @@ -85,6 +140,14 @@ pub fn new_file_name(current: &Path, typed: &str) -> Result 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) } @@ -107,6 +170,39 @@ pub fn rename_target(current: &Path, typed: &str) -> Result, Ren 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) + } + } +} + 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 @@ -120,18 +216,17 @@ impl Session { let Some(target) = rename_target(¤t, typed)? else { return Ok(current.to_string_lossy().into_owned()); }; - if std::fs::metadata(¤t).is_ok_and(|m| m.permissions().readonly()) { - return Err(RenameError::ReadOnly); - } - // `rename_target` checked that the name is free, but this move still replaces a file that - // appeared in between (a sync client, another program): the window is small, and std has no - // no-replace rename on every system. - std::fs::rename(¤t, &target).map_err(|e| { - RenameError::Failed(match e.kind() { - std::io::ErrorKind::PermissionDenied => "it is open in another program, or you don't have permission".into(), - std::io::ErrorKind::NotFound => "it is no longer where it was opened from".into(), - _ => e.to_string(), - }) + // 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. + move_no_replace(¤t, &target).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) { @@ -204,16 +299,64 @@ mod tests { 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(); - assert_eq!(session.rename_file(id, "third"), Err(RenameError::ReadOnly)); + 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(&cased, perms).unwrap(); + 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"); + } + } } diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 7e6b48c797..5a6bf75774 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -34,7 +34,7 @@ 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; the extension is kept. Refused with the reason when the name is taken, the file is read-only or in use, or the document was never saved; unsaved changes are saved first (Save and 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" From c4e5748b4a34d01b652600f645baed67fa88eb36 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran Melendez Date: Thu, 12 Nov 2026 06:24:43 -0500 Subject: [PATCH 09/11] Automation doc_rename: on Linux the move is made below the write root with no link followed (openat O_NOFOLLOW, renameat2 NOREPLACE) A parent swapped for a link between the path checks and the rename could carry the file outside the root. macOS and Windows keep the check-then-rename model. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/automation/src/documents.rs | 10 ++- crates/engine/Cargo.toml | 5 ++ crates/engine/src/rename.rs | 140 ++++++++++++++++++++++++++++- 4 files changed, 154 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fafd037d33..b8af078fa2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4475,6 +4475,7 @@ dependencies = [ "pdfcraft-xfa", "pdfcraft-xfdf", "png 0.18.1", + "rustix 1.1.5", "thiserror 2.0.21", "tiff", "unicode-segmentation", diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index 2fb1d28661..438486ced5 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -174,7 +174,15 @@ impl Automation { let shown = target.to_string_lossy().into_owned(); self.resolve_for(&shown, file_access::Access::Write, true)?; } - let path = self.session.rename_file(id, name).map_err(failed)?; + // 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) })) } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f5b924c921..96f2497f81 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -54,6 +54,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/rename.rs b/crates/engine/src/rename.rs index ed2efa9f6a..31f4f4ac29 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -203,11 +203,112 @@ fn move_no_replace(old: &Path, new: &Path) -> std::io::Result<()> { } } +/// 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 { @@ -220,7 +321,14 @@ impl Session { // 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. - move_no_replace(¤t, &target).map_err(|e| match e.kind() { + #[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()) } @@ -359,4 +467,34 @@ mod tests { 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); + } } From 894fd5a25adb057afa7fa45399064a899a2c22d6 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran Melendez Date: Thu, 12 Nov 2026 06:36:44 -0500 Subject: [PATCH 10/11] Cargo.lock: engine's rustix at the workspace's version --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index ba2a88e1eb..cf341b459b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4492,7 +4492,7 @@ dependencies = [ "pdfcraft-xfa", "pdfcraft-xfdf", "png 0.18.1", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tiff", "unicode-segmentation", From 440a7f89a2bfeeb8356e15febedddd910bddae79 Mon Sep 17 00:00:00 2001 From: Osvaldo Duran Melendez Date: Thu, 12 Nov 2026 07:33:50 -0500 Subject: [PATCH 11/11] Rename: the path length is checked on targets that are neither Unix nor Windows too (browser build) Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/rename.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index 31f4f4ac29..e2e93db27d 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -100,11 +100,16 @@ fn path_len(path: &Path) -> usize { { path.as_os_str().encode_wide().count() } - #[cfg(not(windows))] + #[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;