From 08b44e858b8761bda1b0931087ea41b0748435eb Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 16 Oct 2026 18:03:46 +0000 Subject: [PATCH 01/34] fix(ui): keep output file names taken from documents inside the chosen folder An attachment opened as a tab is named with the same plain file name as its Save suggestion, and Export certificate names the file the same way from the certificate subject. Writing files into a chosen folder refuses any name with a separator, a drive, or that is . or .., so no caller can write outside the folder. --- crates/ui-egui/src/dialogs.rs | 3 +- crates/ui-egui/src/files.rs | 53 +++++++++++++++++++++++++--- crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/src/panels.rs | 3 +- crates/ui-egui/src/sign_ui.rs | 23 +++++++++++++ crates/ui-egui/tests/pickers.rs | 61 ++++++++++++++++++++++++++++----- 6 files changed, 129 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2d2407629..0de1c6a7e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -738,8 +738,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { match action { Some(crate::sign_ui::CertAction::Trust(c)) => app.trust_certificate(*c), Some(crate::sign_ui::CertAction::Export(c)) => { - let pem = crate::sign_ui::certificate_pem(&c); - app.write_files(&[(format!("{}.cer", c.display_name()), std::sync::Arc::new(pem.into_bytes()))], "Export certificate"); + app.export_certificate(&c); } None => {} } diff --git a/crates/ui-egui/src/files.rs b/crates/ui-egui/src/files.rs index 23754e13e..f5e9e0319 100644 --- a/crates/ui-egui/src/files.rs +++ b/crates/ui-egui/src/files.rs @@ -195,9 +195,9 @@ pub(crate) fn file_stem_from_user(name: &str) -> String { if reserved { format!("_{stem}") } else { stem.to_string() } } -/// A safe native Save suggestion for a PDF-supplied attachment name. -/// This changes only the suggestion, never the stored name or the selected destination. -#[cfg(any(test, not(target_arch = "wasm32")))] +/// A plain file name for a PDF-supplied attachment name: the Save suggestion, and the tab name +/// (which later names files written from that tab). It never changes the stored name or a +/// destination the user selected. pub(crate) fn attachment_file_name(name: &str) -> String { let cleaned: String = name .chars() @@ -217,6 +217,14 @@ pub(crate) fn attachment_file_name(name: &str) -> String { if reserved { format!("_{name}") } else { name.to_string() } } +/// Whether `name` names a file directly inside a folder: not empty, `.` or `..`, with no `/` or +/// `\\`, and no drive (`C:`). On Windows any `:` is refused, which also rules out alternate data +/// streams. +pub(crate) fn is_plain_file_name(name: &str) -> bool { + let drive = matches!(name.as_bytes(), [letter, b':', ..] if letter.is_ascii_alphabetic()); + !(name.is_empty() || name == "." || name == ".." || name.contains(['/', '\\']) || drive || (cfg!(windows) && name.contains(':'))) +} + /// Pages ▸ Rotate Pages. #[derive(Clone, Debug, PartialEq)] pub struct RotateDraft { @@ -667,7 +675,12 @@ impl PdfCraftApp { /// [`Self::write_files`], then `after` once every file is written: now, or on a later frame /// when the user chooses the folder. `after` never runs when writing fails or is cancelled. + /// Every name must be a plain file name ([`is_plain_file_name`]); otherwise nothing is written. pub(crate) fn write_files_then(&mut self, named: Vec<(String, Arc>)>, title: &str, after: impl FnOnce(&mut Self) + Send + 'static) { + if let Some((name, _)) = named.iter().find(|(name, _)| !is_plain_file_name(name)) { + self.notify_fmt("Couldn't write {name}: {e}", &[("name", name), ("e", tl!("the name is not a plain file name"))]); + return; + } #[cfg(not(target_arch = "wasm32"))] { let write = move |app: &mut Self, dir: std::path::PathBuf| { @@ -996,7 +1009,7 @@ impl PdfCraftApp { #[cfg(test)] mod stem_tests { - use super::{attachment_file_name, file_stem_from_user}; + use super::{attachment_file_name, file_stem_from_user, is_plain_file_name}; #[test] fn user_file_names_stay_inside_the_folder_and_writable_everywhere() { @@ -1049,4 +1062,36 @@ mod stem_tests { assert_eq!(attachment_file_name(&once), once); } } + + #[test] + fn write_files_refuses_names_that_leave_the_folder() { + let dir = std::env::temp_dir().join(format!("pdfcraft-write-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let out = dir.join("a").join("out"); + std::fs::create_dir_all(&out).unwrap(); + let absolute = dir.join("abs.pdf").to_string_lossy().into_owned(); + let mut app = crate::PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.export_dir_override = Some(out.to_string_lossy().into_owned()); + for bad in ["../x.pdf", "..", ".", "", "sub/x.pdf", "sub\\x.pdf", "C:x.pdf", absolute.as_str()] { + assert!(!is_plain_file_name(bad), "{bad}"); + // A plain name first: nothing is written when any name in the batch is refused. + app.write_files(&[("ok.pdf".into(), std::sync::Arc::new(b"%PDF".to_vec())), (bad.into(), std::sync::Arc::new(b"%PDF".to_vec()))], "t"); + assert!(app.toast.as_ref().is_some_and(|t| t.0.contains("not a plain file name")), "{bad}"); + } + let names: Vec<_> = walk(&dir); + assert!(names.is_empty(), "{names:?}"); + app.write_files(&[("x.pdf".into(), std::sync::Arc::new(b"%PDF".to_vec()))], "t"); + assert_eq!(walk(&dir), vec![out.join("x.pdf")]); + let _ = std::fs::remove_dir_all(&dir); + } + + fn walk(dir: &std::path::Path) -> Vec { + let mut out = Vec::new(); + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { out.extend(walk(&path)) } else { out.push(path) } + } + out + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 79464624c..e7df5d670 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1520,7 +1520,8 @@ impl PdfCraftApp { match (data, open) { (Err(e), _) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]), (Ok(bytes), true) => { - if let Err(e) = self.open_bytes(&att.name, None, bytes) { + // The tab name later names files written from the tab (Split, Extract pages). + if let Err(e) = self.open_bytes(&crate::files::attachment_file_name(&att.name), None, bytes) { self.notify_fmt("Couldn't open {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]); } } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index d69148807..2007dc0af 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -784,8 +784,7 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { app.start_signing(page, None, Some(field), None); } Some(crate::sign_ui::PanelAction::ExportCertificate(c)) => { - let pem = crate::sign_ui::certificate_pem(&c); - app.write_files(&[(format!("{}.cer", c.display_name()), std::sync::Arc::new(pem.into_bytes()))], "Export certificate"); + app.export_certificate(&c); } None => {} } diff --git a/crates/ui-egui/src/sign_ui.rs b/crates/ui-egui/src/sign_ui.rs index 988833e30..3cb67bb8e 100644 --- a/crates/ui-egui/src/sign_ui.rs +++ b/crates/ui-egui/src/sign_ui.rs @@ -266,6 +266,12 @@ fn entry_unusable(u: &sign::windows::Unusable) -> DigitalIdEntry { } impl PdfCraftApp { + /// Export certificate: write `c` as PEM into a chosen folder, named after its subject. + pub(crate) fn export_certificate(&mut self, c: &Certificate) { + let name = format!("{}.cer", crate::files::attachment_file_name(&c.display_name())); + self.write_files(&[(name, std::sync::Arc::new(certificate_pem(c).into_bytes()))], "Export certificate"); + } + /// Start signing: the rectangle (or field) is known; show Sign with a Digital ID. pub fn start_signing(&mut self, page: usize, rect: Option<[f64; 4]>, field: Option, certify: Option) { self.refresh_os_key_store_ids(); @@ -1496,6 +1502,23 @@ mod tests { Ok(PathBuf::from(&app.digital_ids[i].path)) } + #[test] + fn an_exported_certificate_is_written_inside_the_chosen_folder() { + let dir = scratch(); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let key = PrivateKey::generate_p256().unwrap(); + let cert = Certificate::self_signed(&Name::build("../x", "", "", "", ""), &key, sign::Time::from_unix(0), 1, &[1]).unwrap(); + let mut app = PdfCraftApp::new(); + app.export_dir_override = Some(out.to_string_lossy().into_owned()); + app.export_certificate(&cert); + let written: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(written, vec![std::ffi::OsString::from("out")]); + let pem = std::fs::read_to_string(out.join(".._x.cer")).unwrap(); + assert!(pem.starts_with("-----BEGIN CERTIFICATE-----"), "{pem}"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn signature_status_style_gives_each_verdict_its_panel_icon() { assert_eq!(signature_status_style(SignatureStatus::Valid).0, "circle-check"); diff --git a/crates/ui-egui/tests/pickers.rs b/crates/ui-egui/tests/pickers.rs index e7db8cffa..bf9df10b3 100644 --- a/crates/ui-egui/tests/pickers.rs +++ b/crates/ui-egui/tests/pickers.rs @@ -748,20 +748,26 @@ fn a_background_startup_forms_script_notice_waits_until_its_tab_is_selected() { /// Embedded bytes and the PDF's original /UF name stay independent of the Save suggestion. fn attachment_fixture() -> Vec { - let name = "invoice\u{202e}fdp.exe"; + attachment_pdf("invoice\u{202e}fdp.exe", b"hello notes") +} + +/// A one-page PDF with one embedded file whose /UF name is `name`. +fn attachment_pdf(name: &str, data: &[u8]) -> Vec { let uf = std::iter::once(0xfeffu16).chain(name.encode_utf16()).map(|c| format!("{c:04X}")).collect::(); - let objs = [ - "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(notes.txt) 5 0 R] >> >> >>".to_string(), - "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> >>".to_string(), - "<< /Type /EmbeddedFile /Length 11 >>\nstream\nhello notes\nendstream".to_string(), - format!("<< /Type /Filespec /F (notes.txt) /UF <{uf}> /EF << /F 4 0 R >> >>"), + let objs: [Vec; 5] = [ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(notes.txt) 5 0 R] >> >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> >>".to_vec(), + [format!("<< /Type /EmbeddedFile /Length {} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(), + format!("<< /Type /Filespec /F (notes.txt) /UF <{uf}> /EF << /F 4 0 R >> >>").into_bytes(), ]; let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); for (i, o) in objs.iter().enumerate() { offsets.push(out.len()); - out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); } let xref = out.len(); out.extend_from_slice(b"xref\n0 6\n0000000000 65535 f \n"); @@ -824,3 +830,42 @@ fn attachment_save_preserves_bytes_metadata_and_selected_destination() { assert_eq!(doc.info.attachments[index].name, raw_name); assert_eq!(doc.bytes.as_ref(), &original); } + +/// Every file under `dir`, recursively, sorted. +fn files_under(dir: &std::path::Path) -> Vec { + let mut out = Vec::new(); + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { out.extend(files_under(&path)) } else { out.push(path) } + } + out.sort(); + out +} + +#[test] +fn files_written_from_an_attachment_tab_stay_inside_the_chosen_folder() { + let dir = AttachmentDir::new(); + let absolute = dir.0.join("elsewhere").join("x.pdf").to_string_lossy().into_owned(); + for name in ["../../x.pdf", absolute.as_str()] { + let out = dir.0.join("a").join("b").join("out"); + std::fs::create_dir_all(&out).unwrap(); + let mut h = harness(&[]); + h.state_mut().open_bytes("outer.pdf", None, attachment_pdf(name, &fixture(2))).unwrap(); + h.run_steps(2); + let id = h.state().views[0].id; + h.state_mut().attachment_action(id, 0, true); + h.run_steps(2); + assert_eq!(h.state().views.len(), 2, "{name}: the attachment opens as a tab"); + h.state_mut().export_dir_override = Some(out.to_string_lossy().into_owned()); + h.state_mut().split_active(&pdfcraft_ui_egui::SplitPlan::By(pdfcraft_engine::SplitBy::PageCount(1))); + let written = files_under(&dir.0); + assert_eq!(written.len(), 2, "{name}: two split parts, got {written:?}"); + assert!(written.iter().all(|p| p.parent() == Some(out.as_path())), "{name}: {written:?}"); + // Extract writes page 1 under the name Split gave it. + h.state_mut().extract_draft = pdfcraft_ui_egui::ExtractDraft { separate: true, ..Default::default() }; + h.state_mut().extract_selection(); + assert!(h.state().toast.as_ref().is_some_and(|t| t.0.starts_with("Wrote 1 file")), "{name}: {:?}", h.state().toast); + assert_eq!(files_under(&dir.0), written, "{name}"); + std::fs::remove_dir_all(dir.0.join("a")).unwrap(); + } +} From 265403813b207a3e42c4834726fc32765debbeb1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 16 Oct 2026 18:16:41 +0000 Subject: [PATCH 02/34] fix(links): resolve remote document paths with the shared path check GoToR file specifications go through craft-docpath: network, device and object-manager paths (\??\, /??/) are refused without touching the filesystem, relative targets resolve against the source document's folder, and a result that is not absolute is refused rather than read against the working directory. Files named on the command line open under their absolute path, so their relative links keep resolving. --- Cargo.lock | 5 +++ Cargo.toml | 2 + apps/pdfcraft/src/main.rs | 5 ++- crates/engine/Cargo.toml | 1 + crates/engine/src/links.rs | 81 +++++++++++++++++++++++++++----------- 5 files changed, 69 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 91ed3c490..8358ee188 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1142,6 +1142,10 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-docpath" +version = "0.1.0" + [[package]] name = "craft-print" version = "0.1.0" @@ -4100,6 +4104,7 @@ name = "pdfcraft-engine" version = "0.8.0" dependencies = [ "chrono", + "craft-docpath", "icu_properties", "idna", "image", diff --git a/Cargo.toml b/Cargo.toml index 597dd316f..905b3a390 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "f58bc1a3df490992d633393d0898af0588ce882c" } # Shared system spooler; document composition remains in pdfcraft-print. craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "666c358065261a2816b376fa3bb10538dbf53040" } +# Whether a path stored in a document may be opened (GoToR link targets). +craft-docpath = { path = "../secfix-craft-libs/crates/docpath" } # internal pdfcraft-geom = { path = "crates/geom", version = "0.8.0" } pdfcraft-filters = { path = "crates/filters", version = "0.8.0" } diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 7a0bb2043..4d9857ce1 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -231,7 +231,10 @@ fn main() -> eframe::Result { // running and exits (#282, #317, #1726). Any option means the caller wants this launch's own // window. let may_hand_off = !new_window && !files.is_empty() && options.is_empty() && control_file.is_none() && !create_images; - let instance = match single_instance::claim(&single_instance::absolute(&files), may_hand_off) { + // Absolute for this instance too: links relative to a document resolve against its folder, + // never the working directory. + let files = single_instance::absolute(&files); + let instance = match single_instance::claim(&files, may_hand_off) { single_instance::Claim::HandedOff => return Ok(()), single_instance::Claim::Primary(server) => Some(server), single_instance::Claim::Alone => None, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 7de028763..74567eb48 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +craft-docpath = { workspace = true } pdfcraft-measure = { workspace = true } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff"] } pdfcraft-render = { workspace = true } diff --git a/crates/engine/src/links.rs b/crates/engine/src/links.rs index 5dd9aff5b..4902d72f5 100644 --- a/crates/engine/src/links.rs +++ b/crates/engine/src/links.rs @@ -137,7 +137,8 @@ pub enum RemoteDocumentPathError { Empty, TooLong, Hidden, - UrlOrNetwork, + /// A URL, a network or device path, or a path that climbs above its root. + NotLocal(craft_docpath::Refused), MissingSourcePath, /// The target doesn't end in `.pdf`. NotPdf, @@ -155,7 +156,7 @@ impl std::fmt::Display for RemoteDocumentPathError { Self::Empty => f.write_str("the file specification is empty"), Self::TooLong => f.write_str("the file specification is too long"), Self::Hidden => f.write_str("the file specification contains hidden or control characters"), - Self::UrlOrNetwork => f.write_str("only local document paths are supported"), + Self::NotLocal(r) => write!(f, "only local document paths are supported: {r}"), Self::MissingSourcePath => f.write_str("a relative link needs a source document path"), Self::NotPdf => f.write_str("the linked file is not a .pdf file"), Self::NotAFile => f.write_str("the linked path is not a regular file"), @@ -173,7 +174,9 @@ pub fn remote_document_path_is_absolute(raw: &str) -> bool { } /// Resolve a PDF remote-Go-To file specification to a local path without opening it. -/// Relative paths are based on the source document; an in-memory source has no fallback to CWD. +/// Relative paths are based on the source document, which should be an absolute path; an +/// in-memory source has no fallback to CWD. URLs (including `file:`), network and device paths are +/// refused ([`craft_docpath::resolve`]). pub fn resolve_remote_document_path(source: Option<&Path>, raw: &str) -> Result { if raw.is_empty() || raw.trim().is_empty() { return Err(RemoteDocumentPathError::Empty); @@ -184,25 +187,22 @@ pub fn resolve_remote_document_path(source: Option<&Path>, raw: &str) -> Result< if raw.chars().any(hides_text) { return Err(RemoteDocumentPathError::Hidden); } - if raw.starts_with("//") || raw.starts_with("\\\\") || raw.starts_with("/\\") || raw.starts_with("\\/") { - return Err(RemoteDocumentPathError::UrlOrNetwork); - } - let path = Path::new(raw); - let drive_absolute = remote_document_path_is_absolute(raw); + // A GoToR file specification is a path, not a URL: any scheme of two or more characters is + // refused (one letter is a drive), `file:` and names such as `custom:target.pdf` included. if let Some((scheme, _)) = raw.split_once(':') { - let valid_scheme = scheme.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) + let is_scheme = scheme.len() > 1 + && scheme.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) && scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); - let windows_drive = scheme.len() == 1 && drive_absolute; - if valid_scheme && !windows_drive { - return Err(RemoteDocumentPathError::UrlOrNetwork); + if is_scheme { + return Err(RemoteDocumentPathError::NotLocal(craft_docpath::Refused::Url)); } } - if drive_absolute { - return Ok(path.to_path_buf()); + let path = craft_docpath::resolve(raw, source).map_err(RemoteDocumentPathError::NotLocal)?; + // A relative result would be read against the working directory. + if !path.is_absolute() { + return Err(RemoteDocumentPathError::MissingSourcePath); } - let source = source.ok_or(RemoteDocumentPathError::MissingSourcePath)?; - let parent = source.parent().ok_or(RemoteDocumentPathError::MissingSourcePath)?; - Ok(parent.join(path)) + Ok(path) } /// Largest linked PDF a GoToR link may open (1 GiB, the largest size the large-file work measures). @@ -503,23 +503,56 @@ mod tests { use super::{RemoteDocumentPathError as E, resolve_remote_document_path as resolve}; use std::path::Path; - let source = Path::new("/docs/chapter/source.pdf"); - assert_eq!(resolve(Some(source), "../target.pdf").as_deref(), Ok(Path::new("/docs/chapter/../target.pdf"))); + let source = std::env::temp_dir().join("chapter").join("source.pdf"); + let source = source.as_path(); + let folder = source.parent().unwrap(); + assert_eq!(resolve(Some(source), "target.pdf"), Ok(folder.join("target.pdf"))); + assert_eq!(resolve(Some(source), "../target.pdf").as_deref(), Ok(folder.parent().unwrap().join("target.pdf").as_path())); + #[cfg(unix)] assert_eq!(resolve(Some(source), "/manual/target.pdf").as_deref(), Ok(Path::new("/manual/target.pdf"))); assert_eq!(resolve(None, "target.pdf"), Err(E::MissingSourcePath)); + assert_eq!(resolve(Some(Path::new("source.pdf")), "target.pdf"), Err(E::MissingSourcePath), "a relative source is not used"); assert_eq!(resolve(Some(source), ""), Err(E::Empty)); assert_eq!(resolve(Some(source), " "), Err(E::Empty)); - for url in ["file:///tmp/a.pdf", "https://example.org/a.pdf", "smb://host/share/a.pdf", "ftp://host/a.pdf", "custom:target.pdf"] { - assert_eq!(resolve(Some(source), url), Err(E::UrlOrNetwork), "{url}"); - } - for network_path in ["//server/share/a.pdf", "\\\\server\\share\\a.pdf", "\\\\?\\C:\\a.pdf", "\\\\.\\device\\a.pdf", "/\\server/share/a.pdf"] + for url in + ["file:///tmp/a.pdf", "file://h/s/a.pdf", "https://example.org/a.pdf", "smb://host/share/a.pdf", "ftp://host/a.pdf", "custom:target.pdf"] { - assert_eq!(resolve(Some(source), network_path), Err(E::UrlOrNetwork), "{network_path:?}"); + assert!(matches!(resolve(Some(source), url), Err(E::NotLocal(_))), "{url}"); } assert_eq!(resolve(Some(source), "folder/hidden\u{200B}.pdf"), Err(E::Hidden)); assert_eq!(resolve(Some(source), &"a".repeat(super::MAX_REMOTE_DOCUMENT_PATH_BYTES + 1)), Err(E::TooLong)); } + #[test] + fn remote_document_paths_to_other_computers_and_devices_are_refused() { + use super::{RemoteDocumentPathError as E, resolve_remote_document_path as resolve}; + + let source = std::env::temp_dir().join("chapter").join("source.pdf"); + let source = source.as_path(); + // Refused before any filesystem access: none of these exist, and a stat of a network path + // would contact its host. + for not_local in [ + "//server/share/a.pdf", + "\\\\server\\share\\a.pdf", + "\\\\h\\s\\a.pdf", + "\\\\?\\UNC\\h\\s\\a.pdf", + "\\??\\UNC\\h\\s\\a.pdf", + "/??/x", + "\\??\\C:\\a.pdf", + "\\\\.\\device\\a.pdf", + "/\\server/share/a.pdf", + "NUL.pdf", + ] { + assert!(matches!(resolve(Some(source), not_local), Err(E::NotLocal(_))), "{not_local:?}"); + } + // Linux reads `//tmp/x` as `/tmp/x`, but on Windows it names a share. + #[cfg(unix)] + { + let doubled = format!("/{}", source.with_file_name("a.pdf").display()); + assert!(matches!(resolve(Some(source), &doubled), Err(E::NotLocal(_))), "{doubled}"); + } + } + #[test] fn urls_follow_the_artcraft_scheme() { assert_eq!(super::APP_PAGE, format!("{}/apps/{}", super::WEBSITE, super::APP)); From c7a6feb3937e7101d46cddac82a06612ada5b6c8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 16 Oct 2026 21:02:39 +0000 Subject: [PATCH 03/34] i18n: translate the new link and file-name messages --- ATTRIBUTION.toml | 44 ++++++++++++++--------------- crates/ui-egui/src/i18n/ar.tsv | 1 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/kk.tsv | 1 + crates/ui-egui/src/i18n/lt.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sl.tsv | 1 + crates/ui-egui/src/i18n/te.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 23 files changed, 44 insertions(+), 22 deletions(-) diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index be9e2c448..87b11279e 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 = "a3234684d5318ce38213c79533d3eebb9c635497ba9e00fb9ca7ebe2fad9d73d" # 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 = "c5e0206846b009bcb366d092c3d64fd8b9e42d29d5406fb73ae36ecb1f2083d5" [[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 = "349a2ead371bdbfeefb9ab2279c676b205cefe163cbef174f8123fe4bf739ab9" [[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 = "cb332907792d4aa760ca9862160e24a7b469afdbcfb93235e99deb8d58604ae2" [[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 = "ebd3a12e471ba9d9a69e6532fbac2d027dec3c91b79cdfbb1c6c386d13de3bd6" [[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 = "f5e0553165ab0223bfbc809b1630170d1af11d6546ae5a682d4090104b6e4a05" [[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 = "dd2171a0a940a84e512fd6408a11cddf104be897ec4ab670c5ef6f1781ccb671" [[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 = "1b9b3d0d6dab626c3acb8c9aa64d64e56b98eb3f2faf71dcb1957067e72706db" [[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 = "668f23f4095120343e3f0910dc8f5844765370fae40400c48d685cad20dcf60e" [[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 = "02f3fd4b2721b0ea9c01c99d477a0339a28180514568179d3fc420e7fb81c671" [[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 = "26eb438c309d34e55eba959a21f139db91fa5fd1d6d4b7c3d1cd0fa79a60a5b0" [[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 = "c04b6d0320bce999b33bd189bffcec8a196d4169e56cc65675dc920c5a671dac" [[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 = "37b042977d934b0b550e5f52faa5d90abbcb9e7ff61ff9588021610ce709e474" [[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 = "3d1f1d2558eec1271fa653bc38616feeefc6559deeb2a0cdbf07d67634e9ac97" [[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 = "03071249bd6c13f79da72262415e484fb1aa36098a37a49094b9dab58cebc4e2" [[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 = "c0ba73b27b95b275f5eebc040ab1c3c6c3b227c63e1c637b4cdb27d0a9264a8b" [[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 = "e3af76714ee9899328a453ec83195f4dc462fe48ba445fbe3688c777e74bc9dc" [[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 = "0855d7f785c433799da83400ebc932f987eb543008486bc4f553aadb4102c2ba" [[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 = "884ab18d60db52f65cd0e30530e196c73c0e627f450bc948517e2f4b7deeb04b" [[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 = "c805a2c6da08e77a9a7455856d82c168cf6f353d96e1dc140fcc8898f12ba538" [[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 = "11619064ae9edaeee5d601b7008e40095a40375a3e1a298155d59cb758fe7d34" [[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 = "89f2c7495cfb0fc9d36d35b95c056dbeda18ccae521250babac719ff5df62d89" [[asset]] diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 5a0e6e9c9..246a26fa6 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -1703,6 +1703,7 @@ Couldn't use {name}: {e} تعذّر استخدام {name}: {e} Couldn't extract pages: {e} تعذّر استخراج الصفحات: {e} Couldn't write {name}: {e} تعذّرت كتابة {name}: {e} + the name is not a plain file name الاسم ليس اسم ملف بسيطًا Wrote 1 file to {dir} كُتب ملف واحد في {dir} Wrote {n} files to {dir} كُتب {n} ملفات في {dir} No pages match those choices لا صفحات تطابق هذه الاختيارات diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 90791f4a8..a39489aed 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1664,6 +1664,7 @@ Couldn't use {name}: {e} {name} не можа да бъде използван: {e} Couldn't extract pages: {e} Страниците не можаха да бъдат извлечени: {e} Couldn't write {name}: {e} {name} не можа да бъде записан: {e} + the name is not a plain file name името не е обикновено име на файл Wrote 1 file to {dir} Записан е 1 файл в {dir} Wrote {n} files to {dir} Записани са {n} файла в {dir} No pages match those choices Няма страници, отговарящи на този избор diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4bbb9a5e7..3b7c677e0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1755,6 +1755,7 @@ key Space Mezerník Couldn't use {name}: {e} {name} nelze použít: {e} Couldn't extract pages: {e} Stránky nelze extrahovat: {e} Couldn't write {name}: {e} {name} nelze zapsat: {e} + the name is not a plain file name název není prostý název souboru Wrote 1 file to {dir} Zapsán 1 soubor do {dir} Wrote {n} files to {dir} Zapsáno souborů: {n} (složka {dir}) No pages match those choices Těmto volbám neodpovídají žádné stránky diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 796543525..c98c40561 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1637,6 +1637,7 @@ Couldn't use {name}: {e} {name} konnte nicht verwendet werden: {e} Couldn't extract pages: {e} Seiten konnten nicht extrahiert werden: {e} Couldn't write {name}: {e} {name} konnte nicht geschrieben werden: {e} + the name is not a plain file name der Name ist kein einfacher Dateiname Wrote 1 file to {dir} 1 Datei nach {dir} geschrieben Wrote {n} files to {dir} {n} Dateien nach {dir} geschrieben No pages match those choices Keine Seiten entsprechen dieser Auswahl diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 57de6eef0..9be3e19c2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1215,6 +1215,7 @@ Couldn't use {name}: {e} Δεν ήταν δυνατή η χρήση του {name}: {e} Couldn't extract pages: {e} Δεν ήταν δυνατή η εξαγωγή σελίδων: {e} Couldn't write {name}: {e} Δεν ήταν δυνατή η εγγραφή του {name}: {e} + the name is not a plain file name το όνομα δεν είναι απλό όνομα αρχείου Wrote 1 file to {dir} Γράφτηκε 1 αρχείο στον φάκελο {dir} Wrote {n} files to {dir} Γράφτηκαν {n} αρχεία στον φάκελο {dir} No pages match those choices Καμία σελίδα δεν αντιστοιχεί σε αυτές τις επιλογές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e4eb63446..6a48611a3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1714,6 +1714,7 @@ action wizard Start Iniciar Couldn't use {name}: {e} No se pudo usar {name}: {e} Couldn't extract pages: {e} No se pudieron extraer las páginas: {e} Couldn't write {name}: {e} No se pudo escribir {name}: {e} + the name is not a plain file name el nombre no es un nombre de archivo simple Wrote 1 file to {dir} Se ha escrito 1 archivo en {dir} Wrote {n} files to {dir} Se han escrito {n} archivos en {dir} No pages match those choices Ninguna página coincide con esas opciones diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 62acea1da..0de88637a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1632,6 +1632,7 @@ Couldn't use {name}: {e} Impossible d'utiliser {name} : {e} Couldn't extract pages: {e} Impossible d'extraire les pages : {e} Couldn't write {name}: {e} Impossible d'écrire {name} : {e} + the name is not a plain file name le nom n'est pas un simple nom de fichier Wrote 1 file to {dir} 1 fichier écrit dans {dir} Wrote {n} files to {dir} {n} fichiers écrits dans {dir} No pages match those choices Aucune page ne correspond à ces choix diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2238e1ade..2d7dd82a1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1622,6 +1622,7 @@ Couldn't use {name}: {e} {name} használata nem sikerült: {e} Couldn't extract pages: {e} Az oldalakat nem sikerült kinyerni: {e} Couldn't write {name}: {e} {name} írása nem sikerült: {e} + the name is not a plain file name a név nem egyszerű fájlnév Wrote 1 file to {dir} 1 fájl ide írva: {dir} Wrote {n} files to {dir} {n} fájl ide írva: {dir} No pages match those choices Egy oldal sem felel meg ezeknek a választásoknak diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 3fa2263a0..169533374 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1709,6 +1709,7 @@ Couldn't use {name}: {e} Impossibile usare {name}: {e} Couldn't extract pages: {e} Impossibile estrarre le pagine: {e} Couldn't write {name}: {e} Impossibile scrivere {name}: {e} + the name is not a plain file name il nome non è un semplice nome file Wrote 1 file to {dir} Scritto 1 file in {dir} Wrote {n} files to {dir} Scritti {n} file in {dir} No pages match those choices Nessuna pagina corrisponde a queste scelte diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ee9439e31..c86303174 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1713,6 +1713,7 @@ Couldn't use {name}: {e} {name} を使用できませんでした: {e} Couldn't extract pages: {e} ページを抽出できませんでした: {e} Couldn't write {name}: {e} {name} に書き込めませんでした: {e} + the name is not a plain file name 名前が単独のファイル名ではありません Wrote 1 file to {dir} {dir} に 1 ファイルを書き込みました Wrote {n} files to {dir} {dir} に {n} ファイルを書き込みました No pages match those choices 条件に一致するページはありません diff --git a/crates/ui-egui/src/i18n/kk.tsv b/crates/ui-egui/src/i18n/kk.tsv index 827165ae3..64a4ea26f 100644 --- a/crates/ui-egui/src/i18n/kk.tsv +++ b/crates/ui-egui/src/i18n/kk.tsv @@ -1634,6 +1634,7 @@ Couldn't use {name}: {e} {name} файлын пайдалану мүмкін болмады: {e} Couldn't extract pages: {e} Беттерді шығарып алу мүмкін болмады: {e} Couldn't write {name}: {e} {name} файлына жазу мүмкін болмады: {e} + the name is not a plain file name атау қарапайым файл атауы емес Wrote 1 file to {dir} 1 файл {dir} ішіне жазылды Wrote {n} files to {dir} {n} файл {dir} ішіне жазылды No pages match those choices Ешбір бет бұл таңдауларға сәйкес келмейді diff --git a/crates/ui-egui/src/i18n/lt.tsv b/crates/ui-egui/src/i18n/lt.tsv index 56a785cd3..d98befcf4 100644 --- a/crates/ui-egui/src/i18n/lt.tsv +++ b/crates/ui-egui/src/i18n/lt.tsv @@ -1965,6 +1965,7 @@ comment menu Edit Redaguoti Couldn't use the photo: {e} Nepavyko panaudoti nuotraukos: {e} Couldn't use {name}: {e} Nepavyko panaudoti {name}: {e} Couldn't write {name}: {e} Nepavyko įrašyti {name}: {e} + the name is not a plain file name vardas nėra paprastas failo vardas Couldn't write {path}: {e} Nepavyko įrašyti {path}: {e} Create link Kurti saitą Created 1 link Sukurtas 1 saitas diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3dbb24705..e8df52794 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1696,6 +1696,7 @@ Couldn't use {name}: {e} Nie można użyć {name}: {e} Couldn't extract pages: {e} Nie można wyodrębnić stron: {e} Couldn't write {name}: {e} Nie można zapisać {name}: {e} + the name is not a plain file name nazwa nie jest zwykłą nazwą pliku Wrote 1 file to {dir} Zapisano 1 plik w {dir} Wrote {n} files to {dir} Liczba plików zapisanych w {dir}: {n} No pages match those choices Żadna strona nie pasuje do wybranych opcji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8b3baa2d3..dbefb9d04 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1538,6 +1538,7 @@ Couldn't use {name}: {e} Não foi possível usar {name}: {e} Couldn't extract pages: {e} Não foi possível extrair páginas: {e} Couldn't write {name}: {e} Não foi possível gravar {name}: {e} + the name is not a plain file name o nome não é um nome de arquivo simples Wrote 1 file to {dir} 1 arquivo gravado em {dir} Wrote {n} files to {dir} {n} arquivos gravados em {dir} No pages match those choices Nenhuma página corresponde a essas opções diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d0f8fc239..d5cd9d6cb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1704,6 +1704,7 @@ Couldn't use {name}: {e} Не удалось использовать {name}: {e} Couldn't extract pages: {e} Не удалось извлечь страницы: {e} Couldn't write {name}: {e} Не удалось записать {name}: {e} + the name is not a plain file name имя не является простым именем файла Wrote 1 file to {dir} Записан 1 файл в {dir} Wrote {n} files to {dir} Записано {n} файлов в {dir} No pages match those choices Страницы не соответствуют этим выбору diff --git a/crates/ui-egui/src/i18n/sl.tsv b/crates/ui-egui/src/i18n/sl.tsv index 92d9c9a6e..560450c25 100644 --- a/crates/ui-egui/src/i18n/sl.tsv +++ b/crates/ui-egui/src/i18n/sl.tsv @@ -479,6 +479,7 @@ Couldn't take the snapshot: {e} Posnetka ni bilo mogoče usvariti: {e} Couldn't use {name}: {e} Datoteke {name} ni bilo mogoče uporabiti: {e} Couldn't write {name}: {e} Datoteke {name} ni bilo mogoče zapisati: {e} + the name is not a plain file name ime ni preprosto ime datoteke Couldn't write {path}: {e} Poti {path} ni bilo mogoče zapisati: {e} Counterclockwise 90 degrees 90 stopinj v levo Country/Region Država/regija diff --git a/crates/ui-egui/src/i18n/te.tsv b/crates/ui-egui/src/i18n/te.tsv index 07b716eac..c3900c825 100644 --- a/crates/ui-egui/src/i18n/te.tsv +++ b/crates/ui-egui/src/i18n/te.tsv @@ -1623,6 +1623,7 @@ action wizard Start ప్రారంభించు Couldn't use {name}: {e} {name}ను ఉపయోగించడం సాధ్యం కాలేదు: {e} Couldn't extract pages: {e} పేజీలను వేరు తీయడం సాధ్యం కాలేదు: {e} Couldn't write {name}: {e} {name}ను రాయడం సాధ్యం కాలేదు: {e} + the name is not a plain file name పేరు సాధారణ ఫైల్ పేరు కాదు Wrote 1 file to {dir} {dir}లో 1 ఫైల్ సేవ్ చేయబడింది Wrote {n} files to {dir} {dir}లో {n} ఫైల్‌లు సేవ్ చేయబడ్డాయి No pages match those choices ఆ ఎంపికలకు సరిపోయే పేజీలు ఏవీ లేవు diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 30e19f213..bec543b02 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1603,6 +1603,7 @@ Couldn't use {name}: {e} {name} kullanılamadı: {e} Couldn't extract pages: {e} Sayfalar ayıklanamadı: {e} Couldn't write {name}: {e} {name} yazılamadı: {e} + the name is not a plain file name ad, basit bir dosya adı değil Wrote 1 file to {dir} 1 dosya {dir} konumuna yazıldı Wrote {n} files to {dir} {n} dosya {dir} konumuna yazıldı No pages match those choices Bu seçimlerle eşleşen sayfa yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c60799ef1..379e47317 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1701,6 +1701,7 @@ Couldn't use {name}: {e} Не вдалося використати {name}: {e} Couldn't extract pages: {e} Не вдалося видобути сторінки: {e} Couldn't write {name}: {e} Не вдалося записати {name}: {e} + the name is not a plain file name назва не є простою назвою файлу Wrote 1 file to {dir} Записано 1 файл у {dir} Wrote {n} files to {dir} Записано файлів ({n}) у {dir} No pages match those choices Жодна сторінка не відповідає вибраним параметрам diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b07275523..b68d6f61e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1955,6 +1955,7 @@ comment menu Edit Sửa Couldn't use the photo: {e} Không thể dùng ảnh: {e} Couldn't use {name}: {e} Không thể dùng {name}: {e} Couldn't write {name}: {e} Không thể ghi {name}: {e} + the name is not a plain file name tên không phải là tên tệp đơn thuần Couldn't write {path}: {e} Không thể ghi {path}: {e} Create link Tạo liên kết Created 1 link Đã tạo 1 liên kết diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2297d1269..1f37b431d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1671,6 +1671,7 @@ Couldn't use {name}: {e} 无法使用{name}:{e} Couldn't extract pages: {e} 无法提取页面:{e} Couldn't write {name}: {e} 无法写入{name}:{e} + the name is not a plain file name 名称不是单纯的文件名 Wrote 1 file to {dir} 已将 1 个文件写入{dir} Wrote {n} files to {dir} 已将{n}个文件写入{dir} No pages match those choices 所选条件没有匹配的页面 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2ddb33dd6..0cd22d7ff 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1615,6 +1615,7 @@ Couldn't use {name}: {e} 無法使用{name}:{e} Couldn't extract pages: {e} 無法提取頁面:{e} Couldn't write {name}: {e} 無法寫入{name}:{e} + the name is not a plain file name 名稱不是單純的檔案名稱 Wrote 1 file to {dir} 已將 1 個檔案寫入{dir} Wrote {n} files to {dir} 已將{n}個檔案寫入{dir} No pages match those choices 所選條件沒有匹配的頁面 From 77776ca2c6d6c00408e8e096d6a8411bd9e3bb37 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 17 Oct 2026 02:21:34 +0000 Subject: [PATCH 04/34] Build: use craft-docpath from craft-libs --- Cargo.lock | 1 + Cargo.toml | 2 +- deny.toml | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8358ee188..1d44502dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1145,6 +1145,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" +source = "git+https://github.com/aiongg/craft-libs?rev=12281d07fedff5c955bb68344fb287aa5d87971e#12281d07fedff5c955bb68344fb287aa5d87971e" [[package]] name = "craft-print" diff --git a/Cargo.toml b/Cargo.toml index 905b3a390..683a029ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0 # Shared system spooler; document composition remains in pdfcraft-print. craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "666c358065261a2816b376fa3bb10538dbf53040" } # Whether a path stored in a document may be opened (GoToR link targets). -craft-docpath = { path = "../secfix-craft-libs/crates/docpath" } +craft-docpath = { git = "https://github.com/aiongg/craft-libs", version = "0.1.0", rev = "12281d07fedff5c955bb68344fb287aa5d87971e" } # internal pdfcraft-geom = { path = "crates/geom", version = "0.8.0" } pdfcraft-filters = { path = "crates/filters", version = "0.8.0" } diff --git a/deny.toml b/deny.toml index 2362d5682..738a9f706 100644 --- a/deny.toml +++ b/deny.toml @@ -34,7 +34,7 @@ unknown-registry = "deny" unknown-git = "deny" # Shared UI components and spooler; Cargo.toml pins the immutable revision. craft-print pins # storytold's winprint fork (Windows printing, #1107) to an immutable revision of its own. -allow-git = ["https://github.com/storytold/craft-libs", "https://github.com/storytold/winprint.rs"] +allow-git = ["https://github.com/storytold/craft-libs", "https://github.com/aiongg/craft-libs", "https://github.com/storytold/winprint.rs"] [advisories] yanked = "warn" From 5cf11e9b8d3f8c75f13a52cfa0f2189aa4029939 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Sat, 17 Oct 2026 12:03:16 -0600 Subject: [PATCH 05/34] Build: take craft-docpath from the merged craft-libs rev craft-libs#169 is merged, so the fork pin is no longer needed. Pinned to storytold/craft-libs 82a24b006eefa036b43c09a67fb9a3fbd17ffe63 (main after the merge) rather than the older 12281d07, which predates resolve_absolute and the Windows colon refusal. --- Cargo.lock | 2 +- Cargo.toml | 2 +- deny.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1d44502dd..4e661341d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1145,7 +1145,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=12281d07fedff5c955bb68344fb287aa5d87971e#12281d07fedff5c955bb68344fb287aa5d87971e" +source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63" [[package]] name = "craft-print" diff --git a/Cargo.toml b/Cargo.toml index 683a029ca..27fd003e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0 # Shared system spooler; document composition remains in pdfcraft-print. craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "666c358065261a2816b376fa3bb10538dbf53040" } # Whether a path stored in a document may be opened (GoToR link targets). -craft-docpath = { git = "https://github.com/aiongg/craft-libs", version = "0.1.0", rev = "12281d07fedff5c955bb68344fb287aa5d87971e" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" } # internal pdfcraft-geom = { path = "crates/geom", version = "0.8.0" } pdfcraft-filters = { path = "crates/filters", version = "0.8.0" } diff --git a/deny.toml b/deny.toml index 738a9f706..2362d5682 100644 --- a/deny.toml +++ b/deny.toml @@ -34,7 +34,7 @@ unknown-registry = "deny" unknown-git = "deny" # Shared UI components and spooler; Cargo.toml pins the immutable revision. craft-print pins # storytold's winprint fork (Windows printing, #1107) to an immutable revision of its own. -allow-git = ["https://github.com/storytold/craft-libs", "https://github.com/aiongg/craft-libs", "https://github.com/storytold/winprint.rs"] +allow-git = ["https://github.com/storytold/craft-libs", "https://github.com/storytold/winprint.rs"] [advisories] yanked = "warn" From cee48385b76631270f68ea1e928060cc378bf405 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Sat, 17 Oct 2026 12:57:57 -0600 Subject: [PATCH 06/34] deny: acknowledge the new zbus unmaintained advisories RUSTSEC-2026-0370/0371/0372 were published today for zvariant, zbus_names and zvariant_derive. All three are unmaintained notices rather than vulnerabilities, and none has a fixed release to move to. They reach the tree as the D-Bus stack behind accesskit_unix -> atspi (Linux accessibility) and as a dev-dependency of pdfcraft-platform, so nothing ships in the other targets' binaries. This is why main went red today; no dependency version changed. --- deny.toml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/deny.toml b/deny.toml index 2362d5682..ed9c26c20 100644 --- a/deny.toml +++ b/deny.toml @@ -48,6 +48,13 @@ ignore = [ # winprint's fmt-derive (craft-print's Windows spooler), so it runs at compile time on Windows # and is not in the binary. { id = "RUSTSEC-2024-0370", reason = "compile-time proc macro of winprint's fmt-derive (craft-print Windows printing, #1107)" }, + # zvariant, zbus_names and zvariant_derive are unmaintained (no vulnerability, and no fixed + # release to move to). They reach the tree as the D-Bus stack behind `accesskit_unix` -> + # `atspi`, which is Linux accessibility only, and as a dev-dependency of pdfcraft-platform. + # Revisit when the accesskit/zbus chain moves to a maintained successor. + { id = "RUSTSEC-2026-0370", reason = "zvariant unmaintained; Linux a11y stack via accesskit_unix" }, + { id = "RUSTSEC-2026-0371", reason = "zbus_names unmaintained; Linux a11y stack via accesskit_unix" }, + { id = "RUSTSEC-2026-0372", reason = "zvariant_derive unmaintained; Linux a11y stack via accesskit_unix" }, ] # egui's default UI fonts (Ubuntu-Light, Hack, emoji-icon-font): font licences on the AGENTS.md From 392406eb4ad488bddacb9eae12ad73b987e13a30 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Sat, 17 Oct 2026 21:50:58 +0200 Subject: [PATCH 07/34] fix(content): read a comment at the end of a content stream as the renderer does (#3081) Pieces::join separated a page's content streams with a newline, which ended a comment left open at the end of one stream. hayro, MuPDF and Poppler join them with a space, so the comment runs on into the next stream and hides its first line. Edit text, object_list, the redaction audit, redaction and the Office/HTML export therefore saw text and boxes that nothing draws, and redacting unrelated text on the page made the hidden content visible: the rewritten stream dropped the comment. - Pieces::join uses a space, so every reader of the joined streams agrees with rendering. - The parser records, per piece, whether a top-level comment runs into it and out of it (boundaries only, not every comment). A redaction rewrite of a piece ends an incoming comment before its first operator and leaves an outgoing one open, so hidden content stays hidden. - Reading for export parses the streams joined, instead of one by one. - The redaction tag check compares the joined streams the same way. - Pieces::piece_of uses a binary search. --- crates/audit/src/tests.rs | 19 +++++++ crates/content/src/lib.rs | 72 +++++++++++++++++++++++-- crates/content/src/tests.rs | 105 ++++++++++++++++++++++++++++++++++++ crates/edit/src/text.rs | 14 ++++- crates/redact/src/interp.rs | 16 +++++- crates/redact/src/lib.rs | 3 +- crates/redact/src/tests.rs | 39 ++++++++++++++ 7 files changed, 258 insertions(+), 10 deletions(-) diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs index ed36a8d5e..64ea05bde 100644 --- a/crates/audit/src/tests.rs +++ b/crates/audit/src/tests.rs @@ -500,3 +500,22 @@ fn forms_nested_past_depth_limit_fail_closed() { let result = audit_redactions(&open(nested_forms(33))); assert!(matches!(result, Err(crate::AuditError::TooDeep)), "{result:?}"); } + +#[test] +fn comment_across_streams_neither_invents_text_nor_a_cover() { + let doc = open(two_streams(b"BT /F1 24 Tf 72 700 Td (Visible text) Tj ET % note", b"0 g 70 690 200 40 re f")); + assert!(audit_redactions(&doc).unwrap().is_empty(), "commented cover must not be reported"); + let doc = open(two_streams(b"BT /F1 24 Tf 72 700 Td (Before comment) Tj ET % note", b"BT /F1 24 Tf 72 650 Td (After comment) Tj ET")); + let text: String = pdfcraft_edit::text_lines(&doc, 0).unwrap().into_iter().map(|line| line.text).collect(); + assert!(!text.contains("After comment"), "editor exposed phantom text: {text}"); +} + +#[test] +fn reading_blocks_respect_stream_comments_and_split_operands() { + let doc = open(two_streams(b"BT /F1 24 Tf 72 700 Td (Before comment) Tj ET % note", b"BT /F1 24 Tf 72 650 Td (After comment) Tj ET")); + let text: String = pdfcraft_edit::reading_blocks(&doc, 0).unwrap().into_iter().map(|block| block.editor_text).collect(); + assert_eq!(text, "Before comment"); + let doc = open(two_streams(b"BT /F1 24 Tf 72 700 Td (Split operand)", b"Tj ET")); + let text: String = pdfcraft_edit::reading_blocks(&doc, 0).unwrap().into_iter().map(|block| block.editor_text).collect(); + assert_eq!(text, "Split operand"); +} diff --git a/crates/content/src/lib.rs b/crates/content/src/lib.rs index 32334e047..c7c8bca9e 100644 --- a/crates/content/src/lib.rs +++ b/crates/content/src/lib.rs @@ -60,6 +60,10 @@ pub struct Parsed { pub ops: Vec, /// Bytes that could not be read as operands or operators. pub skipped: usize, + /// For [`Pieces::parse`]: per piece, whether a comment runs into it from the piece before + /// and whether one runs out of it into the next. Only boundaries are recorded, so the size + /// depends on the number of pieces, not of comments. + comment_edges: Vec<(bool, bool)>, } fn is_ws(b: u8) -> bool { @@ -72,12 +76,25 @@ fn is_delim(b: u8) -> bool { /// Parse a (decoded) content stream. pub fn parse(data: &[u8]) -> Parsed { - let mut out = Parsed::default(); + parse_pieces(data, &[]) +} + +/// Parse `data`, recording which of the piece boundaries `ends` (as in [`Pieces`]) a comment +/// crosses. +fn parse_pieces(data: &[u8], ends: &[usize]) -> Parsed { + let mut out = Parsed { comment_edges: vec![(false, false); ends.len()], ..Parsed::default() }; + let mut boundary = 0; let mut lx = Lexer::new(data, 0); let mut operands: Vec = Vec::new(); let mut start: Option = None; loop { + let trivia = lx.pos; lx.skip_ws(); + // Only the whitespace the lexer skips here holds top-level comments: a `%` inside a + // string, a name, an array or dictionary operand or inline image data is not one. + if boundary < ends.len() { + comment_edges(data, trivia..lx.pos, ends, &mut boundary, &mut out.comment_edges); + } let Some(&b) = data.get(lx.pos) else { break }; let at = lx.pos; let operand_start = matches!(b, b'/' | b'(' | b'<' | b'[' | b'+' | b'-' | b'.') || b.is_ascii_digit(); @@ -148,6 +165,39 @@ pub fn parse(data: &[u8]) -> Parsed { out } +/// Record the piece boundaries crossed by the comments in `trivia` (skipped whitespace and +/// comments). `boundary` is the first boundary not yet passed; boundaries only move forward. +fn comment_edges(data: &[u8], trivia: std::ops::Range, ends: &[usize], boundary: &mut usize, edges: &mut [(bool, bool)]) { + let mut at = trivia.start; + while at < trivia.end { + if data.get(at) != Some(&b'%') { + at += 1; + continue; + } + let comment = at; + while at < trivia.end && !matches!(data.get(at), Some(b'\r' | b'\n')) { + at += 1; + } + // The separator of piece `boundary` is the last byte before its end. + while let Some(&end) = ends.get(*boundary) { + let separator = end.saturating_sub(1); + if separator >= at { + break; + } + if separator >= comment { + if let Some(edge) = edges.get_mut(*boundary) { + edge.1 = true; + } + // Includes a comment whose end of line is the next piece's first byte. + if let Some(edge) = edges.get_mut(boundary.saturating_add(1)) { + edge.0 = true; + } + } + *boundary += 1; + } + } +} + /// Read an inline image starting after `BI`: (parameters, data, position after `EI`). `Err` holds /// the position after the `EI` (or the end of the stream) of an image whose parameters can't be read. fn inline_image(data: &[u8], pos: usize) -> Result<(Dict, Vec, usize), usize> { @@ -305,7 +355,9 @@ pub fn serialize_ops(ops: &[Op]) -> Vec { /// A page's content streams joined into the one stream they are. Writers may split it between /// any two tokens (ISO 32000-2 §7.8.2), so an operator's operands can end one piece and its /// keyword start the next: parse the pieces joined ([`Pieces::parse`]) and map positions back -/// with [`Pieces::piece_of`]. A newline separates the pieces so tokens never run together. +/// with [`Pieces::piece_of`]. A space separates the pieces, as renderers join them (hayro, +/// MuPDF and Poppler alike): tokens never run together, and a comment at the end of a piece +/// runs on into the next one, up to its first end of line. #[derive(Clone, Debug, Default, PartialEq)] pub struct Pieces { data: Vec, @@ -319,7 +371,7 @@ impl Pieces { let mut ends = Vec::with_capacity(pieces.len()); for p in pieces { data.extend_from_slice(p.as_ref()); - data.push(b'\n'); + data.push(b' '); ends.push(data.len()); } Pieces { data, ends } @@ -341,12 +393,22 @@ impl Pieces { /// Parse the pieces as one stream. pub fn parse(&self) -> Parsed { - parse(&self.data) + parse_pieces(&self.data, &self.ends) + } + + /// Per piece, from `parsed` (this piece set's [`Pieces::parse`]): whether a comment runs + /// into it from the piece before, and whether one runs out of it into the next. A writer + /// that rewrites a piece without its comments must keep both: end the incoming comment + /// before its first operator, and leave a comment open at its end. + pub fn comment_edges(&self, parsed: &Parsed) -> Vec<(bool, bool)> { + let mut edges = parsed.comment_edges.clone(); + edges.resize(self.len(), (false, false)); + edges } /// The piece holding joined position `at` (the last piece for positions past the end). pub fn piece_of(&self, at: usize) -> usize { - self.ends.iter().position(|&e| at < e).unwrap_or(self.ends.len().saturating_sub(1)) + self.ends.partition_point(|&e| e <= at).min(self.ends.len().saturating_sub(1)) } /// The pieces an operator spans: (the one its first token is in, the one its keyword is in). diff --git a/crates/content/src/tests.rs b/crates/content/src/tests.rs index 18e0b8cbc..1119bdaf9 100644 --- a/crates/content/src/tests.rs +++ b/crates/content/src/tests.rs @@ -283,3 +283,108 @@ fn pieces_parse_as_one_stream_and_splice_back() { assert_eq!(out.len(), 3); assert!(Pieces::join::<&[u8]>(&[]).splice([(0..1, b"x".to_vec())]).is_empty()); } + +#[test] +fn stream_boundary_comment_matches_space_concatenation() { + for eol in [b"\n".as_slice(), b"\r", b"\r\n"] { + let mut tail = b"(HIDDEN) Tj".to_vec(); + tail.extend(eol); + tail.extend(b"(LIVE) Tj"); + let pieces = Pieces::join(&[b"BT % comment".as_slice(), b"(ALSO HIDDEN) Tj", &tail, b"ET"]); + let parsed = pieces.parse(); + let shown: Vec<_> = parsed.ops.iter().filter(|op| op.is("Tj")).collect(); + assert_eq!(shown.len(), 1); + assert_eq!(shown[0].operands[0].as_string().unwrap().bytes, b"LIVE"); + } +} + +#[test] +fn comment_edges_terminate_at_next_piece_byte_zero() { + for eol in [b"\n".as_slice(), b"\r", b"\r\n"] { + let mut next = eol.to_vec(); + next.extend_from_slice(b"q Q"); + let pieces = Pieces::join(&[b"% outgoing".as_slice(), next.as_slice()]); + let parsed = pieces.parse(); + assert_eq!(pieces.comment_edges(&parsed), vec![(false, true), (true, false)], "EOL {eol:?}"); + assert_eq!(parsed.ops.iter().map(|op| op.op.as_slice()).collect::>(), vec![b"q".as_slice(), b"Q"]); + } +} + +#[test] +fn comment_edges_span_empty_pieces_and_end_of_content() { + let pieces = Pieces::join(&[b"q % outgoing".as_slice(), b"", b"", b"ignored\nQ"]); + let parsed = pieces.parse(); + assert_eq!(pieces.comment_edges(&parsed), vec![(false, true), (true, true), (true, true), (true, false)]); + assert_eq!(parsed.ops.iter().map(|op| op.op.as_slice()).collect::>(), vec![b"q".as_slice(), b"Q"]); + + let pieces = Pieces::join(&[b"% outgoing".as_slice(), b"", b"still ignored"]); + let parsed = pieces.parse(); + assert_eq!(pieces.comment_edges(&parsed), vec![(false, true), (true, true), (true, true)]); + assert!(parsed.ops.is_empty()); + + let pieces = Pieces::join::<&[u8]>(&[]); + assert!(pieces.comment_edges(&pieces.parse()).is_empty()); +} + +#[test] +fn comment_edges_ignore_percent_inside_operands_and_image_data() { + for first in [ + b"(literal % not a comment) Tj".as_slice(), + b"/Percent#25Name MP", + b"[(literal % not a comment)] TJ", + b"/P << /ActualText (literal % not a comment) >> BDC EMC", + b"BI /W 1 /H 1 /BPC 8 /CS /G ID % EI", + ] { + let pieces = Pieces::join(&[first, b"q Q"]); + let parsed = pieces.parse(); + assert_eq!(pieces.comment_edges(&parsed), vec![(false, false), (false, false)], "{first:?}"); + assert_eq!(parsed.ops.last().unwrap().op, b"Q"); + assert_eq!(parsed.skipped, 0); + } +} + +#[test] +fn compound_operand_comment_split_is_owned_by_spanning_operator() { + for parts in [[b"[(A) % ignored".as_slice(), b"still ignored\n(B)] TJ"], [b"/P << /MCID 0 % ignored".as_slice(), b"still ignored\n>> BDC"]] { + let pieces = Pieces::join(&parts); + let parsed = pieces.parse(); + // The object lexer consumes this nested comment. Its containing operator spans + // both pieces, which forces both to be rewritten together by the redactor. + assert_eq!(pieces.comment_edges(&parsed), vec![(false, false), (false, false)]); + assert_eq!(parsed.ops.len(), 1); + assert_eq!(pieces.pieces_of(&parsed.ops[0]), (0, 1)); + assert_eq!(parsed.skipped, 0); + } +} + +#[test] +fn comment_edges_do_not_confuse_local_comments_with_boundary_comments() { + let pieces = Pieces::join(&[b"% local\nq % crossing".as_slice(), b"ignored\n% local again\nQ\n% final local\n", b"q Q"]); + let parsed = pieces.parse(); + assert_eq!(pieces.comment_edges(&parsed), vec![(false, true), (true, false), (false, false)]); + assert_eq!(parsed.ops.iter().map(|op| op.op.as_slice()).collect::>(), vec![b"q".as_slice(), b"Q", b"q", b"Q"]); +} + +#[test] +fn comment_edge_storage_depends_on_piece_count_not_comment_count() { + let mut first = b"%\n".repeat(16_384); + first.extend_from_slice(b"q % crossing"); + let pieces = Pieces::join(&[first.as_slice(), b"ignored\nQ"]); + let parsed = pieces.parse(); + assert_eq!(pieces.comment_edges(&parsed), vec![(false, true), (true, false)]); + assert_eq!(parsed.ops.len(), 2); + // Also exercise public parsing without piece-boundary metadata. + assert_eq!(parse(&first).ops.len(), 1); +} + +#[test] +fn piece_lookup_preserves_exact_boundary_and_empty_piece_mapping() { + // Joined layout: qQ; separator belongs to prior piece. + let pieces = Pieces::join(&[b"q".as_slice(), b"", b"Q"]); + for (at, expected) in [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2), (5, 2), (usize::MAX, 2)] { + assert_eq!(pieces.piece_of(at), expected, "position {at}"); + } + let empty = Pieces::join::<&[u8]>(&[]); + assert_eq!(empty.piece_of(0), 0); + assert_eq!(empty.piece_of(usize::MAX), 0); +} diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs index 9c83cf9a3..93d1b54fc 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -1276,8 +1276,18 @@ fn reading_lines(doc: &Document, page: usize) -> Result, EditError let streams = content_streams(doc, &p.dict); let mut w = Walk { doc, lines: Vec::new(), next_stream: streams.len(), path: Vec::new(), visits: 0 }; let mut carry = Carry::new(); - for (si, (_, data)) in streams.into_iter().enumerate() { - walk(&mut w, &parse(&data).ops, &res, &mut carry, si); + // Read the page's streams as the one stream they are, as rendering and editing do: a + // comment or an operator's operands can run on from one stream into the next. Each operator + // still counts as its first stream's, which keeps lines from different streams apart. + let pieces = Pieces::join(&streams.into_iter().map(|(_, data)| data).collect::>()); + let mut grouped: Vec> = (0..pieces.len()).map(|_| Vec::new()).collect(); + for op in pieces.parse().ops { + if let Some(group) = grouped.get_mut(pieces.pieces_of(&op).0) { + group.push(op); + } + } + for (si, ops) in grouped.iter().enumerate() { + walk(&mut w, ops, &res, &mut carry, si); } let mut lines = w.lines; // A visual-order Indic font draws pre-base vowel signs before their consonant. diff --git a/crates/redact/src/interp.rs b/crates/redact/src/interp.rs index c76e11995..50802eff3 100644 --- a/crates/redact/src/interp.rs +++ b/crates/redact/src/interp.rs @@ -380,6 +380,9 @@ pub(crate) fn process(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec< // next. Parse them joined, then give each operator back to the piece its keyword is in. let joined = Pieces::join(streams); let mut parsed = joined.parse(); + // A rewritten piece loses its comments, so keep where they began and ended: a comment that + // ran on into the next piece still hides that piece's first line. + let comment_edges = joined.comment_edges(&parsed); if !scope.hidden_layers.is_empty() { let props = res_dict(doc, resources, b"Properties"); let (kept, removed) = strip_hidden_layers(doc, scope, parsed.ops, &props); @@ -405,7 +408,7 @@ pub(crate) fn process(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec< } } - for (piece, mut changed) in pieces.into_iter().zip(rewrite) { + for ((piece, mut changed), (comment_in, comment_out)) in pieces.into_iter().zip(rewrite).zip(comment_edges) { let mut ops: Vec = Vec::with_capacity(piece.len()); for op in piece { let o = op.op.as_slice(); @@ -622,7 +625,16 @@ pub(crate) fn process(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec< if !path.is_empty() { ops.append(&mut path); } - out.streams.push(changed.then(|| serialize_ops(&ops))); + out.streams.push(changed.then(|| { + // The piece before still ends inside a comment: end it before the first operator. + let mut bytes = if comment_in { b"\n".to_vec() } else { Vec::new() }; + bytes.extend(serialize_ops(&ops)); + // The piece ended inside a comment that hid the start of the next one: keep it open. + if comment_out { + bytes.push(b'%'); + } + bytes + })); } out } diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs index 61231bd98..21af3691c 100644 --- a/crates/redact/src/lib.rs +++ b/crates/redact/src/lib.rs @@ -400,7 +400,8 @@ pub fn apply(doc: &mut Document, pages: Option<&[usize]>) -> Result