mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-05 19:51:56 -05:00
Merge storytold/pdfcraft main into feat/lock-signatures-prompt
Conflicts: - crates/ui-egui/src/workflows/js_ui.rs: main moved the Preferences dialog to crates/ui-egui/src/dialogs/preferences.rs (cards with search). Took main's re-export and carried this branch's "Otherwise, ask on the first save after a signature is placed" checkbox into card_fill_and_sign, disabled while flattening is on as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv
This commit is contained in:
@@ -219,6 +219,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-11-01 (M7, #5657):** Header/footer, watermark and background additions and replacements stage the complete call before committing. Synthetic later-page failures preserve exact incremental bytes, object count, dirty state and allocation cursor; success controls retain other marks and shared/inherited resources. Estimates unchanged.
|
||||
|
||||
- **2026-11-01 (M14, #5572):** Preferences ▸ Documents and view sets how many recent files to keep, from 0 to 50 with 12 by default. At 0 Home has no Recent section and File ▸ Open Recent is disabled. The list is cut when Preferences closes, so the number can pass through 0 on its way to another.
|
||||
|
||||
- **2026-11-01 (M5/M14, customizable hotbar, freehand highlight, and moveable navigation rail):** Added Freehand-Highlight (`/Subtype /Ink`, `/IT /FreehandHighlight`, Multiply blending, 100 pt max line width) inside the standard Highlight flyout and headless `comment_add`; added a customizable floating or side-docked hotbar with a full-side chrome strip mode, settings gear icon anchored at the bar end, and 24–64 px sizing; and added Left/Right docking for the navigation rail (`rail_side`). Focused unit and integration tests pass across `annot`, `automation`, and `ui-egui`. Estimates unchanged.
|
||||
@@ -743,6 +745,7 @@ Newest first: the date, what moved, and the new overall estimate.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
|
||||
| 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. |
|
||||
| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. |
|
||||
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
|
||||
|
||||
@@ -180,3 +180,6 @@ sync_github_name = true
|
||||
|
||||
[people.dylanmtaylor]
|
||||
sync_github_name = true
|
||||
|
||||
[people.Combiler01]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -730,11 +730,14 @@ impl Matrix {
|
||||
pub fn invert(&self) -> Option<Matrix> {
|
||||
let [a, b, c, d, e, f] = self.0;
|
||||
let det = a * d - b * c;
|
||||
if det.abs() < 1e-12 || !det.is_finite() {
|
||||
if det == 0.0 || !det.is_finite() || det.abs() <= 1e-12 * ((a * d).abs() + (b * c).abs()) {
|
||||
return None;
|
||||
}
|
||||
let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
|
||||
Some(Matrix([ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)]))
|
||||
let inverse = [ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)];
|
||||
// A determinant that underflows toward zero can still pass the relative check above,
|
||||
// and dividing by it overflows: such a matrix has no usable inverse.
|
||||
inverse.iter().all(|v| v.is_finite()).then_some(Matrix(inverse))
|
||||
}
|
||||
|
||||
/// The bounding box of a rectangle `[x0 y0 x1 y1]` after this transform.
|
||||
|
||||
@@ -552,3 +552,17 @@ fn inline_images_end_where_the_renderer_ends_them() {
|
||||
assert_eq!((parsed.skipped, parsed.ambiguous_images), (0, 0), "{}", String::from_utf8_lossy(data));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invert_accepts_small_scale_and_rejects_singular() {
|
||||
let m = Matrix([1e-7, 0., 0., 1e-7, 0., 0.]);
|
||||
let inv = m.invert().expect("a uniform 1e-7 scale is invertible");
|
||||
let id = m.then(&inv).0;
|
||||
for (got, want) in id.iter().zip(Matrix::IDENTITY.0) {
|
||||
assert!((got - want).abs() < 1e-9, "{id:?}");
|
||||
}
|
||||
assert!(Matrix([1., 2., 2., 4., 0., 0.]).invert().is_none());
|
||||
assert!(Matrix([f64::NAN, 0., 0., 1., 0., 0.]).invert().is_none());
|
||||
// A subnormal scale passes the relative check but its inverse overflows (CodeRabbit on #5703).
|
||||
assert!(Matrix([1e-310, 0., 0., 1., 0., 0.]).invert().is_none());
|
||||
}
|
||||
|
||||
@@ -7,9 +7,25 @@ use super::place::{
|
||||
};
|
||||
use super::{Document, EditError, Object, added, backdrop, helvetica_width};
|
||||
|
||||
/// Commit one complete mark operation only after every selected page succeeds. The snapshot
|
||||
/// shares original bytes, cross-references, caches and unchanged objects; only the overlay table
|
||||
/// and document metadata are copied. Dropping a failed stage also drops removed marks, changed
|
||||
/// page/resources/backdrop dictionaries and new objects, including the allocation cursor.
|
||||
fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document) -> Result<(), EditError>) -> Result<(), EditError> {
|
||||
let mut staged = doc.clone();
|
||||
apply(&mut staged)?;
|
||||
*doc = staged;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on
|
||||
/// those pages are removed first (Acrobat's Replace Existing).
|
||||
/// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic:
|
||||
/// on error, the document (including earlier selected pages) is unchanged.
|
||||
pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
|
||||
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx))
|
||||
}
|
||||
|
||||
fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
|
||||
let all = page_list(doc);
|
||||
check(pages, all.len())?;
|
||||
if hf.text.iter().all(|t| t.trim().is_empty()) {
|
||||
@@ -121,8 +137,13 @@ pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter,
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a text watermark to `pages`.
|
||||
/// Add a text or picture watermark to `pages`. All selected pages, including mark replacement,
|
||||
/// form one transaction; on error, the document is unchanged.
|
||||
pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
|
||||
apply_mark_transaction(doc, |staged| add_watermark_in_place(staged, pages, wm, replace))
|
||||
}
|
||||
|
||||
fn add_watermark_in_place(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
|
||||
let all = page_list(doc);
|
||||
check(pages, all.len())?;
|
||||
let text = wm.text.trim();
|
||||
@@ -201,8 +222,13 @@ pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replac
|
||||
|
||||
/// Add a solid-colour background behind the content of `pages`. With `bg.replace_backdrop`, a
|
||||
/// white backdrop a page paints itself is replaced first, so the background shows (see
|
||||
/// [`backdrop`]); a picture backdrop (a scan) still hides it.
|
||||
/// [`backdrop`]); a picture backdrop (a scan) still hides it. All selected pages, including
|
||||
/// replacement and backdrop edits, form one transaction; on error, the document is unchanged.
|
||||
pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
|
||||
apply_mark_transaction(doc, |staged| add_background_in_place(staged, pages, bg, replace))
|
||||
}
|
||||
|
||||
fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
|
||||
let all = page_list(doc);
|
||||
check(pages, all.len())?;
|
||||
if replace {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
//! pdfcraft-edit — page content editing (L4). Today: page marks, Acrobat's Header & footer,
|
||||
//! Watermark, Background and Bates numbering (execution plan M7.6).
|
||||
//!
|
||||
//! **Atomic page-mark operations.** Adding or replacing headers/footers, watermarks and backgrounds
|
||||
//! stages the whole call on a document snapshot and commits only after every selected page succeeds.
|
||||
//! An error preserves existing marks, content, resources, pending edits and allocated objects. The
|
||||
//! snapshot shares original PDF bytes and unchanged objects; it copies the overlay table and metadata.
|
||||
//!
|
||||
//! **How marks are stored.** Each mark is one content stream appended to (or, for content behind
|
||||
//! the page, inserted after the backgrounds at the start of) the page's `/Contents`, drawn in
|
||||
//! display space (after `/Rotate`) and wrapped in a marked-content artifact (§14.8.2.2) so
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! The public mark APIs either commit the complete operation or leave the document untouched.
|
||||
use super::{cx, fixture, reopen, streams};
|
||||
use crate::place::MARK_PLACEMENT_FAILURE;
|
||||
use crate::*;
|
||||
use pdfcraft_cos::{ObjRef, SaveOptions, write_incremental};
|
||||
|
||||
const SELECTED: &[usize] = &[0, 1, 2];
|
||||
|
||||
struct PlacementFailure;
|
||||
|
||||
impl PlacementFailure {
|
||||
fn after_two_pages(kind: MarkKind) -> Self {
|
||||
MARK_PLACEMENT_FAILURE.with(|failure| {
|
||||
assert!(failure.get().is_none());
|
||||
failure.set(Some((kind, 2, 0)));
|
||||
});
|
||||
Self
|
||||
}
|
||||
|
||||
fn completed(&self) -> usize {
|
||||
MARK_PLACEMENT_FAILURE.with(|failure| failure.get().unwrap().2)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PlacementFailure {
|
||||
fn drop(&mut self) {
|
||||
MARK_PLACEMENT_FAILURE.with(|failure| failure.set(None));
|
||||
}
|
||||
}
|
||||
|
||||
/// Four pages share an original stream and resources, both inherited and directly referenced.
|
||||
/// All have all three existing marks, including a picture background with a replaced white fill.
|
||||
fn marked_document() -> (Document, MarkSource) {
|
||||
let mut doc = fixture();
|
||||
let parent = ObjRef::new(2, 0);
|
||||
let extra = doc.add(Object::Dict(Dict::from_iter([
|
||||
(b"Type".to_vec(), Object::name("Page")),
|
||||
(b"Parent".to_vec(), Object::Ref(parent)),
|
||||
(b"Contents".to_vec(), Object::Ref(ObjRef::new(7, 0))),
|
||||
])));
|
||||
doc.update_dict(parent, |d| {
|
||||
d.set(b"Kids".to_vec(), Object::Array([3, 4, 5].map(|n| Object::Ref(ObjRef::new(n, 0))).into_iter().chain([Object::Ref(extra)]).collect()));
|
||||
d.set(b"Count".to_vec(), Object::Int(4));
|
||||
})
|
||||
.unwrap();
|
||||
doc.set(ObjRef::new(7, 0), Object::Stream(Stream::from_raw(Dict::new(), b"1 g 0 0 600 800 re f 0 g BT /F1 9 Tf (Original page) Tj ET".to_vec())));
|
||||
let picture = |doc: &mut Document, gray| {
|
||||
let image = doc.add(Object::Stream(Stream::from_raw(
|
||||
Dict::from_iter([
|
||||
(b"Type".to_vec(), Object::name("XObject")),
|
||||
(b"Subtype".to_vec(), Object::name("Image")),
|
||||
(b"Width".to_vec(), Object::Int(1)),
|
||||
(b"Height".to_vec(), Object::Int(1)),
|
||||
(b"ColorSpace".to_vec(), Object::name("DeviceGray")),
|
||||
(b"BitsPerComponent".to_vec(), Object::Int(8)),
|
||||
]),
|
||||
vec![gray],
|
||||
)));
|
||||
MarkSource { xobject: image, size: (1.0, 1.0), image: true }
|
||||
};
|
||||
let old_picture = picture(&mut doc, 170);
|
||||
let replacement_picture = picture(&mut doc, 80);
|
||||
let all = [0, 1, 2, 3];
|
||||
let hf = HeaderFooter {
|
||||
text: ["Old header".into(), String::new(), String::new(), String::new(), String::new(), String::new()],
|
||||
font: added::Family::Times,
|
||||
..Default::default()
|
||||
};
|
||||
add_header_footer(&mut doc, &all, &hf, false, &cx()).unwrap();
|
||||
add_watermark(&mut doc, &all, &Watermark { text: "Old watermark".into(), opacity: 0.45, ..Default::default() }, false).unwrap();
|
||||
add_background(&mut doc, &all, &Background { source: Some(old_picture), opacity: 0.6, replace_backdrop: true, ..Default::default() }, false)
|
||||
.unwrap();
|
||||
let pages = page_list(&doc);
|
||||
let shared = ObjRef::new(6, 0);
|
||||
let resources = (*doc.resolve(pages[0].dict.get(b"Resources").unwrap())).clone();
|
||||
doc.set(shared, resources);
|
||||
for (i, page) in pages.iter().enumerate() {
|
||||
doc.update_dict(page.obj, |d| {
|
||||
if i % 2 == 0 {
|
||||
d.set(b"Resources".to_vec(), Object::Ref(shared));
|
||||
} else {
|
||||
d.remove(b"Resources");
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let doc = reopen(&doc);
|
||||
assert!(!doc.is_modified());
|
||||
let pages = page_list(&doc);
|
||||
assert_eq!(pages.len(), 4);
|
||||
assert!(doc.get(pages[1].obj).as_dict().unwrap().get(b"Resources").is_none(), "a selected page inherits its resources");
|
||||
assert_eq!(pages[0].dict.get(b"Resources").and_then(Object::as_ref), Some(shared));
|
||||
assert_eq!(pages[2].dict.get(b"Resources").and_then(Object::as_ref), Some(shared));
|
||||
for i in 0..4 {
|
||||
for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
|
||||
assert_eq!(mark_streams(&doc, i, kind).len(), 1, "page {i} has existing {kind:?}");
|
||||
}
|
||||
}
|
||||
(doc, replacement_picture)
|
||||
}
|
||||
|
||||
fn mark_streams(doc: &Document, page: usize, kind: MarkKind) -> Vec<String> {
|
||||
streams(doc, page).into_iter().filter(|s| s.contains(&format!("/PCMark /{}", kind.tag()))).collect()
|
||||
}
|
||||
|
||||
fn apply_replacement(doc: &mut Document, kind: MarkKind, source: MarkSource, replace: bool) -> Result<(), EditError> {
|
||||
match kind {
|
||||
MarkKind::HeaderFooter => add_header_footer(
|
||||
doc,
|
||||
SELECTED,
|
||||
&HeaderFooter {
|
||||
text: ["New header".into(), String::new(), String::new(), String::new(), String::new(), String::new()],
|
||||
font: added::Family::Courier,
|
||||
shrink: true,
|
||||
..Default::default()
|
||||
},
|
||||
replace,
|
||||
&cx(),
|
||||
),
|
||||
MarkKind::Watermark => add_watermark(doc, SELECTED, &Watermark { source: Some(source), opacity: 0.25, ..Default::default() }, replace),
|
||||
MarkKind::Background => {
|
||||
add_background(doc, SELECTED, &Background { color: [0.1, 0.3, 0.7], replace_backdrop: true, ..Default::default() }, replace)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unchanged_after_later_page_failure(kind: MarkKind) {
|
||||
// Replacement and addition share the same operation boundary; exercise replacement first.
|
||||
for (replace, pending_edit) in [(true, false), (true, true), (false, false), (false, true)] {
|
||||
let (mut doc, source) = marked_document();
|
||||
if pending_edit {
|
||||
let pending = doc.add(Object::String(pdfcraft_cos::PdfString::literal(b"unsaved caller edit".to_vec())));
|
||||
doc.update_dict(page_list(&doc)[0].obj, |d| d.set(b"CallerEdit".to_vec(), Object::Ref(pending))).unwrap();
|
||||
}
|
||||
let modified = doc.is_modified();
|
||||
let before = write_incremental(&doc, &SaveOptions::default()).unwrap();
|
||||
let objects = doc.object_numbers().len();
|
||||
let mut allocation_probe = doc.clone();
|
||||
let next_object = allocation_probe.add(Object::Null);
|
||||
let failure = PlacementFailure::after_two_pages(kind);
|
||||
let result = apply_replacement(&mut doc, kind, source, replace);
|
||||
assert_eq!(result, Err(EditError::Invalid("injected mark placement failure".into())));
|
||||
assert_eq!(failure.completed(), 2, "the error followed two real page placements");
|
||||
assert_eq!(doc.object_numbers().len(), objects, "{kind:?}, replace={replace}: no allocated objects remain");
|
||||
assert_eq!(doc.is_modified(), modified, "{kind:?}, replace={replace}: the dirty state is preserved");
|
||||
assert!(write_incremental(&doc, &SaveOptions::default()).unwrap() == before, "{kind:?}, replace={replace}: every byte stays unchanged");
|
||||
assert_eq!(doc.add(Object::Null), next_object, "the allocation cursor is unchanged too");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_footer_changes_are_atomic_after_a_later_page_failure() {
|
||||
unchanged_after_later_page_failure(MarkKind::HeaderFooter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watermark_changes_are_atomic_after_a_later_page_failure() {
|
||||
unchanged_after_later_page_failure(MarkKind::Watermark);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_changes_are_atomic_after_a_later_page_failure() {
|
||||
unchanged_after_later_page_failure(MarkKind::Background);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources() {
|
||||
for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
|
||||
let (mut doc, source) = marked_document();
|
||||
let before = doc.clone();
|
||||
let expected = match kind {
|
||||
MarkKind::HeaderFooter => "(New header)".to_string(),
|
||||
MarkKind::Watermark => format!("/PCPic{} Do", source.xobject.num),
|
||||
MarkKind::Background => "0.1 0.3 0.7 rg".to_string(),
|
||||
};
|
||||
apply_replacement(&mut doc, kind, source, true).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
assert_eq!(streams(&doc, 3), streams(&before, 3), "the unselected page keeps its content");
|
||||
let unselected = page_list(&before)[3].obj;
|
||||
assert_eq!(doc.get(unselected), before.get(unselected), "the unselected page keeps its resources and entries");
|
||||
for reference in [ObjRef::new(6, 0), ObjRef::new(7, 0)] {
|
||||
assert_eq!(
|
||||
format!("{:?}", doc.get(reference)),
|
||||
format!("{:?}", before.get(reference)),
|
||||
"shared resources and original content stay unchanged"
|
||||
);
|
||||
}
|
||||
for page in SELECTED {
|
||||
let marks = mark_streams(&doc, *page, kind);
|
||||
assert_eq!(marks.len(), 1, "one replacement on selected page {page}");
|
||||
assert!(marks[0].contains(&expected), "the new mark is present: {}", marks[0]);
|
||||
let old_page = &page_list(&before)[*page];
|
||||
let new_page = &page_list(&doc)[*page];
|
||||
let old_resources = before.resolve(old_page.dict.get(b"Resources").unwrap());
|
||||
let new_resources = doc.resolve(new_page.dict.get(b"Resources").unwrap());
|
||||
for category in [&b"Font"[..], &b"ExtGState"[..], &b"XObject"[..]] {
|
||||
let old = before.resolve(old_resources.as_dict().unwrap().get(category).unwrap());
|
||||
let new = doc.resolve(new_resources.as_dict().unwrap().get(category).unwrap());
|
||||
for (name, value) in old.as_dict().unwrap().iter() {
|
||||
assert_eq!(new.as_dict().unwrap().get(name), Some(value), "old resources remain usable on page {page}");
|
||||
assert_eq!(doc.resolve(value), before.resolve(value), "referenced resource contents are unchanged on page {page}");
|
||||
}
|
||||
}
|
||||
for other in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
|
||||
if other != kind {
|
||||
assert_eq!(mark_streams(&doc, *page, other), mark_streams(&before, *page, other), "unrelated {other:?} on page {page}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -294,7 +294,32 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation {
|
||||
/// Put a mark's content on a page: behind (with the behind-marks at the start) or on top
|
||||
/// (appended, after wrapping the original content in q/Q).
|
||||
pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
|
||||
place_tagged(doc, page, kind.tag(), content, behind).map(drop)
|
||||
place_tagged(doc, page, kind.tag(), content, behind)?;
|
||||
#[cfg(test)]
|
||||
fail_after_mark_placement(kind)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Force an error after N completed placements of one kind, on this test thread only.
|
||||
pub(crate) static MARK_PLACEMENT_FAILURE: std::cell::Cell<Option<(MarkKind, usize, usize)>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn fail_after_mark_placement(kind: MarkKind) -> Result<(), EditError> {
|
||||
MARK_PLACEMENT_FAILURE.with(|failure| {
|
||||
if let Some((target, after, completed)) = failure.get()
|
||||
&& target == kind
|
||||
{
|
||||
let completed = completed.saturating_add(1);
|
||||
failure.set(Some((target, after, completed)));
|
||||
if completed == after {
|
||||
return Err(EditError::Invalid("injected mark placement failure".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Put content on a page, tagged `tag` (see [`place`]). On top, whatever graphics state the
|
||||
|
||||
@@ -4,6 +4,9 @@ use pdfcraft_cos::{Document, SaveOptions, write_full, write_incremental};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[path = "mark_transaction_tests.rs"]
|
||||
mod mark_transactions;
|
||||
|
||||
/// Three pages: an upright page with content that leaves the graphics state changed (an
|
||||
/// unbalanced `cm`), a page rotated 90° and one with inherited, shared resources.
|
||||
fn fixture() -> Document {
|
||||
|
||||
@@ -8491,6 +8491,99 @@ mod devicen_inks;
|
||||
// patch 27).
|
||||
mod isolated_cmyk_groups;
|
||||
|
||||
/// The generation-0 stand-in a rebuilt table files an object under must not make the object a
|
||||
/// second object: enumeration yielded it once per key, so a document recovered without a readable
|
||||
/// page tree reported the page twice (noted in review of #5580).
|
||||
///
|
||||
/// And a later header for the same object number replaces the stand-in, so `N 0 R` cannot be left
|
||||
/// pointing at a body the exact key no longer names.
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
fn a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object() {
|
||||
// No table, no `startxref`, and no readable page tree: the pages are recovered by looking for
|
||||
// objects that are pages, which is where a doubled object shows up as a doubled page.
|
||||
let pdf = "%PDF-1.4\n\
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
3 99999 obj << /Type /Page /MediaBox [0 0 200 100] /Contents 4 0 R >> endobj\n\
|
||||
4 0 obj << /Length 0 >> stream\n\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n\
|
||||
%%EOF\n";
|
||||
let mut r = PageRenderer::new(Arc::new(pdf.to_string().into_bytes()), RenderConfig::default());
|
||||
let first = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
|
||||
assert!(first.error.is_none(), "the page is recovered: {:?}", first.error);
|
||||
let second = r.render(RenderRequest { page: 1, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
|
||||
assert!(second.error.is_some(), "and it is one page, not two: page 2 must not exist");
|
||||
|
||||
// Two headers for object 3, the second the one the exact key names: the stand-in follows it.
|
||||
// `(B)` is drawn by the later body, so the page that comes back says which one was read.
|
||||
let twice = "%PDF-1.4\n\
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 1 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 5 0 R >> endobj\n\
|
||||
3 1 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 150] /Contents 5 0 R >> endobj\n\
|
||||
5 0 obj << /Length 0 >> stream\n\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n\
|
||||
%%EOF\n";
|
||||
let mut r = PageRenderer::new(Arc::new(twice.to_string().into_bytes()), RenderConfig::default());
|
||||
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
|
||||
assert!(page.error.is_none(), "the page is found: {:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (300, 150), "`3 0 R` reads the later body, as `3 1` does");
|
||||
}
|
||||
|
||||
/// A file whose cross-reference table has to be rebuilt keeps an object whose header names a
|
||||
/// generation the reference does not.
|
||||
///
|
||||
/// `poppler-85140-0.pdf` is 340 bytes with no table at all, and its one page's header reads
|
||||
/// `3 18446744073709551616 obj` while the page tree points at `3 0 R`. Before #427 the digits
|
||||
/// wrapped, and 2^64 wrapped to exactly 0, so the header read as `3 0 obj` and the file opened by
|
||||
/// accident; once an overflowing integer became a real the object was unreachable and the file
|
||||
/// stopped opening at all, which `cargo xtask check` reports as a regression (#5580).
|
||||
///
|
||||
/// A rebuilt table has no revision history to tell two generations of an object apart -- the scan
|
||||
/// already files objects found in object streams under generation 0 -- so the object number is
|
||||
/// what identifies one. A readable generation that simply is not the one referenced
|
||||
/// (`3 99999 obj`) was lost the same way, and is covered here too.
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
||||
#[cfg_attr(not(target_arch = "wasm32"), test)]
|
||||
fn a_rebuilt_table_finds_an_object_whose_header_names_another_generation() {
|
||||
for generation in [
|
||||
// The generation the reference names, which always worked.
|
||||
"0",
|
||||
// One that reads as an integer but is not the one referenced.
|
||||
"99999",
|
||||
// And one no generation may be: 2^64, which is what the reported file carries. A
|
||||
// generation number is at most 65,535 (ISO 32000-2 §7.5.4).
|
||||
"18446744073709551616",
|
||||
] {
|
||||
// No table and no `startxref`, so the objects are recovered by scanning the file.
|
||||
let pdf = format!(
|
||||
"%PDF-1.4\n\
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 {generation} obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >> endobj\n\
|
||||
trailer << /Root 1 0 R >>\n\
|
||||
%%EOF\n"
|
||||
);
|
||||
let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
|
||||
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
|
||||
assert!(page.error.is_none(), "generation {generation}: the page is found: {:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (200, 100), "generation {generation}: and it is the page's own size");
|
||||
}
|
||||
|
||||
// A stray number before a header (`42 3 0 obj`) is not a header, and must not cost the one
|
||||
// after it: the lenient read leaves the scan where it was when it fails (noted in review).
|
||||
let pdf = "%PDF-1.4\n\
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
42 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >> endobj\n\
|
||||
trailer << /Root 1 0 R >>\n\
|
||||
%%EOF\n";
|
||||
let mut r = PageRenderer::new(Arc::new(pdf.to_string().into_bytes()), RenderConfig::default());
|
||||
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
|
||||
assert!(page.error.is_none(), "the header after a stray number is found: {:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (200, 100));
|
||||
}
|
||||
|
||||
/// #3109 / #3116: clipping-only text (`7 Tr`) installs a clip for subsequent painting
|
||||
/// but draws no pixels itself.
|
||||
#[test]
|
||||
|
||||
@@ -149,6 +149,7 @@ impl PdfCraftApp {
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
open_prepare_gate: None,
|
||||
pinned: Default::default(),
|
||||
recent_check: Default::default(),
|
||||
pinned_tools: Vec::new(),
|
||||
pin_tool_search: String::new(),
|
||||
toast: None,
|
||||
@@ -457,6 +458,7 @@ impl eframe::App for PdfCraftApp {
|
||||
}
|
||||
self.poll_pending_opens();
|
||||
}
|
||||
self.check_restored_recent();
|
||||
// Chinese wants its own faces before the Japanese ones (one baseline per line).
|
||||
let cjk = theme::CjkPreference::for_language(lang.code());
|
||||
if !self.styled {
|
||||
|
||||
@@ -332,6 +332,7 @@ impl PdfCraftApp {
|
||||
#[cfg(target_os = "macos")]
|
||||
macos_association::repair(std::path::Path::new(&p));
|
||||
self.recent.retain(|r| r.path != p);
|
||||
self.recent_check.opened(&p);
|
||||
self.recent.insert(0, RecentFile { name: name.to_string(), path: p, pages, size });
|
||||
self.recent.truncate(self.recent_limit);
|
||||
}
|
||||
|
||||
@@ -183,9 +183,9 @@ impl PdfCraftApp {
|
||||
self.organize_zoom = zoom.clamp(*canvas::GRID_ZOOM_RANGE.start(), *canvas::GRID_ZOOM_RANGE.end());
|
||||
}
|
||||
if let Ok(r) = serde_json::from_value::<Vec<RecentFile>>(v["recent"].clone()) {
|
||||
// Only keep entries whose files still exist.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let r: Vec<RecentFile> = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect();
|
||||
// Entries whose files are gone leave once the window is up: asking here could block
|
||||
// startup on a mount that has stopped answering (#5682).
|
||||
self.recent_check.restored(r.iter().map(|f| f.path.clone()).collect());
|
||||
self.recent = r;
|
||||
}
|
||||
// Nonsense keeps the limit it had; settings from before the limit have none.
|
||||
|
||||
@@ -14,6 +14,7 @@ pub(super) mod credits;
|
||||
pub(super) mod marks_ui;
|
||||
pub(super) mod pageboxes;
|
||||
pub(super) mod palette;
|
||||
pub(super) mod preferences;
|
||||
mod prompts;
|
||||
pub(super) mod protect;
|
||||
pub(super) mod standards_ui;
|
||||
@@ -128,6 +129,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
Dialog::Properties(_) => 640.0,
|
||||
Dialog::Print => 820.0,
|
||||
Dialog::FieldProps | Dialog::BulkFieldProps => 600.0,
|
||||
Dialog::Preferences => 610.0,
|
||||
Dialog::About => 780.0,
|
||||
Dialog::PinTool => 540.0,
|
||||
_ => 520.0,
|
||||
@@ -1387,10 +1389,13 @@ fn dialog_signature(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending)
|
||||
|
||||
/// `Dialog::Preferences` content. Returns `false` when it has its own buttons and no footer is wanted.
|
||||
fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {
|
||||
ui.set_width(610.0);
|
||||
let t = Tokens::get(ui.ctx());
|
||||
preferences::preferences_header(ui, &t);
|
||||
ui.add_space(10.0);
|
||||
// The settings outgrow a short window: scroll them rather than run off the screen.
|
||||
// The OK row stays below the scroll, in reach however far the settings are scrolled.
|
||||
let max = (ui.ctx().content_rect().height() - 120.0 - crate::js_ui::PREFERENCES_BUTTON_ROW).max(crate::js_ui::PREFERENCES_MIN_SCROLL);
|
||||
let max = (ui.ctx().content_rect().height() - 120.0 - preferences::PREFERENCES_BUTTON_ROW - 40.0).max(preferences::PREFERENCES_MIN_SCROLL);
|
||||
// A scroll area starts from the room the dialog offers it, and a modal offers more
|
||||
// each frame for the first few, so with OK outside the scroll the dialog would grow
|
||||
// over those frames. Asking for the full height as the least it may scroll in
|
||||
@@ -1399,9 +1404,17 @@ fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pendin
|
||||
// cards and other full-width rows (#3557).
|
||||
ui.scope(|ui| {
|
||||
ui.spacing_mut().scroll.floating = false;
|
||||
egui::ScrollArea::vertical().max_height(max).min_scrolled_height(max).show(ui, |ui| crate::js_ui::preferences_body(ui, app, &t));
|
||||
ui.spacing_mut().scroll.bar_inner_margin = 14.0;
|
||||
ui.spacing_mut().scroll.bar_outer_margin = 2.0;
|
||||
ui.style_mut().scroll_animation = egui::style::ScrollAnimation::duration(0.25);
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("preferences-dialog-scroll")
|
||||
.max_height(max)
|
||||
.min_scrolled_height(max)
|
||||
.animated(true)
|
||||
.show(ui, |ui| preferences::preferences_body(ui, app, &t));
|
||||
});
|
||||
req.close = crate::js_ui::preferences_buttons(ui);
|
||||
req.close = preferences::preferences_buttons(ui);
|
||||
false
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Preferences › Appearance: the appearance mode (follow the system, light or dark) above a light
|
||||
//! and a dark theme card, each with a small picture of PdfCraft in that theme.
|
||||
|
||||
use egui::{Rect, RichText, pos2, vec2};
|
||||
use egui::{CornerRadius, Rect, RichText, Stroke, pos2, vec2};
|
||||
|
||||
use crate::PdfCraftApp;
|
||||
use crate::theme::{self, ThemeKind, ThemePreference, Tokens};
|
||||
use crate::widgets;
|
||||
|
||||
/// The themes each card offers. One of each today; a new theme is one more row here.
|
||||
pub const LIGHT_THEMES: &[(ThemeKind, &str)] = &[(ThemeKind::Light, "Light gray")];
|
||||
@@ -82,43 +81,70 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// One theme card: its title, Active when it is what shows now, a preview of the chosen theme
|
||||
/// and a radio row per theme. Returns true when the card or one of its radio rows was clicked.
|
||||
fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)]) -> bool {
|
||||
let inner = egui::Frame::new()
|
||||
.fill(t.card)
|
||||
.stroke(egui::Stroke::new(1.0, if active { t.accent } else { t.border }))
|
||||
.corner_radius(6.0)
|
||||
.inner_margin(egui::Margin::same(8))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(title).font(theme::semibold(12.5)).color(t.text));
|
||||
if active {
|
||||
ui.label(RichText::new(tl!("Active")).color(t.accent_text).small());
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind);
|
||||
preview(ui, shown, ui.available_width());
|
||||
ui.add_space(4.0);
|
||||
let mut clicked = false;
|
||||
for (kind, label) in themes {
|
||||
// One theme per card today, so it is always the chosen one.
|
||||
clicked |= ui.add(widgets::radio(*kind == shown, tl!(label))).clicked();
|
||||
}
|
||||
clicked
|
||||
});
|
||||
// The whole card picks its theme, not just the radio row.
|
||||
let whole = inner.response.interact(egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
inner.inner || whole.clicked()
|
||||
/// One theme card: its title, Active when it is what shows now, and a preview of the chosen theme.
|
||||
/// Returns whether the card was clicked and the control's Response.
|
||||
fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)], query: &str) -> (bool, egui::Response) {
|
||||
let mut card_clicked = false;
|
||||
let frame_stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.border) };
|
||||
let scope_res = ui.scope_builder(egui::UiBuilder::new().id_salt(title).sense(egui::Sense::click()), |ui| {
|
||||
egui::Frame::new().fill(t.card).stroke(frame_stroke).corner_radius(CornerRadius::same(6)).inner_margin(egui::Margin::same(8)).show(
|
||||
ui,
|
||||
|ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
let font = theme::semibold(12.5);
|
||||
let ranges = crate::dialogs::preferences::find_match_ranges(title, query);
|
||||
let galley = if ranges.is_empty() {
|
||||
crate::bidi::layout_ui(ui, title.to_owned(), font, t.text)
|
||||
} else {
|
||||
let (job, _) = crate::dialogs::preferences::create_highlight_job(title, &ranges, font, t.text);
|
||||
ui.painter().layout_job(job)
|
||||
};
|
||||
let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover());
|
||||
ui.painter().galley(title_rect.min, galley, t.text);
|
||||
if active {
|
||||
ui.label(RichText::new(tl!("Active")).color(t.accent_text).small());
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind);
|
||||
preview(ui, shown, ui.available_width());
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
let resp = scope_res.response;
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, active, title));
|
||||
|
||||
if resp.has_focus() {
|
||||
ui.painter().rect_stroke(resp.rect, CornerRadius::same(6), Stroke::new(2.0, t.accent_text), egui::StrokeKind::Outside);
|
||||
}
|
||||
|
||||
let resp = theme::hand(resp);
|
||||
let key_select = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Space) || i.key_pressed(egui::Key::Enter));
|
||||
if resp.clicked() || key_select {
|
||||
card_clicked = true;
|
||||
}
|
||||
(card_clicked, resp)
|
||||
}
|
||||
|
||||
/// The Appearance section of Preferences.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "called by unit tests"))]
|
||||
pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
|
||||
ui.label(RichText::new(tl_ctx!("theme", "Appearance")).font(theme::semibold(13.0)));
|
||||
let mut ctx = crate::dialogs::preferences::PrefSearchContext::new("", false);
|
||||
preferences_section_with_context(ui, app, t, &mut ctx);
|
||||
}
|
||||
|
||||
/// The Appearance section of Preferences with live search highlighting and scrolling context.
|
||||
pub(crate) fn preferences_section_with_context(
|
||||
ui: &mut egui::Ui,
|
||||
app: &mut PdfCraftApp,
|
||||
t: &Tokens,
|
||||
ctx: &mut crate::dialogs::preferences::PrefSearchContext,
|
||||
) {
|
||||
ctx.label(ui, tl_ctx!("theme", "Appearance"), theme::semibold(13.0), t.text);
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Appearance mode"));
|
||||
let label = ctx.label(ui, tl!("Appearance mode"), theme::regular(13.0), t.text);
|
||||
let combo = craft_ui::ComboBox::from_id_salt("appearance-mode").selected_text(tl!(mode_label(app.theme_preference))).show_ui(ui, |ui| {
|
||||
for preference in [ThemePreference::System, ThemePreference::Light, ThemePreference::Dark] {
|
||||
if ui.selectable_label(app.theme_preference == preference, tl!(mode_label(preference))).clicked() {
|
||||
@@ -132,18 +158,29 @@ pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens)
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let light_active = app.theme == ThemeKind::Light;
|
||||
let light_title = tl!("Light theme");
|
||||
let dark_title = tl!("Dark theme");
|
||||
let light_matches = crate::dialogs::preferences::find_match_ranges(light_title, ctx.query).len();
|
||||
let dark_matches = crate::dialogs::preferences::find_match_ranges(dark_title, ctx.query).len();
|
||||
ctx.total_matches += light_matches + dark_matches;
|
||||
|
||||
ui.columns(2, |cols| {
|
||||
let [light, dark] = cols else { return };
|
||||
if card(light, t, tl!("Light theme"), light_active, LIGHT_THEMES) {
|
||||
let (light_clicked, light_resp) = card(light, t, light_title, light_active, LIGHT_THEMES, ctx.query);
|
||||
if light_clicked {
|
||||
app.execute(mode_command(ThemePreference::Light));
|
||||
}
|
||||
if card(dark, t, tl!("Dark theme"), !light_active, DARK_THEMES) {
|
||||
ctx.scroll_if_first_match(&light_resp, light_matches);
|
||||
|
||||
let (dark_clicked, dark_resp) = card(dark, t, dark_title, !light_active, DARK_THEMES, ctx.query);
|
||||
if dark_clicked {
|
||||
app.execute(mode_command(ThemePreference::Dark));
|
||||
}
|
||||
ctx.scroll_if_first_match(&dark_resp, dark_matches);
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
// Acrobat's "Highlight existing fields": shared with the toggle in the form bar.
|
||||
ui.add(crate::widgets::checkbox(&mut app.view_defaults.highlight_fields, tl!("Highlight fields")));
|
||||
ctx.checkbox(ui, &mut app.view_defaults.highlight_fields, tl!("Highlight fields"), t);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -175,7 +212,6 @@ mod tests {
|
||||
);
|
||||
h.run();
|
||||
assert!(h.query_by_label("Light theme").is_some() && h.query_by_label("Dark theme").is_some());
|
||||
assert!(h.query_by_label("Light gray").is_some() && h.query_by_label("Dark gray").is_some());
|
||||
assert_eq!(h.query_all_by_label("Active").count(), 1);
|
||||
if let Ok(path) = std::env::var("PDFCRAFT_APPEARANCE_SHOT") {
|
||||
h.render().unwrap().save(path).unwrap();
|
||||
@@ -200,7 +236,7 @@ mod tests {
|
||||
assert_eq!(h.state().theme_preference, ThemePreference::System);
|
||||
}
|
||||
|
||||
/// Clicking a theme card, or its radio row, picks that theme, not only the mode combo box.
|
||||
/// Clicking a theme card picks that theme, not only the mode combo box.
|
||||
#[test]
|
||||
fn clicking_a_theme_card_picks_that_theme() {
|
||||
let mut app = PdfCraftApp::new();
|
||||
@@ -219,10 +255,9 @@ mod tests {
|
||||
app,
|
||||
);
|
||||
h.run();
|
||||
h.get_by_label("Dark gray").click();
|
||||
h.get_by_label("Dark theme").click();
|
||||
h.run();
|
||||
assert_eq!((h.state().theme_preference, h.state().theme), (ThemePreference::Dark, ThemeKind::Dark));
|
||||
// The card's title is not a widget of its own: the click lands on the card.
|
||||
h.get_by_label("Light theme").click();
|
||||
h.run();
|
||||
assert_eq!((h.state().theme_preference, h.state().theme), (ThemePreference::Light, ThemeKind::Light));
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -405,6 +405,8 @@ pub struct PdfCraftApp {
|
||||
open_prepare_gate: Option<std::sync::Arc<open_worker::PrepareGate>>,
|
||||
/// Folders pinned to Home, and what they held when last listed.
|
||||
pub pinned: folders_ui::PinnedFolders,
|
||||
/// The recent files restored from settings, checked off the UI thread (#5682).
|
||||
recent_check: persist::recent_check::RecentCheck,
|
||||
/// Tools pinned to Home, in user-defined order.
|
||||
pub pinned_tools: Vec<String>,
|
||||
/// Search query for the Pin a tool selection dialog.
|
||||
|
||||
@@ -22,7 +22,9 @@ pub(crate) fn parse(text: &str, count: usize) -> Result<Vec<usize>, PrintError>
|
||||
let mut pages = BTreeSet::new();
|
||||
let mut budget = 1_000_000usize;
|
||||
let number = |token: &str| {
|
||||
let n = token.trim().parse::<usize>().map_err(|_| PrintError::NotAPage(token.into()))?;
|
||||
let t = token.trim();
|
||||
let n =
|
||||
if t.bytes().all(|b| b.is_ascii_digit()) { t.parse::<usize>().ok() } else { None }.ok_or_else(|| PrintError::NotAPage(token.into()))?;
|
||||
if n == 0 || n > count { Err(PrintError::OutOfRange(n, count)) } else { Ok(n - 1) }
|
||||
};
|
||||
for part in text.split([',', ';']).map(str::trim) {
|
||||
@@ -132,6 +134,13 @@ impl PageSelectionInput {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn plus_sign_is_not_a_page_number() {
|
||||
for text in ["+3", "+2-4", "2-+4"] {
|
||||
assert!(matches!(parse(text, 100), Err(PrintError::NotAPage(_))), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_ranges_are_sorted_unique_and_bounded() {
|
||||
let pages = parse("1,12,16-18,89,92,93,97,99", 100).unwrap();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod last_session;
|
||||
pub mod last_view;
|
||||
pub mod paper;
|
||||
pub(crate) mod recent_check;
|
||||
pub(super) mod recovery;
|
||||
pub mod units;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Recent files whose files are gone leave the list, without the window waiting to find out
|
||||
//! (#5682).
|
||||
//!
|
||||
//! A recent file can be on a network or cloud mount that has stopped answering, where even
|
||||
//! asking whether the file exists blocks in the kernel, and no timeout can cancel that. So
|
||||
//! settings keep every recent entry when they load, and a worker asks about them once the window
|
||||
//! is up; each frame only takes the answers it has so far. An entry the worker hasn't reached
|
||||
//! yet, or can't tell about (the mount answers with an error), stays listed and can be opened or
|
||||
//! removed by hand. A worker stuck on a dead mount stays stuck, but nothing waits for it.
|
||||
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use crate::PdfCraftApp;
|
||||
|
||||
/// The recent files restored from settings that haven't been checked yet, and the check under way.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct RecentCheck {
|
||||
/// Paths restored from settings, checked on the next frame.
|
||||
unchecked: Vec<String>,
|
||||
/// The paths the worker has found gone so far; it adds to them as it goes.
|
||||
gone: Option<Arc<Mutex<Vec<String>>>>,
|
||||
/// Paths opened while a check was pending: the file is there now, whatever the worker found.
|
||||
opened: Vec<String>,
|
||||
}
|
||||
|
||||
impl RecentCheck {
|
||||
/// Settings just restored these recent files: check them once the window is up.
|
||||
pub(crate) fn restored(&mut self, paths: Vec<String>) {
|
||||
self.unchecked = paths;
|
||||
}
|
||||
|
||||
/// `path` was just opened: an answer the worker gives about it later is out of date.
|
||||
pub(crate) fn opened(&mut self, path: &str) {
|
||||
if self.gone.is_some() || !self.unchecked.is_empty() {
|
||||
self.opened.push(path.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is known to be gone. Any other answer, an error included, keeps the entry.
|
||||
fn gone(path: &str) -> bool {
|
||||
matches!(std::fs::exists(path), Ok(false))
|
||||
}
|
||||
|
||||
impl PdfCraftApp {
|
||||
/// Start checking the recent files restored from settings, and drop the ones found gone so
|
||||
/// far (called each frame). The check runs on a worker thread, inline in tests
|
||||
/// ([`PdfCraftApp::run_inline`]).
|
||||
pub(crate) fn check_restored_recent(&mut self) {
|
||||
let paths = std::mem::take(&mut self.recent_check.unchecked);
|
||||
// The web build's recent files aren't paths on a file system.
|
||||
if !paths.is_empty() && !cfg!(target_arch = "wasm32") {
|
||||
let slot = Arc::new(Mutex::new(Vec::new()));
|
||||
let out = slot.clone();
|
||||
let ctx = self.ctx.clone();
|
||||
let work = move || {
|
||||
for path in paths {
|
||||
if gone(&path) {
|
||||
out.lock().unwrap_or_else(PoisonError::into_inner).push(path);
|
||||
if let Some(ctx) = &ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if self.run_inline {
|
||||
work();
|
||||
} else if std::thread::Builder::new().name("pdfcraft-recent".into()).spawn(work).is_err() {
|
||||
// No worker: the entries stay listed, as if the check hadn't reached them.
|
||||
return;
|
||||
}
|
||||
self.recent_check.gone = Some(slot);
|
||||
}
|
||||
let Some(slot) = &self.recent_check.gone else { return };
|
||||
// Asked before taking, so a path the worker adds after this is taken on a later frame.
|
||||
let finished = Arc::strong_count(slot) == 1;
|
||||
let gone = std::mem::take(&mut *slot.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
if !gone.is_empty() {
|
||||
// A file opened since the check began is there, whatever the worker found earlier.
|
||||
let opened = &self.recent_check.opened;
|
||||
self.recent.retain(|r| !gone.contains(&r.path) || opened.contains(&r.path));
|
||||
}
|
||||
// The worker has finished (or panicked) and everything it found is taken.
|
||||
if finished {
|
||||
self.recent_check.gone = None;
|
||||
self.recent_check.opened.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A file opened after the worker found it gone, but before that answer was taken, stays
|
||||
/// listed (CodeRabbit on #5692).
|
||||
#[test]
|
||||
fn a_file_opened_while_the_check_is_pending_stays() {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.recent = vec![crate::state::RecentFile { name: "a.pdf".into(), path: "/gone/a.pdf".into(), pages: 1, size: 0 }];
|
||||
// The worker's answer is waiting: it found the file gone.
|
||||
app.recent_check.gone = Some(Arc::new(Mutex::new(vec!["/gone/a.pdf".to_string()])));
|
||||
app.recent_check.opened("/gone/a.pdf");
|
||||
app.check_restored_recent();
|
||||
assert_eq!(app.recent.len(), 1, "the reopened file stays");
|
||||
assert!(app.recent_check.gone.is_none() && app.recent_check.opened.is_empty());
|
||||
// Without the open, the answer removes it.
|
||||
app.recent_check.gone = Some(Arc::new(Mutex::new(vec!["/gone/a.pdf".to_string()])));
|
||||
app.check_restored_recent();
|
||||
assert!(app.recent.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_path_known_to_be_missing_is_gone() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-recent-check-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let here = dir.join("here.pdf");
|
||||
std::fs::write(&here, b"%PDF-1.7").unwrap();
|
||||
assert!(!gone(&here.to_string_lossy()));
|
||||
assert!(gone(&dir.join("missing.pdf").to_string_lossy()));
|
||||
// A path that can't be asked about (here: one with a NUL) is not known to be gone.
|
||||
assert!(!gone("bad\0path.pdf"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -316,449 +316,10 @@ pub(crate) fn document_js_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
|
||||
close
|
||||
}
|
||||
|
||||
/// The height the Preferences dialog keeps below its scrolling settings for the OK row: the
|
||||
/// button, and the space above it.
|
||||
pub(crate) const PREFERENCES_BUTTON_ROW: f32 = 52.0;
|
||||
|
||||
/// The least height the scrolling settings are given. The dialog around them takes about 80 more,
|
||||
/// so this still fits the smallest window (520 pt) at the largest interface size (300%, which
|
||||
/// leaves 173 pt): a taller floor would push OK off the screen again.
|
||||
pub(crate) const PREFERENCES_MIN_SCROLL: f32 = 60.0;
|
||||
|
||||
/// Whether the interface can draw a language picker's native name. On the web the browser's glyph
|
||||
/// rasterizer draws scripts no embedded face has, so the native names stay; on native, ask the
|
||||
/// fonts this build installed (including an installed fallback face, unless system fonts are off).
|
||||
fn picker_text_is_drawable(ui: &egui::Ui, text: &str) -> bool {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (ui, text);
|
||||
true
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
ui.fonts_mut(|fonts| fonts.has_glyphs(&egui::FontId::proportional(13.0), text))
|
||||
}
|
||||
}
|
||||
|
||||
/// The date picker's displayed name. Its languages are the interface languages, so it uses the
|
||||
/// same drawable-name fallback: a native name whose script this build has no face for would
|
||||
/// otherwise abort under egui 0.37's `MissingGlyphPolicy::Panic` (for example Hindi without a
|
||||
/// Devanagari face and installed system fonts turned off).
|
||||
fn date_language_picker_name(l: &pdfcraft_engine::dates::DateLanguage, drawable: impl FnOnce(&str) -> bool) -> &'static str {
|
||||
match crate::i18n::Lang::from_code(l.code) {
|
||||
Some(language) => language.picker_name(drawable),
|
||||
None => l.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// Preferences: interface language and size, appearance, identity and JavaScript. Drawn in a scroll
|
||||
/// area; [`preferences_buttons`] goes below it, outside the scroll, so OK is always in reach.
|
||||
pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
|
||||
ui.label(egui::RichText::new(tl!("Preferences")).font(theme::semibold(18.0)));
|
||||
ui.label(egui::RichText::new(tl!("Appearance")).font(theme::semibold(13.0)));
|
||||
if ui.add(widgets::checkbox(&mut app.show_page_edge_shadows, tl!("Show Page Edge Shadows"))).changed() {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Interface language"));
|
||||
// A native name is only drawn when these fonts can draw it; otherwise the English name
|
||||
// keeps the list readable instead of aborting on a missing glyph (for example Hindi
|
||||
// without a Devanagari face, and installed system fonts turned off).
|
||||
let (selected, picker) = {
|
||||
let drawable = |text: &str| picker_text_is_drawable(ui, text);
|
||||
let selected = crate::i18n::Lang::from_code(&app.language)
|
||||
.map_or_else(|| tl!("Auto").to_owned(), |language| language.picker_name(drawable).to_owned());
|
||||
let picker = crate::i18n::Lang::for_picker_by(|language| language.picker_name(drawable))
|
||||
.into_iter()
|
||||
.map(|language| (language, language.picker_name(drawable)))
|
||||
.collect::<Vec<_>>();
|
||||
(selected, picker)
|
||||
};
|
||||
let before = app.language.clone();
|
||||
craft_ui::ComboBox::from_id_salt("interface-language")
|
||||
.selected_text(selected)
|
||||
.show_ui(ui, |ui| {
|
||||
if ui.selectable_value(&mut app.language, crate::i18n::AUTO.to_string(), tl!("Auto")).clicked() {
|
||||
ui.close();
|
||||
}
|
||||
for (language, name) in &picker {
|
||||
if ui.selectable_value(&mut app.language, language.code().to_string(), *name).clicked() {
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.labelled_by(label.id);
|
||||
// Relabel the rest of this dialog in the new language right away, not next frame.
|
||||
if app.language != before {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_pref(&app.language));
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
use crate::ui_scale;
|
||||
let label = ui.label(tl!("Interface size"));
|
||||
// Auto shows the size it draws at: the display's scale times the system's text scale.
|
||||
let native = ui.ctx().native_pixels_per_point().unwrap_or(1.0);
|
||||
let auto_percent = ui_scale::percent(ui_scale::drawn(None, app.system_text_scale, native));
|
||||
let auto = crate::i18n::fmt(tl!("Auto ({percent}%)"), &[("percent", &auto_percent.to_string())]);
|
||||
let selected = app.ui_scale.map_or_else(|| auto.clone(), |f| format!("{}%", ui_scale::percent(f)));
|
||||
craft_ui::ComboBox::from_id_salt("interface-size")
|
||||
.selected_text(selected)
|
||||
.show_ui(ui, |ui| {
|
||||
if ui.selectable_value(&mut app.ui_scale, None, auto).clicked() {
|
||||
ui.close();
|
||||
}
|
||||
for p in ui_scale::PRESETS {
|
||||
let factor = f32::from(p) / 100.0;
|
||||
if ui.selectable_label(app.ui_scale.is_some_and(|f| ui_scale::percent(f) == u32::from(p)), format!("{p}%")).clicked() {
|
||||
app.ui_scale = Some(factor);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.labelled_by(label.id);
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new(tl!("Auto follows the system's text size. Pages always render at the display's full resolution."))
|
||||
.small()
|
||||
.color(t.text_muted),
|
||||
);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Tools panel side"));
|
||||
let right = app.side_panels.tools_on_right();
|
||||
if ui.selectable_label(!right, tl!("Left")).clicked() {
|
||||
app.side_panels.tools_side = crate::side_panels::ToolsSide::Left;
|
||||
}
|
||||
if ui.selectable_label(right, tl!("Right")).clicked() {
|
||||
app.side_panels.tools_side = crate::side_panels::ToolsSide::Right;
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Navigation rail side"));
|
||||
let right = app.side_panels.rail_on_right();
|
||||
let left_btn = ui.selectable_label(!right, tl!("Left"));
|
||||
left_btn.widget_info(|| {
|
||||
egui::WidgetInfo::selected(egui::Role::Button, true, !right, format!("{}: {}", tl!("Navigation rail side"), tl!("Left")))
|
||||
});
|
||||
if left_btn.clicked() {
|
||||
app.side_panels.rail_side = crate::side_panels::ToolsSide::Left;
|
||||
}
|
||||
let right_btn = ui.selectable_label(right, tl!("Right"));
|
||||
right_btn.widget_info(|| {
|
||||
egui::WidgetInfo::selected(egui::Role::Button, true, right, format!("{}: {}", tl!("Navigation rail side"), tl!("Right")))
|
||||
});
|
||||
if right_btn.clicked() {
|
||||
app.side_panels.rail_side = crate::side_panels::ToolsSide::Right;
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
crate::appearance::preferences_section(ui, app, t);
|
||||
ui.add_space(8.0);
|
||||
reading_colours_section(ui, app, t);
|
||||
ui.add_space(8.0);
|
||||
ui.label(egui::RichText::new(tl!("Documents and view")).font(theme::semibold(13.0)));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Default workspace mode"));
|
||||
for (mode, label) in [
|
||||
(crate::Mode::AllTools, "All tools"),
|
||||
(crate::Mode::Read, "Read"),
|
||||
(crate::Mode::Edit, "Edit"),
|
||||
(crate::Mode::Convert, "Convert"),
|
||||
(crate::Mode::Sign, "E-Sign"),
|
||||
] {
|
||||
widgets::radio_value(ui, &mut app.default_mode, mode, tl!(label));
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new(tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session."))
|
||||
.small()
|
||||
.color(t.text_muted),
|
||||
);
|
||||
let defaults = &mut app.view_defaults;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Default page display"));
|
||||
for l in crate::canvas::PageLayout::ORDER {
|
||||
widgets::radio_value(ui, &mut defaults.layout, l, tl!(l.label()));
|
||||
}
|
||||
ui.add(widgets::checkbox(&mut defaults.continuous, tl!("Continuous scrolling")));
|
||||
});
|
||||
ui.add(widgets::checkbox(&mut defaults.show_page_gaps, tl!("Show gaps between pages")));
|
||||
ui.label(egui::RichText::new(tl!("Hide gaps to join page edges. Margins inside the PDF remain unchanged.")).small().color(t.text_muted));
|
||||
ui.horizontal(|ui| {
|
||||
use crate::canvas::Fit;
|
||||
ui.label(tl!("Default zoom"));
|
||||
widgets::radio_value(ui, &mut defaults.fit, Fit::Width, tl!("Fit to width"));
|
||||
widgets::radio_value(ui, &mut defaults.fit, Fit::Page, tl!("Zoom to page level"));
|
||||
widgets::radio_value(ui, &mut defaults.fit, Fit::None, tl!("Custom"));
|
||||
// Editing the percentage selects Custom.
|
||||
let mut percent = defaults.zoom * 100.0;
|
||||
if ui.add(egui::DragValue::new(&mut percent).range(8.0..=6400.0).max_decimals(0).suffix("%")).changed() {
|
||||
(defaults.fit, defaults.zoom) = (Fit::None, percent / 100.0);
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new(tl!("Used when a PDF doesn't ask for a layout or zoom. Continuous scrolling never snaps between pages."))
|
||||
.small()
|
||||
.color(t.text_muted),
|
||||
);
|
||||
ui.add(widgets::checkbox(&mut app.always_default_view, tl!("Always use my default zoom and page layout")));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Units"));
|
||||
for u in crate::units::Unit::ALL {
|
||||
widgets::radio_value(ui, &mut app.units, u, u.label());
|
||||
}
|
||||
});
|
||||
ui.label(egui::RichText::new(tl!("For page sizes and margins.")).small().color(t.text_muted));
|
||||
// The web build has no file paths to list.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Recent files to keep"));
|
||||
ui.add(egui::DragValue::new(&mut app.recent_limit).range(0..=crate::RECENT_FILES_MAX)).labelled_by(label.id);
|
||||
});
|
||||
ui.label(egui::RichText::new(tl!("Lowering this forgets the oldest files. At 0 there is no list.")).small().color(t.text_muted));
|
||||
}
|
||||
// The web build has no file paths to reopen.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
ui.add(widgets::checkbox(&mut app.reopen_last_session, tl!("Reopen the files that were open when PdfCraft last closed")));
|
||||
// Acrobat's "Restore last view settings when reopening documents" (#1767).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
ui.add(widgets::checkbox(&mut app.restore_last_view, tl!("Restore the last view (page, zoom and page display) when a document is opened again")));
|
||||
// The web build has no files on disk to watch.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
ui.add(widgets::checkbox(&mut app.reload_changed_files, tl!("Reload documents when their files change on disk")));
|
||||
// The notice's "Don't show again" turns this off (#4035); the restrictions stay either way.
|
||||
ui.add(widgets::checkbox(&mut app.show_secured_notice, tl!("Show a notice when a document is secured")));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Scroll speed (mouse wheel and arrow keys)"));
|
||||
for speed in crate::scroll_speed::ScrollSpeed::ALL {
|
||||
widgets::radio_value(ui, &mut app.scroll_speed, speed, tl_ctx!("scroll speed", speed.label()));
|
||||
}
|
||||
});
|
||||
// Whether anything animates, the wheel's scrolling and zooming included; left alone it
|
||||
// follows the system's animation setting.
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Animation effects"));
|
||||
for choice in crate::motion::AnimationEffects::ALL {
|
||||
widgets::radio_value(ui, &mut app.animation_effects, choice, tl_ctx!("animation effects", choice.label()));
|
||||
}
|
||||
});
|
||||
// Only where the app draws the title bar (GNOME on Wayland); elsewhere the desktop draws it.
|
||||
if app.window_controls.is_some() {
|
||||
ui.add(widgets::checkbox(&mut app.system_title_bar, tl!("Use system title bar")))
|
||||
.on_hover_text(tl!("Show a basic title bar for the window buttons instead of the tab strip. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme."));
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
// Identity: the author of new comments (Acrobat: Preferences ▸ Identity).
|
||||
ui.label(egui::RichText::new(tl!("Identity")).font(theme::semibold(13.0)));
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Name on new comments"));
|
||||
ui.add(crate::widgets::line(&mut app.comment_prefs.author).desired_width(220.0).char_limit(crate::MAX_AUTHOR_CHARS)).labelled_by(label.id);
|
||||
});
|
||||
ui.add(widgets::checkbox(&mut app.comment_prefs.hide_empty_highlight_hover, tl!("Hide hover previews for highlights without comment text")));
|
||||
ui.add_space(8.0);
|
||||
ui.label(egui::RichText::new(tl!("Fill & Sign")).font(theme::semibold(13.0)));
|
||||
ui.add(widgets::checkbox(&mut app.flatten_fill_sign_on_save, tl!("Flatten Fill & Sign when saving")));
|
||||
ui.add_enabled(
|
||||
!app.flatten_fill_sign_on_save,
|
||||
widgets::checkbox(&mut app.ask_to_lock_signatures, tl!("Otherwise, ask on the first save after a signature is placed")),
|
||||
);
|
||||
ui.label(
|
||||
egui::RichText::new(tl!("Text, marks and signatures become part of the page. Other comments stay editable.")).small().color(t.text_muted),
|
||||
);
|
||||
ui.add_space(8.0);
|
||||
date_format(ui, app, t);
|
||||
ui.add_space(8.0);
|
||||
ui.label(egui::RichText::new("JavaScript").font(theme::semibold(13.0)));
|
||||
egui::Frame::new().fill(t.hover).corner_radius(egui::CornerRadius::same(6)).inner_margin(egui::Margin::same(10)).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
let mut on = app.session.javascript();
|
||||
if ui.add(widgets::checkbox(&mut on, tl!("Enable Acrobat JavaScript"))).changed() {
|
||||
app.session.set_javascript(on);
|
||||
}
|
||||
ui.label(
|
||||
egui::RichText::new(tl!("Scripts run in a sandbox without file or network access. A script that asks to open a web page needs your permission first. With JavaScript off, Acrobat's standard format, validate and calculate functions still work."))
|
||||
.small()
|
||||
.color(t.text_muted),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// The Preferences dialog's OK row. Returns `true` to close.
|
||||
pub(crate) fn preferences_buttons(ui: &mut egui::Ui) -> bool {
|
||||
ui.add_space(10.0);
|
||||
buttons(ui, tl!("OK"), &[]).is_some()
|
||||
}
|
||||
|
||||
/// Preferences ▸ Date format: a preset, or any pattern typed in, for Fill & Sign dates, and the
|
||||
/// language of its month and weekday names. A valid pattern applies as it's typed; an invalid
|
||||
/// one stays in the box with the reason, and the last valid one stays in use.
|
||||
fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
|
||||
use pdfcraft_engine::dates::{DATE_FORMATS, DATE_LANGUAGES, MAX_DATE_FORMAT_CHARS};
|
||||
ui.label(egui::RichText::new(tl!("Date format")).font(theme::semibold(13.0)));
|
||||
let sample = |app: &PdfCraftApp, f: &str| format!("{} {f}", app.date_text(Some(f)).unwrap_or_default());
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Fill & Sign dates"));
|
||||
let current = app.session.date_format().to_string();
|
||||
let selected = if DATE_FORMATS.contains(¤t.as_str()) { sample(app, ¤t) } else { tl!("Custom").to_string() };
|
||||
craft_ui::ComboBox::from_id_salt("date-format")
|
||||
.selected_text(selected)
|
||||
.width(240.0)
|
||||
.show_ui(ui, |ui| {
|
||||
for f in DATE_FORMATS {
|
||||
if ui.selectable_label(current == f, sample(app, f)).clicked() && app.session.set_date_format(f).is_ok() {
|
||||
app.date_format_draft = None;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.labelled_by(label.id);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Pattern"));
|
||||
let mut text = app.date_format_draft.clone().unwrap_or_else(|| app.session.date_format().to_string());
|
||||
let edit = ui.add(egui::TextEdit::singleline(&mut text).desired_width(160.0).char_limit(MAX_DATE_FORMAT_CHARS)).labelled_by(label.id);
|
||||
// The box keeps the text as typed (a trailing space included) while it has focus; the
|
||||
// setting takes the trimmed pattern whenever it's valid.
|
||||
if edit.changed() {
|
||||
let _ = app.session.set_date_format(&text);
|
||||
app.date_format_draft = Some(text.clone());
|
||||
}
|
||||
if !edit.has_focus() && pdfcraft_engine::dates::check_date_format(&text).is_ok() {
|
||||
app.date_format_draft = None;
|
||||
}
|
||||
match app.date_text(Some(&text)) {
|
||||
Ok(today) => ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Today: {date}"), &[("date", &today)])).color(t.text_muted)),
|
||||
// The engine's reason, in English.
|
||||
Err(e) => ui.label(egui::RichText::new(e).color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B))),
|
||||
};
|
||||
});
|
||||
// Fill & Sign refuses a date it would save as "?"; say so before anyone tries.
|
||||
let bad = app.date_text(None).map(|today| pdfcraft_engine::dates::unwritable(&today)).unwrap_or_default();
|
||||
if !bad.is_empty() {
|
||||
ui.label(
|
||||
egui::RichText::new(crate::i18n::fmt(
|
||||
tl!(
|
||||
"{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy."
|
||||
),
|
||||
&[("chars", &bad)],
|
||||
))
|
||||
.color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B)),
|
||||
);
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Language"));
|
||||
// Build every label before the combo box mutably borrows `ui`, with the same drawable
|
||||
// fallback the interface language picker uses.
|
||||
let (follow, selected, current, names) = {
|
||||
let drawable = |text: &str| picker_text_is_drawable(ui, text);
|
||||
let interface = crate::i18n::current().picker_name(drawable);
|
||||
let follow = crate::i18n::fmt(tl!("Same as interface ({language})"), &[("language", interface)]);
|
||||
let current = app.session.date_language().map(str::to_string);
|
||||
let selected = DATE_LANGUAGES
|
||||
.iter()
|
||||
.find(|l| current.as_deref() == Some(l.code))
|
||||
.map_or_else(|| follow.clone(), |l| date_language_picker_name(l, drawable).to_string());
|
||||
let names = DATE_LANGUAGES.iter().map(|l| (l, date_language_picker_name(l, drawable))).collect::<Vec<_>>();
|
||||
(follow, selected, current, names)
|
||||
};
|
||||
craft_ui::ComboBox::from_id_salt("date-language")
|
||||
.selected_text(selected)
|
||||
.width(240.0)
|
||||
.show_ui(ui, |ui| {
|
||||
if ui.selectable_label(current.is_none(), follow).clicked() && app.session.set_date_language(None).is_ok() {
|
||||
ui.close();
|
||||
}
|
||||
for (l, name) in &names {
|
||||
if ui.selectable_label(current.as_deref() == Some(l.code), *name).clicked() && app.session.set_date_language(Some(l.code)).is_ok()
|
||||
{
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.labelled_by(label.id);
|
||||
});
|
||||
ui.label(
|
||||
egui::RichText::new(crate::i18n::fmt(
|
||||
tl!("yyyy or yy year · m or mm month · mmm or mmmm month name · d or dd day · ddd or dddd weekday. H, h, M, s and t are time letters and can't be used on their own: put {escape} before a letter to show it as is."),
|
||||
&[("escape", "\\")],
|
||||
))
|
||||
.small()
|
||||
.color(t.text_muted),
|
||||
);
|
||||
}
|
||||
|
||||
fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
|
||||
// Reading colours (Acrobat: Replace Document Colors): solid text and line-art paints are
|
||||
// remapped while rendering, and the page clears to the background colour. The preference
|
||||
// is app-wide: every open document follows it, and documents open with it.
|
||||
ui.label(egui::RichText::new(tl!("Reading colours")).font(theme::semibold(13.0)));
|
||||
let mode = app.reading_colors.mode_name();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (name, label, colors) in [
|
||||
("off", "Off", pdfcraft_render::ReadingColors::default()),
|
||||
("black-on-white", "Black on white", pdfcraft_render::ReadingColors::BLACK_ON_WHITE),
|
||||
("white-on-black", "White on black", pdfcraft_render::ReadingColors::WHITE_ON_BLACK),
|
||||
("yellow-on-black", "Yellow on black", pdfcraft_render::ReadingColors::YELLOW_ON_BLACK),
|
||||
("green-on-black", "Green on black", pdfcraft_render::ReadingColors::GREEN_ON_BLACK),
|
||||
] {
|
||||
let params = colors.params.unwrap_or(pdfcraft_render::ReadingParams {
|
||||
text: [0, 0, 0],
|
||||
background: [255, 255, 255],
|
||||
only_black: false,
|
||||
line_art: true,
|
||||
});
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(104.0);
|
||||
let sample = egui::RichText::new("Aa").size(22.0).color(egui::Color32::from_rgb(params.text[0], params.text[1], params.text[2]));
|
||||
let button = egui::Button::new(sample)
|
||||
.fill(egui::Color32::from_rgb(params.background[0], params.background[1], params.background[2]))
|
||||
.min_size(egui::vec2(94.0, 44.0))
|
||||
.stroke(egui::Stroke::new(if mode == name { 2.0 } else { 1.0 }, if mode == name { t.accent } else { t.border }));
|
||||
let response = ui.add(button);
|
||||
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, mode == name, tl!(label)));
|
||||
if response.clicked() {
|
||||
app.set_reading_colors(colors);
|
||||
}
|
||||
ui.label(tl!(label));
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
if let Some(params) = app.reading_colors.params {
|
||||
let text = egui::Color32::from_rgb(params.text[0], params.text[1], params.text[2]);
|
||||
let background = egui::Color32::from_rgb(params.background[0], params.background[1], params.background[2]);
|
||||
egui::Frame::new().fill(background).inner_margin(16.0).show(ui, |ui| {
|
||||
ui.set_min_width((ui.available_width() - 32.0).max(0.0));
|
||||
ui.label(egui::RichText::new(tl!("Reading colours")).size(18.0).color(text));
|
||||
ui.label(egui::RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).color(text));
|
||||
});
|
||||
} else {
|
||||
ui.label(tl!("Original"));
|
||||
}
|
||||
egui::CollapsingHeader::new(tl!("Custom")).default_open(mode == "custom").show(ui, |ui| {
|
||||
let mut colors = if app.reading_colors.params.is_some() { app.reading_colors } else { pdfcraft_render::ReadingColors::BLACK_ON_WHITE };
|
||||
let mut changed = false;
|
||||
if let Some(params) = colors.params.as_mut() {
|
||||
ui.horizontal(|ui| {
|
||||
let text = ui.label(tl!("Text"));
|
||||
changed |= ui.color_edit_button_srgb(&mut params.text).labelled_by(text.id).changed();
|
||||
let background = ui.label(tl!("Page background"));
|
||||
changed |= ui.color_edit_button_srgb(&mut params.background).labelled_by(background.id).changed();
|
||||
});
|
||||
changed |= ui.add(crate::widgets::checkbox(&mut params.only_black, tl!("Only change the colour of black text or line art"))).changed();
|
||||
changed |= ui.add(crate::widgets::checkbox(&mut params.line_art, tl!("Change the colour of line art as well as text"))).changed();
|
||||
}
|
||||
if changed {
|
||||
app.set_reading_colors(colors);
|
||||
}
|
||||
});
|
||||
ui.label(egui::RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).small().color(t.text_muted));
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
#[expect(unused_imports, reason = "re-exported for tests and backward compatibility")]
|
||||
pub(crate) use crate::dialogs::preferences::{
|
||||
PREFERENCES_BUTTON_ROW, PREFERENCES_MIN_SCROLL, date_language_picker_name, preferences_body, preferences_buttons, preferences_header,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
@@ -102,3 +102,152 @@ fn a_very_tall_window_does_not_leave_a_blank_gap_above_ok() {
|
||||
assert!(on_screen(ok, 2600.0) && on_screen(last, 2600.0), "{last:?} {ok:?}");
|
||||
assert!(ok.min.y - last.max.y < 120.0, "a gap of {} pt between the last setting and OK", ok.min.y - last.max.y);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn segmented_pill_controls_switch_modes_and_layouts() {
|
||||
let mut h = harness(900.0);
|
||||
// Switch workspace mode via segmented pill
|
||||
h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Convert").scroll_to_me();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Convert").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().default_mode, pdfcraft_ui_egui::Mode::Convert);
|
||||
|
||||
let continuous_before = h.state().view_defaults.continuous;
|
||||
|
||||
// Switch page layout via segmented pill
|
||||
h.get_by_label("Two-page view").scroll_to_me();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Two-page view").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp);
|
||||
assert_eq!(h.state().view_defaults.continuous, continuous_before, "Two-page view retains continuous scrolling");
|
||||
|
||||
// Switch continuous scrolling pill (can be combined with Two-page view)
|
||||
h.get_by_label("Continuous scrolling").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().view_defaults.continuous, !continuous_before);
|
||||
assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp, "two-page continuous scrolling is supported");
|
||||
|
||||
// Switch to single page mode (continuous setting remains independent)
|
||||
h.get_by_label("Single page").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
|
||||
assert_eq!(h.state().view_defaults.continuous, !continuous_before);
|
||||
|
||||
// Switch tools panel side via segmented pill
|
||||
h.get_by_label("Left").scroll_to_me();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Left").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().side_panels.tools_side, pdfcraft_ui_egui::side_panels::ToolsSide::Left);
|
||||
|
||||
// Switch measurement units via segmented pill
|
||||
h.get_by_label("pt").scroll_to_me();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("pt").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().units, pdfcraft_ui_egui::units::Unit::Points);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_settings_scans_and_highlights_in_situ_without_hiding_cards() {
|
||||
let mut h = harness(900.0);
|
||||
// Initially all card titles exist
|
||||
assert!(h.query_by_label("General & Interface").is_some());
|
||||
assert!(h.query_by_label("Comment").is_some());
|
||||
assert!(h.query_by_label("JavaScript").is_some());
|
||||
|
||||
// Type "Hide hover" in search box
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
|
||||
h.run_steps(1);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Hide hover");
|
||||
h.run_steps(4);
|
||||
|
||||
// In browser-style search, cards are NOT hidden
|
||||
assert!(h.query_by_label("General & Interface").is_some());
|
||||
assert!(h.query_by_label("Comment").is_some());
|
||||
assert!(h.query_by_label("JavaScript").is_some());
|
||||
|
||||
// The setting "Hide hover previews for highlights without comment text" is present and matched
|
||||
assert!(h.query_by_label("Hide hover previews for highlights without comment text").is_some());
|
||||
// Match badge displays 1 match
|
||||
assert!(h.query_by_label("1 match").is_some());
|
||||
|
||||
// Clearing search clears match badge
|
||||
h.get_by_label("Clear search").click();
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("1 match").is_none());
|
||||
|
||||
// Search for "javascript"
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
|
||||
h.run_steps(1);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("javascript");
|
||||
h.run_steps(4);
|
||||
|
||||
// Cards remain visible and multiple matches are reported
|
||||
assert!(h.query_by_label("JavaScript").is_some());
|
||||
assert!(h.query_by_label("General & Interface").is_some());
|
||||
assert!(h.query_by_label_contains("matches").is_some());
|
||||
|
||||
// Clearing search shows everything again
|
||||
h.get_by_label("Clear search").click();
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("General & Interface").is_some());
|
||||
assert!(h.query_by_label("Comment").is_some());
|
||||
assert!(h.query_by_label("JavaScript").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferences_dialog_scrollbar_spacing_and_controls() {
|
||||
let h = harness(600.0);
|
||||
let title = h.get_by(|n| n.role() == egui::accesskit::Role::Label && n.value().as_deref() == Some("Preferences")).rect();
|
||||
let search = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").rect();
|
||||
let ok = h.get_by_label("OK").rect();
|
||||
assert!(on_screen(ok, 600.0));
|
||||
// Header title and search box are vertically aligned
|
||||
assert!((title.center().y - search.center().y).abs() <= 2.0);
|
||||
// Search box right edge is aligned within the dialog
|
||||
assert!(search.max.x <= ok.max.x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_scrolls_option_only_and_theme_card_matches_into_visible_viewport() {
|
||||
let mut h = harness(480.0);
|
||||
let title = h.get_by(|n| n.role() == egui::accesskit::Role::Label && n.value().as_deref() == Some("Preferences")).rect();
|
||||
let ok = h.get_by_label("OK").rect();
|
||||
|
||||
// "Two-page view" is an option in Card 3 (Documents and view).
|
||||
// In a 480 pt window, it starts out below the visible scroll viewport.
|
||||
let opt_before = h.get_by_label("Two-page view").rect();
|
||||
assert!(opt_before.min.y >= ok.min.y, "Two-page option starts out below the visible viewport: {opt_before:?} vs OK {ok:?}");
|
||||
|
||||
// Searching "Two-page" (which only occurs inside that segmented pill option)
|
||||
// auto-scrolls the matching option into the visible viewport between title and OK.
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
|
||||
h.run_steps(1);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Two-page");
|
||||
h.run_steps(4);
|
||||
|
||||
let opt_after = h.get_by_label("Two-page view").rect();
|
||||
assert!(
|
||||
opt_after.min.y >= title.max.y && opt_after.max.y <= ok.min.y,
|
||||
"Two-page option scrolled into visible scroll viewport: {opt_after:?} between title {title:?} and OK {ok:?}"
|
||||
);
|
||||
|
||||
// Clear search and test a theme-card-only match
|
||||
h.get_by_label("Clear search").click();
|
||||
h.run_steps(4);
|
||||
|
||||
// Search for "Dark theme" (which occurs only in the dark theme card in Card 2).
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
|
||||
h.run_steps(1);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Dark theme");
|
||||
h.run_steps(4);
|
||||
|
||||
let dark_card = h.get_by_label("Dark theme").rect();
|
||||
assert!(
|
||||
dark_card.min.y >= title.max.y && dark_card.max.y <= ok.min.y,
|
||||
"Dark theme card scrolled into visible viewport: {dark_card:?} between title {title:?} and OK {ok:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -221,6 +221,39 @@ fn the_limit_is_saved_and_restored_and_cuts_a_longer_list() {
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// #5682: restoring settings never asks the file system about recent files, which can block on a
|
||||
/// mount that has stopped answering. A gone file leaves the list once frames run, and a file that
|
||||
/// is there stays.
|
||||
#[test]
|
||||
fn restoring_settings_does_not_check_recent_files_and_a_frame_drops_the_gone_ones() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-recent-restore-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let here = dir.join("here.pdf");
|
||||
std::fs::write(&here, PDF).unwrap();
|
||||
let here = here.to_string_lossy().into_owned();
|
||||
let gone = dir.join("gone.pdf").to_string_lossy().into_owned();
|
||||
let entries: Vec<RecentFile> =
|
||||
[&here, &gone].iter().map(|p| RecentFile { name: "x.pdf".into(), path: (*p).clone(), pages: 1, size: 0 }).collect();
|
||||
let json = serde_json::json!({ "recent": entries }).to_string();
|
||||
|
||||
let mut restored = PdfCraftApp::new();
|
||||
restored.restore(&json);
|
||||
let paths: Vec<&str> = restored.recent.iter().map(|r| r.path.as_str()).collect();
|
||||
assert_eq!(paths, [here.as_str(), gone.as_str()], "restoring keeps every entry without asking whether its file exists");
|
||||
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1600.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.run_inline = true;
|
||||
app.restore(&json);
|
||||
app
|
||||
});
|
||||
h.run_steps(2);
|
||||
let paths: Vec<&str> = h.state().recent.iter().map(|r| r.path.as_str()).collect();
|
||||
assert_eq!(paths, [here.as_str()], "the gone file leaves once the window is up");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_settings_file_can_not_ask_for_a_limit_that_is_not_one() {
|
||||
for (saved, want) in [
|
||||
|
||||
@@ -242,11 +242,11 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() {
|
||||
assert_theme(&h, ThemePreference::System, ThemeKind::Dark);
|
||||
assert_eq!(mode_shown(&h), "Use system setting");
|
||||
|
||||
// The OS is dark: the Dark card's radio row picks Dark, and the combo box says so.
|
||||
// The OS is dark: the Dark card picks Dark, and the combo box says so.
|
||||
// The cards sit below the fold of the Preferences scroll area at this window size.
|
||||
h.get_by_label("Dark gray").scroll_to_me();
|
||||
h.get_by_label("Dark theme").scroll_to_me();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Dark gray").click();
|
||||
h.get_by_label("Dark theme").click();
|
||||
h.run_steps(3);
|
||||
assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark);
|
||||
assert_eq!(mode_shown(&h), "Dark");
|
||||
|
||||
+4
-1
@@ -1,5 +1,7 @@
|
||||
# PdfCraft roadmap: milestones and what's next
|
||||
|
||||
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged)
|
||||
|
||||
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 further review: inherited drawing/text state, affine image gestures, paste/selection ownership, no-op scripts and menu permissions; estimates unchanged)
|
||||
|
||||
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 latest comments: explicit image-paste events, mixed-size field refresh, and documented mixed-script normalization with Undo; estimates unchanged)
|
||||
@@ -223,7 +225,7 @@ total matches the parity estimate.
|
||||
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
|
||||
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Refreshed against upstream `99941daa` (2026-10-15).<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
|
||||
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Done since: #5657 page-mark operations are atomic across selected pages, including shared/inherited resources and existing unsaved edits. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. #1316: replacing a line or paragraph keeps a neighbouring line whose glyph box overlaps when the baselines differ; a second copy on the same baseline is still replaced. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks |
|
||||
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Tracked editable text distinguishes repeated glyph spacing from word gaps, with synthetic paragraph/object regressions. Missing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat |
|
||||
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Existing simple field-font encodings and Differences are respected when generating appearances; an unencodable value uses a separate Helvetica appearance font without changing the source font. Synthetic reopen regressions cover punctuation, subset fallback and multiline text. Exact font metrics/layout and broader Unicode fallback remain incomplete. |
|
||||
@@ -296,6 +298,7 @@ Estimates unchanged.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
|
||||
| 2026-10-31 | patch | #1577: reconcile optional page shadows with current viewer/organizer and settings modules; CI validation pending. |
|
||||
| 2026-10-31 | patch | M3 #1354: reconcile the launch override with split app/file modules and the structured open result; preserve headless help/version exits. CI validation pending. |
|
||||
| 2026-10-31 | patch | M2, PR #4172: eight GBK font/alias cases compare exact pixels with independent installed-face and explicit-Unicode references; wrong-glyph and wrong-family negative controls fail. Estimates unchanged. |
|
||||
|
||||
@@ -2460,8 +2460,8 @@ milestone = "M7"
|
||||
status = "shipped"
|
||||
commands = ["edit.header_footer.update", "edit.header_footer.remove"]
|
||||
tools = ["doc_header_footer", "doc_remove_marks"]
|
||||
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset"]
|
||||
notes = "recognises PdfCraft marks; Acrobat-made headers are not detected yet"
|
||||
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/mark_transaction_tests.rs::header_footer_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"]
|
||||
notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). recognises PdfCraft marks; Acrobat-made headers are not detected yet"
|
||||
|
||||
[[feature]]
|
||||
id = "edit.header-footer-tokens"
|
||||
@@ -2532,8 +2532,8 @@ milestone = "M7"
|
||||
status = "shipped"
|
||||
commands = ["edit.watermark.update", "edit.watermark.remove"]
|
||||
tools = ["doc_watermark", "doc_remove_marks"]
|
||||
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove"]
|
||||
notes = ""
|
||||
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/mark_transaction_tests.rs::watermark_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"]
|
||||
notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). "
|
||||
|
||||
[[feature]]
|
||||
id = "edit.watermark-appearance"
|
||||
@@ -2568,8 +2568,8 @@ milestone = "M7"
|
||||
status = "shipped"
|
||||
commands = ["edit.background.update", "edit.background.remove"]
|
||||
tools = ["doc_background", "doc_remove_marks"]
|
||||
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/backdrop_tests.rs::a_white_fill_backdrop_is_replaced_and_put_back_when_the_background_goes", "crates/edit/src/backdrop_tests.rs::an_edit_after_the_fill_is_kept_and_the_backdrop_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_copy_written_out_again_with_other_spacing_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_change_before_the_fill_leaves_it_off_and_names_the_page", "crates/edit/src/backdrop_tests.rs::a_fill_that_would_cover_content_painted_before_it_stays_off", "crates/engine/src/tests.rs::remove_background_names_the_pages_whose_own_backdrop_stays_off", "crates/automation/tests/it/backdrop.rs::removed_text_leaves_the_file_when_a_background_replaced_the_pages_backdrop"]
|
||||
notes = "Remove also turns back on a page backdrop Add replaced, keeping edits made after it; where that isn't safe it says which pages keep it off"
|
||||
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/backdrop_tests.rs::a_white_fill_backdrop_is_replaced_and_put_back_when_the_background_goes", "crates/edit/src/backdrop_tests.rs::an_edit_after_the_fill_is_kept_and_the_backdrop_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_copy_written_out_again_with_other_spacing_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_change_before_the_fill_leaves_it_off_and_names_the_page", "crates/edit/src/backdrop_tests.rs::a_fill_that_would_cover_content_painted_before_it_stays_off", "crates/engine/src/tests.rs::remove_background_names_the_pages_whose_own_backdrop_stays_off", "crates/automation/tests/it/backdrop.rs::removed_text_leaves_the_file_when_a_background_replaced_the_pages_backdrop", "crates/edit/src/mark_transaction_tests.rs::background_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"]
|
||||
notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). Remove also turns back on a page backdrop Add replaced, keeping edits made after it; where that isn't safe it says which pages keep it off"
|
||||
|
||||
[[feature]]
|
||||
id = "edit.decoration-profiles"
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+123
-2
@@ -4,6 +4,7 @@ use crate::crypto::{DecryptionError, DecryptionTarget, Decryptor, get};
|
||||
use crate::data::Data;
|
||||
use crate::metadata::Metadata;
|
||||
use crate::object::Name;
|
||||
use crate::object::Number;
|
||||
use crate::object::ObjectIdentifier;
|
||||
use crate::object::Stream;
|
||||
use crate::object::dict::keys::{
|
||||
@@ -80,6 +81,65 @@ pub(crate) fn fallback(data: PdfData, password: &[u8]) -> Option<XRef> {
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch: an `N G obj` header for the repair scan, taking a generation number that
|
||||
/// cannot be read as 0.
|
||||
///
|
||||
/// A generation number is at most 65,535 (ISO 32000-2 §7.5.4), so `3 18446744073709551616 obj` is
|
||||
/// malformed and [`ObjectIdentifier::read`] is right to refuse it everywhere else. This scan runs
|
||||
/// only when a file's cross-reference table is unusable and its objects are being recovered by
|
||||
/// reading the file, where refusing the header drops the object and whatever it holds (#5580).
|
||||
/// Before #427 the digits wrapped, and 2^64 wrapped to exactly 0, which is the only reason such a
|
||||
/// file used to open.
|
||||
///
|
||||
/// Only here: reading numbers anywhere else is unchanged.
|
||||
fn read_object_header<'a>(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<ObjectIdentifier> {
|
||||
let mut strict = r.clone();
|
||||
if let Some(obj_id) = strict.read::<ObjectIdentifier>(ctx) {
|
||||
*r = strict;
|
||||
return Some(obj_id);
|
||||
}
|
||||
// On a clone as well, so a header that isn't one leaves `r` where it was for the caller.
|
||||
let mut lenient = r.clone();
|
||||
let obj_number = lenient.read_without_context::<i32>()?;
|
||||
lenient.skip_white_spaces_and_comments();
|
||||
// Any number at all in the generation position, including one no generation may be.
|
||||
lenient.skip::<Number>(false)?;
|
||||
lenient.skip_white_spaces_and_comments();
|
||||
lenient.forward_tag(b"obj")?;
|
||||
*r = lenient;
|
||||
Some(ObjectIdentifier::new(obj_number, 0))
|
||||
}
|
||||
|
||||
/// PdfCraft patch: the body of the object at `offset` whose `N G obj` header cannot be read
|
||||
/// strictly, for a table rebuilt by scanning the file (#5580). The steps are
|
||||
/// `IndirectObject::read`'s, with [`read_object_header`] in place of the strict identifier.
|
||||
fn read_repaired_body<'a, T>(
|
||||
data: &'a [u8],
|
||||
offset: usize,
|
||||
id: ObjectIdentifier,
|
||||
ctx: &ReaderContext<'a>,
|
||||
) -> Option<T>
|
||||
where
|
||||
T: ObjectLike<'a>,
|
||||
{
|
||||
let mut r = Reader::new(data);
|
||||
r.jump(offset);
|
||||
// The number is what identifies the object; the generation is what could not be read.
|
||||
if read_object_header(&mut r, ctx)?.obj_number != id.obj_number {
|
||||
return None;
|
||||
}
|
||||
let mut ctx = ctx.clone();
|
||||
if ctx.parent_chain_contains(&id) {
|
||||
warn!("cycle detected in indirect object: {id:?}");
|
||||
|
||||
return None;
|
||||
}
|
||||
ctx.set_obj_number(id);
|
||||
ctx.parent_chain_push(id);
|
||||
r.skip_white_spaces_and_comments();
|
||||
r.read_with_context::<T>(&ctx)
|
||||
}
|
||||
|
||||
fn fallback_xref_map<'a>(data: &'a PdfData, password: &[u8]) -> (XrefMap, Option<XRefInput<'a>>) {
|
||||
fallback_xref_map_inner(data, ReaderContext::dummy(), true, password)
|
||||
}
|
||||
@@ -91,6 +151,10 @@ fn fallback_xref_map_inner<'a>(
|
||||
password: &[u8],
|
||||
) -> (XrefMap, Option<XRefInput<'a>>) {
|
||||
let mut xref_map = FxHashMap::default();
|
||||
// PdfCraft patch: the generation-0 keys below that stand in for a header with another
|
||||
// generation, so a later header can replace one while a real `N 0 obj` is never displaced
|
||||
// (noted in review of #5580).
|
||||
let mut aliases: rustc_hash::FxHashSet<ObjectIdentifier> = rustc_hash::FxHashSet::default();
|
||||
let mut trailer_dicts = vec![];
|
||||
let mut root_ref = None;
|
||||
|
||||
@@ -105,12 +169,32 @@ fn fallback_xref_map_inner<'a>(
|
||||
|
||||
// First try to check if we have an object identifier.
|
||||
if r.peek_byte().is_some_and(|b: u8| b.is_ascii_digit()) {
|
||||
if let Some(obj_id) = r.read::<ObjectIdentifier>(&dummy_ctx) {
|
||||
if let Some(obj_id) = read_object_header(&mut r, &dummy_ctx) {
|
||||
let mut cloned = r.clone();
|
||||
// Check that the object following it is actually valid before inserting it.
|
||||
cloned.skip_white_spaces_and_comments();
|
||||
if cloned.skip::<Object<'_>>(false).is_some() {
|
||||
xref_map.insert(obj_id, EntryType::Normal(cur_pos));
|
||||
// PdfCraft patch: also reachable by object number alone, so a reference that
|
||||
// names a different generation than the header still finds it. A rebuilt
|
||||
// table has no revision history to tell two generations apart, and a file
|
||||
// that needs rebuilding references everything as `N 0 R` whatever its headers
|
||||
// say: `poppler-85140-0.pdf` has one page whose header reads
|
||||
// `3 18446744073709551616 obj` with a page tree pointing at `3 0 R`, so the
|
||||
// page was lost and the file did not open at all (#5580). `or_insert`, so a
|
||||
// real `N 0 obj` is never displaced by this alias.
|
||||
let by_number = ObjectIdentifier::new(obj_id.obj_number, 0);
|
||||
if obj_id.gen_number == 0 {
|
||||
// A real `N 0 obj`: it owns the key from here on, and the last one wins
|
||||
// as every other entry does.
|
||||
aliases.remove(&by_number);
|
||||
} else if !xref_map.contains_key(&by_number) || aliases.contains(&by_number) {
|
||||
// Stand in for it, and let a later header for the same number replace the
|
||||
// stand-in -- the exact key moves on, so an alias left behind would send
|
||||
// `N 0 R` to a body the exact key no longer names (noted in review).
|
||||
xref_map.insert(by_number, EntryType::Normal(cur_pos));
|
||||
aliases.insert(by_number);
|
||||
}
|
||||
last_obj_num = Some(obj_id);
|
||||
dummy_ctx.set_obj_number(obj_id);
|
||||
}
|
||||
@@ -498,6 +582,14 @@ impl XRef {
|
||||
// Try to yield in the order the objects appeared in the
|
||||
// PDF.
|
||||
elements.sort_by(|e1, e2| e1.1.cmp(&e2.1));
|
||||
// PdfCraft patch: one object per location. A rebuilt table can hold two keys for
|
||||
// one object -- its own generation and the generation-0 stand-in (#5580) -- and
|
||||
// enumeration yielded the object once for each, so a document recovered by
|
||||
// `Pages::new_brute_force` reported the page twice (noted in review). Both keys
|
||||
// stay for lookups; only this walk is deduplicated. The object number is part of
|
||||
// the key: an object stream at (offset, 0) and its first member, also
|
||||
// (offset, 0), are two objects.
|
||||
elements.dedup_by(|a, b| a.1 == b.1 && a.0.obj_number == b.0.obj_number);
|
||||
|
||||
let mut iter = elements.into_iter();
|
||||
|
||||
@@ -653,10 +745,27 @@ impl XRef {
|
||||
}
|
||||
|
||||
if let Some(object) = r.read_with_context::<IndirectObject<T>>(&ctx) {
|
||||
if object.id() == &id {
|
||||
// PdfCraft patch: in a table rebuilt by scanning the file, the object number
|
||||
// is what identifies an object. There is no revision history to tell two
|
||||
// generations apart, the scan already files objects found in object streams
|
||||
// under generation 0, and a malformed generation in a header would otherwise
|
||||
// make the object unreadable through the reference that names it (#5580). A
|
||||
// table read from the file's own xref keeps the exact match.
|
||||
if object.id() == &id || (repaired && object.id().obj_number == id.obj_number) {
|
||||
return Some(Fetched::Object(object.get()));
|
||||
}
|
||||
} else {
|
||||
// PdfCraft patch: the strict read of the header failed. In a table rebuilt by
|
||||
// scanning the file that can be a generation number no generation may be --
|
||||
// `3 18446744073709551616 obj` -- and refusing it loses the object the
|
||||
// reference names (#5580). The object number still has to be the one asked
|
||||
// for; only an unreadable generation is tolerated, and only here.
|
||||
if repaired
|
||||
&& let Some(object) =
|
||||
read_repaired_body::<T>(repr.data.get().as_ref(), offset, id, &ctx)
|
||||
{
|
||||
return Some(Fetched::Object(object));
|
||||
}
|
||||
// There is a valid object at the offset, it's just not of the type the caller
|
||||
// expected, which is fine.
|
||||
if r.skip::<IndirectObject<Object<'_>>>(false).is_some() {
|
||||
@@ -1734,6 +1843,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_stream_and_its_first_member_are_both_enumerated() {
|
||||
// Both sit at (stream offset, 0) in `objects`' ordering; one object per location must
|
||||
// not cost either of them.
|
||||
let pdf = crate::Pdf::new(object_stream_fixture(false)).unwrap();
|
||||
let objects: Vec<_> = pdf.xref().objects().into_iter().collect();
|
||||
assert!(objects.iter().any(|o| matches!(o, Object::Stream(_))));
|
||||
assert!(objects.iter().any(
|
||||
|o| matches!(o, Object::Dict(d) if d.get::<i32>(b"Marker") == Some(123))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_object_stream_locations_fail_without_recursing() {
|
||||
let pdf = crate::Pdf::new(object_stream_fixture(true)).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user