mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-27 03:28:46 +00:00
Merge branch 'main' into port-2081
This commit is contained in:
@@ -5,3 +5,11 @@ xtask = "run -p xtask --"
|
||||
# engine's kernels (rten-simd) and other vectorised code only use it when compiled in.
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = ["-C", "target-feature=+simd128"]
|
||||
|
||||
# aws-lc (digital signatures and TLS, through aws-lc-rs) detects the CPU when `main` asks it to
|
||||
# (`pdfcraft_sign::init_crypto`), not in a static initializer before `main`. On x86 it reads
|
||||
# `OPENSSL_ia32cap` then, and aborts when that asks for a feature the processor lacks; each
|
||||
# executable first runs itself again without the variable (#2916, `pdfcraft_platform::crypto_env`),
|
||||
# which it can only do once `main` runs.
|
||||
[env]
|
||||
AWS_LC_SYS_CFLAGS = "-DBORINGSSL_NO_STATIC_INITIALIZER"
|
||||
|
||||
@@ -24,52 +24,8 @@ jobs:
|
||||
# The shared gate doesn't check where git dependencies come from; release.yml runs the same job.
|
||||
git-sources:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Windows font notice regressions
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-font-notices.ps1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main
|
||||
|
||||
gate:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
> **Last reviewed:** 2026-11-07 | **Last updated:** 2026-11-07 | **Change:** patch (M10: file-backed Windows PDF loading without whole-job buffering or per-chunk async waits; approved dependency chain retains #5006; physical output still unqualified; estimates unchanged)
|
||||
> **Last reviewed:** 2026-11-05 | **Last updated:** 2026-11-05 | **Change:** patch (M7 #2964: directly edit Thai source text inside supported Form XObjects; estimates unchanged)
|
||||
> **Last reviewed:** 2026-11-05 | **Last updated:** 2026-11-05 | **Change:** minor (M3, #5452: native Recent rows gain Reveal in Finder / File Explorer; estimates unchanged)
|
||||
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged)
|
||||
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** minor (M3/M4, #5330: Crop pages is directly available in the document quick toolbar; estimates unchanged)
|
||||
|
||||
@@ -98,6 +98,13 @@ help and feedback: https://discord.gg/artcraft"
|
||||
);
|
||||
|
||||
fn main() -> ExitCode {
|
||||
// Before anything uses aws-lc: an `OPENSSL_ia32cap` naming a CPU feature this processor lacks
|
||||
// would stop it, so the CLI runs again without it (#2916, `pdfcraft_platform::crypto_env`).
|
||||
if let Some(code) = pdfcraft_platform::crypto_env::run_without_cpu_override() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
// aws-lc detects the CPU's features here, where it used to before `main` (`init_crypto`).
|
||||
pdfcraft_engine::sign::init_crypto();
|
||||
// `std::env::args` panics on an argument that is not UTF-8 ("called `Result::unwrap()` on an
|
||||
// `Err` value"), which a Latin-1 file name is, and it panics while collecting them: even
|
||||
// `--help` ended that way. Such a name cannot be passed on either, since the paths here are
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! An `OPENSSL_ia32cap` that asks for a CPU feature the processor lacks stops neither the CLI nor
|
||||
//! its signing (#2916). aws-lc printed "Fatal Error: HW capability found: …" and aborted before
|
||||
//! `main`. Built to detect the CPU on first use, it would abort at the first signature instead.
|
||||
|
||||
// macOS intentionally does not relaunch: Finder delivers files to the original process.
|
||||
#![cfg(not(target_os = "macos"))]
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
/// CPUID leaf 1, EDX bit 10: reserved, so no x86 processor reports it.
|
||||
const MISSING_FEATURE: &str = "0x400";
|
||||
|
||||
fn run(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_pdfcraft-cli")).args(args).env("OPENSSL_ia32cap", MISSING_FEATURE).output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cpu_override_naming_a_missing_feature_stops_neither_the_cli_nor_signing() {
|
||||
let out = run(&["--help"]);
|
||||
assert!(out.status.success(), "--help: {:?} {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("pdfcraft-cli render"));
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-cli-cpu-override-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// A new RSA key: the CLI's first use of aws-lc.
|
||||
let id = dir.join("id.p12");
|
||||
let path = format!("path={}", id.display());
|
||||
let out = run(&["run", "sign_id_create", "name=Test", "password=correct horse", &path, "--root", dir.to_str().unwrap()]);
|
||||
assert!(out.status.success(), "sign_id_create: {:?} {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
assert!(std::fs::metadata(&id).is_ok_and(|m| m.len() > 0), "no digital ID at {}", id.display());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ mod automation_roots;
|
||||
mod batch;
|
||||
mod batch_exit;
|
||||
mod check;
|
||||
mod cpu_override;
|
||||
mod edit;
|
||||
mod extract;
|
||||
mod help;
|
||||
|
||||
@@ -201,6 +201,13 @@ fn rejoin_split_paths(args: Vec<String>, exists: impl Fn(&str) -> bool) -> Vec<S
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// Before anything uses aws-lc: an `OPENSSL_ia32cap` naming a CPU feature this processor lacks
|
||||
// would stop it, so PdfCraft runs again without it (#2916, `crypto_env`).
|
||||
if let Some(code) = pdfcraft_platform::crypto_env::run_without_cpu_override() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
// aws-lc detects the CPU's features here, where it used to before `main` (`init_crypto`).
|
||||
pdfcraft_engine::sign::init_crypto();
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
@@ -208,6 +215,10 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
// First, so the panic hook and every start-up warning are recorded (`logging`).
|
||||
let logger = logging::install();
|
||||
if let Some(value) = pdfcraft_platform::crypto_env::dropped() {
|
||||
let name = pdfcraft_platform::crypto_env::IA32CAP;
|
||||
log::warn!("{name} was set to {value}; PdfCraft started again without it (aws-lc stops on a CPU feature the processor lacks)");
|
||||
}
|
||||
// Last-resort guard (AGENTS.md §4): commands, edits, opens and saves catch panics and report
|
||||
// them; this hook logs every panic, caught or not, with a backtrace when RUST_BACKTRACE is set.
|
||||
std::panic::set_hook(Box::new(|info| {
|
||||
|
||||
@@ -8,7 +8,12 @@ const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft");
|
||||
|
||||
/// Run the app with `args`, failing if it is still running after 60 s (it opened its window).
|
||||
fn run(args: &[&str], stdout: Stdio) -> Output {
|
||||
let mut child = Command::new(BIN).args(args).stdin(Stdio::null()).stdout(stdout).stderr(Stdio::piped()).spawn().unwrap();
|
||||
run_with(Command::new(BIN).args(args), stdout)
|
||||
}
|
||||
|
||||
fn run_with(command: &mut Command, stdout: Stdio) -> Output {
|
||||
let args: Vec<_> = command.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
|
||||
let mut child = command.stdin(Stdio::null()).stdout(stdout).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() > deadline {
|
||||
@@ -42,6 +47,18 @@ fn version_prints_the_version_and_exits() {
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("pdfcraft "), "{}", String::from_utf8_lossy(&out.stdout));
|
||||
}
|
||||
|
||||
/// An `OPENSSL_ia32cap` that asks for a CPU feature the processor lacks (CPUID leaf 1, EDX bit
|
||||
/// 10, reserved on every x86) doesn't stop the app (#2916): aws-lc aborted before `main`, with no
|
||||
/// window and nothing in the log.
|
||||
// macOS intentionally does not relaunch: Finder delivers files to the original process.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_cpu_override_naming_a_missing_feature_does_not_stop_the_app() {
|
||||
let out = run_with(Command::new(BIN).arg("--version").env("OPENSSL_ia32cap", "0x400"), Stdio::piped());
|
||||
assert!(out.status.success(), "{:?} {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("pdfcraft "), "{}", String::from_utf8_lossy(&out.stdout));
|
||||
}
|
||||
|
||||
/// A standard output that can't be written (here a full device) ends the run normally: `println!`
|
||||
/// would panic and exit 101.
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! A lone `+` or `++` is accepted by `hayro-syntax`'s first pass over a dictionary or array,
|
||||
//! which skips it as a number, but no number is read from it. Such an entry is unreadable, like
|
||||
//! any other malformed value: a dictionary leaves it out and keeps its other entries, and an
|
||||
//! array reads it as null in its slot (vendor patch (46)). Before, `Dict::entries` and
|
||||
//! `Array::raw_iter` (and `Dict`'s `Debug`) unwrapped the failed read and panicked, and `Array::iter` ended at the
|
||||
//! token, dropping the items after it. Sign runs a number is read from (`-` reads as 0) keep
|
||||
//! reading as before.
|
||||
|
||||
use hayro_syntax::object::{Array, Dict, FromBytes, MaybeRef, Number, Object};
|
||||
|
||||
/// Sign-only tokens, and two of them in a row.
|
||||
const SIGN_TOKENS: [&str; 8] = ["+", "++", "-", "--", "+-", "-+", "+ -", "+ +"];
|
||||
|
||||
/// The lone signs the first pass accepts: a dictionary or array holding one must still parse.
|
||||
fn must_parse(tok: &str) -> bool {
|
||||
matches!(tok, "+" | "++")
|
||||
}
|
||||
|
||||
/// Whether no number is read from this sign run, so it is the unreadable kind.
|
||||
fn unreadable(sign: &str) -> bool {
|
||||
Number::from_bytes(sign.as_bytes()).is_none()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dictionary_leaves_out_an_entry_made_only_of_signs() {
|
||||
for tok in SIGN_TOKENS {
|
||||
let src = format!("<< /A {tok} /B 7 >>");
|
||||
let Some(dict) = Dict::from_bytes(src.as_bytes()) else {
|
||||
// Refused as a whole, as other unreadable dictionaries are: nothing to iterate.
|
||||
assert!(!must_parse(tok), "{src} was refused");
|
||||
continue;
|
||||
};
|
||||
let entries: Vec<_> = dict.entries().map(|(k, _)| k.as_str().to_owned()).collect();
|
||||
let a = dict.get::<Object<'_>>("A");
|
||||
if unreadable(tok) {
|
||||
assert_eq!(entries, ["B"], "{src}");
|
||||
assert!(a.is_none(), "{src}");
|
||||
} else {
|
||||
assert_eq!(entries, ["A", "B"], "{src}");
|
||||
assert!(matches!(a, Some(Object::Number(_))), "{src}: {a:?}");
|
||||
}
|
||||
assert_eq!(dict.get::<i32>("B"), Some(7), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_reads_a_token_made_only_of_signs_as_null_in_its_slot() {
|
||||
for tok in SIGN_TOKENS {
|
||||
let src = format!("[0 {tok} 7]");
|
||||
let Some(array) = Array::from_bytes(src.as_bytes()) else {
|
||||
assert!(!must_parse(tok), "{src} was refused");
|
||||
continue;
|
||||
};
|
||||
let signs = tok.split_whitespace().count();
|
||||
let raw: Vec<_> = array.raw_iter().collect();
|
||||
let items: Vec<_> = array.iter::<Object<'_>>().collect();
|
||||
assert_eq!(raw.len(), signs + 2, "{src}");
|
||||
assert_eq!(items.len(), signs + 2, "{src}");
|
||||
assert_eq!(items.first().and_then(|o| o.clone().into_i32()), Some(0), "{src}");
|
||||
assert_eq!(items.last().and_then(|o| o.clone().into_i32()), Some(7), "{src}");
|
||||
for ((item, raw), sign) in items.iter().zip(raw.iter()).skip(1).zip(tok.split_whitespace()) {
|
||||
if unreadable(sign) {
|
||||
assert!(matches!(item, Object::Null(_)), "{src}: {item:?}");
|
||||
assert!(matches!(raw, MaybeRef::NotRef(Object::Null(_))), "{src}: raw {raw:?}");
|
||||
} else {
|
||||
assert!(matches!(item, Object::Number(_)), "{src}: {item:?}");
|
||||
assert!(matches!(raw, MaybeRef::NotRef(Object::Number(_))), "{src}: raw {raw:?}");
|
||||
}
|
||||
}
|
||||
// A typed read still stops at a slot that is not a number, as at any other value.
|
||||
let numbers_before = 1 + tok.split_whitespace().take_while(|sign| !unreadable(sign)).count();
|
||||
let expected = if numbers_before == signs + 1 { signs + 2 } else { numbers_before };
|
||||
assert_eq!(array.iter::<f32>().count(), expected, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed read that stops at an unreadable slot leaves the slot in place, as at a value of
|
||||
/// another type, so the caller can read it as an object and go on to the items after it.
|
||||
#[test]
|
||||
fn a_failed_typed_read_leaves_the_unreadable_slot_in_place() {
|
||||
for (src, stop) in [("[0 + 7]", "+"), ("[0 /N 7]", "/N")] {
|
||||
let array = Array::from_bytes(src.as_bytes()).unwrap_or_else(|| panic!("{src} parses"));
|
||||
let mut iter = array.flex_iter();
|
||||
assert_eq!(iter.next::<f32>(), Some(0.0), "{src}");
|
||||
assert_eq!(iter.next::<f32>(), None, "{src}: {stop} is not a number");
|
||||
let slot = iter.next::<Object<'_>>();
|
||||
if stop == "+" {
|
||||
assert!(matches!(slot, Some(Object::Null(_))), "{src}: {slot:?}");
|
||||
} else {
|
||||
assert!(matches!(slot, Some(Object::Name(_))), "{src}: {slot:?}");
|
||||
}
|
||||
assert_eq!(iter.next::<f32>(), Some(7.0), "{src}");
|
||||
assert_eq!(iter.next::<f32>(), None, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every token of up to five characters over signs, digits, `.` and `e` that starts with a
|
||||
/// sign, in each position a value can take, iterates without panicking, and an array never
|
||||
/// loses the item after it.
|
||||
#[test]
|
||||
fn short_sign_led_tokens_never_panic_in_a_dictionary_or_array() {
|
||||
const ALPHABET: &[u8] = b"+-1.e ";
|
||||
let mut checked = 0usize;
|
||||
let mut tok = Vec::new();
|
||||
for len in 1..=5u32 {
|
||||
let total = ALPHABET.len().pow(len);
|
||||
for code in 0..total {
|
||||
tok.clear();
|
||||
let mut k = code;
|
||||
for _ in 0..len {
|
||||
tok.push(ALPHABET.get(k % ALPHABET.len()).copied().unwrap_or(b' '));
|
||||
k /= ALPHABET.len();
|
||||
}
|
||||
if !matches!(tok.first(), Some(b'+' | b'-')) || tok.last() == Some(&b' ') {
|
||||
continue;
|
||||
}
|
||||
let tok = std::str::from_utf8(&tok).unwrap_or_default().to_owned();
|
||||
checked += 1;
|
||||
for src in [format!("[{tok}]"), format!("[0 {tok} 7]"), format!("<< /A {tok} /B 7 >>")] {
|
||||
let outcome = std::panic::catch_unwind(|| {
|
||||
if src.starts_with('[') {
|
||||
Array::from_bytes(src.as_bytes()).map(|a| {
|
||||
let _ = format!("{a:?}");
|
||||
let raw = a.raw_iter().count();
|
||||
let items: Vec<_> = a.iter::<Object<'_>>().collect();
|
||||
(raw, items.len(), items.last().and_then(|o| o.clone().into_i32()))
|
||||
})
|
||||
} else {
|
||||
Dict::from_bytes(src.as_bytes()).map(|d| {
|
||||
let _ = format!("{d:?}");
|
||||
let entries = d.entries().count();
|
||||
let _ = d.get::<Object<'_>>("A");
|
||||
(entries, entries, d.get::<i32>("B"))
|
||||
})
|
||||
}
|
||||
});
|
||||
let Ok(result) = outcome else {
|
||||
panic!("{src:?} panicked");
|
||||
};
|
||||
let Some((raw, items, last)) = result else {
|
||||
continue;
|
||||
};
|
||||
if src.starts_with('[') {
|
||||
assert_eq!(raw, items, "{src:?}: raw_iter and iter disagree");
|
||||
if src.starts_with("[0 ") {
|
||||
assert_eq!(last, Some(7), "{src:?}: the item after the token was lost");
|
||||
}
|
||||
} else {
|
||||
assert_eq!(last, Some(7), "{src:?}: /B was lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Two leading signs, then 6^(len-2) middles and 5 last characters (no trailing space).
|
||||
assert_eq!(checked, 2 + 2 * 5 + 2 * 6 * 5 + 2 * 36 * 5 + 2 * 216 * 5);
|
||||
// A sign-led number still reads as one.
|
||||
assert_eq!(Number::from_bytes(b"+1").map(|n| n.as_f64()), Some(1.0));
|
||||
}
|
||||
@@ -14227,7 +14227,8 @@ fn reset_order_session(reset: &str) -> (Session, DocId) {
|
||||
})
|
||||
.unwrap();
|
||||
let bytes = Arc::new(pdfcraft_cos::write_full(&cos, &Default::default()).unwrap());
|
||||
let mut s = Session::new();
|
||||
// Callers compare two saves byte for byte, and each save stamps `/ModDate`: pin the clock.
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
s.set_javascript(false);
|
||||
let id = s.open("reset-order.pdf", None, bytes, None).unwrap();
|
||||
s.apply(
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! A form edit reads the document's fields once, however many the form holds: filling,
|
||||
//! recalculating, the XFA data and the view each read them, mostly with nothing changed since
|
||||
//! the step before, and on a form with a thousand fields each reading takes tens of milliseconds.
|
||||
//! Counted, not timed: `form_reads_on_this_thread` counts the whole-form walks this thread made.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_engine::{DocId, Edit, FieldValue, Session};
|
||||
use pdfcraft_forms::form_reads_on_this_thread as form_reads;
|
||||
|
||||
/// An AcroForm of `n` text fields `f0`…, fifty to a page.
|
||||
fn acroform(n: usize) -> Vec<u8> {
|
||||
let pages = n.div_ceil(50).max(1);
|
||||
let first_page = 5;
|
||||
let first_field = first_page + pages;
|
||||
let refs = |from: usize, count: usize| (from..from + count).map(|i| format!("{i} 0 R")).collect::<Vec<_>>().join(" ");
|
||||
let mut objs = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 3 0 R >>".to_string(),
|
||||
format!("<< /Type /Pages /Kids [{}] /Count {pages} /MediaBox [0 0 612 792] >>", refs(first_page, pages)),
|
||||
format!("<< /Fields [{}] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 4 0 R >> >> >>", refs(first_field, n)),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
|
||||
];
|
||||
for p in 0..pages {
|
||||
let count = 50.min(n - p * 50);
|
||||
objs.push(format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", refs(first_field + p * 50, count)));
|
||||
}
|
||||
for i in 0..n {
|
||||
let (page, row) = (i / 50, i % 50);
|
||||
let y = 760 - 15 * row;
|
||||
objs.push(format!(
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (f{i}) /TU (Field {i}) /Rect [40 {} 300 {y}] /P {} 0 R /F 4 >>",
|
||||
y - 12,
|
||||
first_page + page
|
||||
));
|
||||
}
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// Fill `name` with `value`, returning how many times the fields were read for it.
|
||||
fn fill(s: &mut Session, id: DocId, name: &str, value: &str) -> usize {
|
||||
let before = form_reads();
|
||||
s.apply(id, Edit::SetFieldValue { name: name.into(), value: FieldValue::Text(value.into()) }).unwrap();
|
||||
form_reads() - before
|
||||
}
|
||||
|
||||
fn value(s: &Session, id: DocId, name: &str) -> Vec<String> {
|
||||
s.get(id).unwrap().form.iter().find(|f| f.name == name).unwrap().value.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_form_edit_reads_the_fields_once_however_many_the_form_holds() {
|
||||
for n in [20, 600] {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("form.pdf", None, Arc::new(acroform(n)), None).unwrap();
|
||||
for k in 0..3 {
|
||||
let name = format!("f{k}");
|
||||
assert_eq!(fill(&mut s, id, &name, &format!("value {k}")), 1, "{n} fields, edit {k}");
|
||||
assert_eq!(value(&s, id, &name), [format!("value {k}")]);
|
||||
}
|
||||
let shown = |s: &Session| s.get(id).unwrap().info.fields.iter().find(|f| f.name == "f2").and_then(|f| f.value.clone());
|
||||
assert_eq!(shown(&s).as_deref(), Some("value 2"));
|
||||
// Undo and redo read the restored state once each, and show it.
|
||||
let before = form_reads();
|
||||
s.undo(id).unwrap();
|
||||
assert!(value(&s, id, "f2").is_empty());
|
||||
assert_eq!(shown(&s), None);
|
||||
s.redo(id).unwrap();
|
||||
assert_eq!(value(&s, id, "f2"), ["value 2"]);
|
||||
assert!(form_reads() - before <= 2, "{n} fields: undo and redo read {} times", form_reads() - before);
|
||||
// The same value again changes nothing and still reads the form at most once.
|
||||
assert!(fill(&mut s, id, "f2", "value 2") <= 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// A laid-out XFA form keeps its data in step with the fields as well: the edit reads them
|
||||
/// once to fill and once after its data is written (its scripts read the fields), however many
|
||||
/// fields the form holds.
|
||||
#[test]
|
||||
fn an_xfa_form_edit_reads_the_fields_a_fixed_number_of_times() {
|
||||
let mut counts = Vec::new();
|
||||
for rows in [2, 60] {
|
||||
let mut s = Session::new();
|
||||
let xdp = pdfcraft_xfa::fixtures::template(rows);
|
||||
let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&xdp)), None).unwrap();
|
||||
let name = s.get(id).unwrap().form.iter().find(|f| f.name.contains("familyName")).unwrap().name.clone();
|
||||
let fields = s.get(id).unwrap().form.len();
|
||||
let reads: Vec<usize> = (0..3).map(|k| fill(&mut s, id, &name, &format!("Name {k}"))).collect();
|
||||
assert_eq!(value(&s, id, &name), ["Name 2"]);
|
||||
counts.push((fields, reads));
|
||||
}
|
||||
let [(small, a), (large, b)] = counts.as_slice() else { panic!("{counts:?}") };
|
||||
assert!(large > small, "{counts:?}");
|
||||
assert_eq!(a, b, "{counts:?}");
|
||||
assert!(a.iter().all(|&r| r <= 2), "{counts:?}");
|
||||
}
|
||||
@@ -39,6 +39,12 @@ let cells: Vec<table::Cell> = grid.cells_for(names)?; // "Table1_1", "Table
|
||||
|
||||
## Behaviour
|
||||
|
||||
- `fields` and `fields_with_adopted` keep their last reading on each thread with the state of the
|
||||
document it read (`pdfcraft_cos::ReadState`, which any change to the document replaces), and
|
||||
give a copy of it to a document that still reads as that state. A form edit reads the fields in
|
||||
several steps (filling, recalculating, the XFA data, the view), most with nothing changed in
|
||||
between, so it walks a form once (twice on a laid-out XFA form, whose data is written in
|
||||
between); `form_reads_on_this_thread` counts the walks, for tests.
|
||||
- Inheritable attributes (`/FT`, `/Ff`, `/V`, `/DV`, `/DA`, `/Q`, `/MaxLen`) are resolved down the
|
||||
field tree; the form's `/DA` and `/Q` are the last fallback.
|
||||
- Text and choice fields get new appearance streams (`/Tx BMC … EMC`): auto-size (`0 Tf`), comb
|
||||
|
||||
@@ -326,7 +326,15 @@ impl FontText {
|
||||
match self {
|
||||
Self::WinAnsi => pdfcraft_fonts::first_undrawable(s),
|
||||
Self::Simple(metrics) => {
|
||||
s.chars().map(|c| if c == '\t' { ' ' } else { c }).find(|c| metrics.encode(c.encode_utf8(&mut [0; 4])).is_none())
|
||||
// A whole string that encodes has no such character, in one pass over the font's
|
||||
// ranges. Otherwise each distinct character is asked once (a call scans every range).
|
||||
if metrics.encode(&s.replace('\t', " ")).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut held = std::collections::HashSet::new();
|
||||
s.chars()
|
||||
.map(|c| if c == '\t' { ' ' } else { c })
|
||||
.find(|c| !held.contains(c) && !(metrics.encode(c.encode_utf8(&mut [0; 4])).is_some() && held.insert(*c)))
|
||||
}
|
||||
Self::Unicode(cmap) => cmap.first_unencodable(s),
|
||||
}
|
||||
@@ -1244,4 +1252,19 @@ mod tests {
|
||||
// When empty selection:
|
||||
assert_eq!(ListRows::top_showing(0, &[], 3, 5), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_unencodable_finds_the_first_character_the_simple_font_cannot_hold() {
|
||||
let doc = Document::new_empty();
|
||||
let mut f = Dict::new();
|
||||
f.set(b"Type".to_vec(), Object::name("Font"));
|
||||
f.set(b"Subtype".to_vec(), Object::name("Type1"));
|
||||
f.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
|
||||
f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
let font = FontText::Simple(Box::new(Metrics::from_dict(&doc, &f)));
|
||||
assert_eq!(font.first_unencodable("h\u{e9}llo\tw\u{e9}rld"), None);
|
||||
assert_eq!(font.first_unencodable(&"a\u{e9}".repeat(1000)), None);
|
||||
assert_eq!(font.first_unencodable("ab\u{3a9}c\u{3a8}"), Some('\u{3a9}'));
|
||||
assert_eq!(font.first_unencodable(""), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,9 +43,9 @@ mod values;
|
||||
pub use appearances::{FieldAppearanceCache, declares_pdfa, need_appearances, undrawn_fields, with_field_appearances, with_field_appearances_cached};
|
||||
pub(crate) use read::page_refs;
|
||||
pub use read::selected_options;
|
||||
pub use read::{Fields, acroform, adopted_page_fields, fields, fields_with_adopted};
|
||||
pub use read::{Fields, acroform, adopted_page_fields, fields, fields_with_adopted, form_reads_on_this_thread};
|
||||
#[cfg(test)]
|
||||
use read::{MAX_SCRIPT_BYTES, PageWalk, enumerate, form_reads};
|
||||
use read::{MAX_SCRIPT_BYTES, PageWalk, enumerate, form_reads_on_this_thread as form_reads};
|
||||
use read::{first_by_export, qualified_name, script, script_budget};
|
||||
pub use tab_order::{TabOrder, move_in_tab_order, set_tab_order, tab_orders};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -407,26 +407,53 @@ pub struct Fields {
|
||||
}
|
||||
|
||||
/// Read all terminal fields and the page-only adoption count in one enumeration.
|
||||
///
|
||||
/// The last reading on this thread is kept with the state of the document it read
|
||||
/// ([`pdfcraft_cos::ReadState`], which every change to the document replaces), and a document
|
||||
/// that still reads as that state gets a copy of it instead of a new walk. One form edit reads
|
||||
/// the fields in several steps (filling, recalculating, the XFA data, the view), most of them
|
||||
/// with nothing changed since the step before: on a form with a thousand fields each walk takes
|
||||
/// tens of milliseconds.
|
||||
pub fn fields_with_adopted(doc: &Document) -> Fields {
|
||||
let kept = LAST_READING
|
||||
.try_with(|last| match last.try_borrow().as_deref() {
|
||||
Ok(Some((state, fields))) if state.matches(doc) => Some(fields.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.ok()
|
||||
.flatten();
|
||||
if let Some(fields) = kept {
|
||||
return fields;
|
||||
}
|
||||
let (items, adopted_page_fields) = enumerate(doc);
|
||||
Fields { items, adopted_page_fields }
|
||||
let fields = Fields { items, adopted_page_fields };
|
||||
// Not kept (the thread is ending, or the slot is in use) costs only a later walk.
|
||||
let _ = LAST_READING.try_with(|last| {
|
||||
if let Ok(mut last) = last.try_borrow_mut() {
|
||||
*last = Some((doc.read_state(), fields.clone()));
|
||||
}
|
||||
});
|
||||
fields
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Whole-form readings ([`enumerate`]) on this thread.
|
||||
/// The last [`fields_with_adopted`] on this thread, with the state of the document it read.
|
||||
/// One entry: one form's fields, and the objects that document had changed when it was read.
|
||||
static LAST_READING: std::cell::RefCell<Option<(pdfcraft_cos::ReadState, Fields)>> = const { std::cell::RefCell::new(None) };
|
||||
/// Whole-form walks ([`enumerate`]) on this thread.
|
||||
static FORM_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times this thread has read the whole form.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn form_reads() -> usize {
|
||||
FORM_READS.with(std::cell::Cell::get)
|
||||
/// How many times this thread has walked a whole form: [`fields`] and the readings like it, but
|
||||
/// not one answered from the last reading. Per thread, so tests running in parallel don't count
|
||||
/// each other's; for tests that check how often an edit reads the form.
|
||||
#[doc(hidden)]
|
||||
pub fn form_reads_on_this_thread() -> usize {
|
||||
FORM_READS.try_with(std::cell::Cell::get).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) fn enumerate(doc: &Document) -> (Vec<Field>, usize) {
|
||||
#[cfg(test)]
|
||||
FORM_READS.with(|n| n.set(n.get() + 1));
|
||||
let _ = FORM_READS.try_with(|n| n.set(n.get().saturating_add(1)));
|
||||
let af = acroform(doc);
|
||||
let mut page_of = std::collections::HashMap::new();
|
||||
let mut annot_index = std::collections::HashMap::new();
|
||||
|
||||
@@ -6098,7 +6098,8 @@ fn set_values_reads_the_form_once_not_per_value() {
|
||||
let before = form_reads();
|
||||
assert!(set_values(&mut doc, &again).unwrap().iter().all(Result::is_ok));
|
||||
let reads = form_reads() - before;
|
||||
assert_eq!(reads, 3, "one to fill, one when f0 comes again, one to recalculate");
|
||||
// Filling starts from the reading the check above made, nothing having changed since.
|
||||
assert_eq!(reads, 2, "one when f0 comes again, one to recalculate");
|
||||
}
|
||||
|
||||
/// Redrawing every field of a large form reads the form once, not once per field: a laid out XFA
|
||||
@@ -6129,6 +6130,45 @@ fn redraw_fields_reads_the_form_once_however_many_fields_it_holds() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields of a document that has not changed since they were last read are not read again,
|
||||
/// and any change, a clone's state or another document reads afresh: a form edit reads them in
|
||||
/// several steps, most with nothing changed in between.
|
||||
#[test]
|
||||
fn fields_are_read_again_only_after_the_document_changes() {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(),
|
||||
"<< /Fields [5 0 R] /DA (/Helv 10 Tf 0 g) >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (old) /Rect [50 10 250 30] /P 3 0 R >>".into(),
|
||||
];
|
||||
let value = |doc: &Document| field(&fields(doc), "name").value.clone();
|
||||
let mut doc = document(&objs);
|
||||
let before = form_reads();
|
||||
assert_eq!(value(&doc), ["old"]);
|
||||
assert_eq!(value(&doc), ["old"]);
|
||||
assert_eq!(fields_with_adopted(&doc).items, fields(&doc));
|
||||
assert_eq!(form_reads() - before, 1, "nothing changed: read once");
|
||||
let unchanged = doc.clone();
|
||||
doc.update_dict(ObjRef::new(5, 0), |d| d.set(b"V".to_vec(), Object::String(PdfString::text("new")))).unwrap();
|
||||
let before = form_reads();
|
||||
assert_eq!(value(&doc), ["new"], "an edit is read");
|
||||
assert_eq!(value(&unchanged), ["old"], "a copy kept from before it is read as it is");
|
||||
assert_eq!(value(&doc), ["new"]);
|
||||
assert_eq!(form_reads() - before, 3);
|
||||
// An object another field's value refers to counts as a change too.
|
||||
let r = doc.add(Object::String(PdfString::text("indirect")));
|
||||
doc.update_dict(ObjRef::new(5, 0), |d| d.set(b"V".to_vec(), Object::Ref(r))).unwrap();
|
||||
assert_eq!(value(&doc), ["indirect"]);
|
||||
doc.set(r, Object::String(PdfString::text("changed in place")));
|
||||
assert_eq!(value(&doc), ["changed in place"]);
|
||||
// Another document with the same bytes is read, not given this one's fields.
|
||||
let other = document(&objs);
|
||||
let before = form_reads();
|
||||
assert_eq!(value(&other), ["old"]);
|
||||
assert_eq!(form_reads() - before, 1);
|
||||
}
|
||||
|
||||
/// A radio group `size` with the buttons Small (on), Medium and Large, a per-widget `/Opt`, and
|
||||
/// the group's buttons in the calculation order; and a text field `name` with two widgets.
|
||||
fn radio_group_form() -> Document {
|
||||
|
||||
@@ -323,25 +323,43 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg(all(not(target_arch = "wasm32"), not(test)))]
|
||||
static LIVE_WORKERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_DOCUMENT_WORKERS: usize = if usize::BITS == 32 { 4 } else { 16 };
|
||||
/// The count of live document workers that the cap applies to: one per process.
|
||||
#[cfg(all(not(target_arch = "wasm32"), not(test)))]
|
||||
fn live_workers() -> &'static std::sync::atomic::AtomicUsize {
|
||||
&LIVE_WORKERS
|
||||
}
|
||||
/// Unit tests run in parallel threads of one process, so one process-wide count lets
|
||||
/// unrelated tests exhaust the cap together. Each test thread counts its own workers
|
||||
/// instead, against the same cap; the leak is one counter per test thread.
|
||||
#[cfg(all(not(target_arch = "wasm32"), test))]
|
||||
fn live_workers() -> &'static std::sync::atomic::AtomicUsize {
|
||||
thread_local! {
|
||||
static LIVE_WORKERS: &'static std::sync::atomic::AtomicUsize =
|
||||
Box::leak(Box::new(std::sync::atomic::AtomicUsize::new(0)));
|
||||
}
|
||||
LIVE_WORKERS.with(|count| *count)
|
||||
}
|
||||
/// A reservation is released only when its worker exits, including detached timed-out workers.
|
||||
/// It releases the count it was taken from, whichever thread drops it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct WorkerPermit;
|
||||
struct WorkerPermit(&'static std::sync::atomic::AtomicUsize);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl WorkerPermit {
|
||||
/// Reserve bounded address space without evicting another document's retained state.
|
||||
fn acquire() -> Result<Self, String> {
|
||||
use std::sync::atomic::Ordering::SeqCst;
|
||||
let mut live = LIVE_WORKERS.load(SeqCst);
|
||||
let count = live_workers();
|
||||
let mut live = count.load(SeqCst);
|
||||
loop {
|
||||
if live >= MAX_DOCUMENT_WORKERS {
|
||||
return Err("document script worker limit reached; close a scripted document and retry".into());
|
||||
}
|
||||
match LIVE_WORKERS.compare_exchange(live, live.saturating_add(1), SeqCst, SeqCst) {
|
||||
Ok(_) => return Ok(Self),
|
||||
match count.compare_exchange(live, live.saturating_add(1), SeqCst, SeqCst) {
|
||||
Ok(_) => return Ok(Self(count)),
|
||||
Err(current) => live = current,
|
||||
}
|
||||
}
|
||||
@@ -350,7 +368,7 @@ impl WorkerPermit {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Drop for WorkerPermit {
|
||||
fn drop(&mut self) {
|
||||
LIVE_WORKERS.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
|
||||
self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1040,7 +1058,7 @@ mod tests {
|
||||
assert_eq!(session.run(capture, &[]).result.as_deref(), Some("retained"));
|
||||
}
|
||||
|
||||
/// Exercise the actual process-wide cap in isolation, then recover a slot without resetting other documents.
|
||||
/// Exercise the cap in isolation, then recover a slot without resetting other documents.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn document_worker_capacity_is_bounded_and_reusable() {
|
||||
@@ -1064,7 +1082,7 @@ mod tests {
|
||||
assert!(extra.start(job("1")).unwrap_err().contains("worker limit"));
|
||||
drop(workers.pop());
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
|
||||
while LIVE_WORKERS.load(std::sync::atomic::Ordering::SeqCst) == MAX_DOCUMENT_WORKERS {
|
||||
while live_workers().load(std::sync::atomic::Ordering::SeqCst) == MAX_DOCUMENT_WORKERS {
|
||||
assert!(std::time::Instant::now() < deadline);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
|
||||
@@ -10,6 +10,6 @@ The desktop Measure objects panel exposes all three tools, live values and coord
|
||||
|
||||
Snapping interprets painted paths and nested Form XObjects, including graphics-state transforms. Cubic paths are flattened to a maximum deviation of 0.2 user units. Raster edges, glyph outlines, clipping and optional-content visibility are not interpreted. Extraction stops at 8,000,000 segments, 24,000,000 endpoint and midpoint targets, 512 MiB of decoded content, 4,096 streams, 32 nested forms or 256 nested `q`; intersection searches use at most 256 nearby segments. Extraction is lenient: a content stream that can't be decoded is skipped and counted, and the rest of the page still snaps. The UI and automation report these limits.
|
||||
|
||||
Imported single-unit decimal rectilinear scales support differing X and Y conversion factors when CYX is present. Unit labels are text strings and may be non-ASCII ("m²"). Compound units (such as feet and inches), fraction formats and non-rectilinear scales are not supported: `list` reports such measurements, and ones with invalid geometry, under `unsupported` with a reason instead of failing, and leaves their PDF data untouched. A polygon whose last vertex repeats the first is treated as closed. Interoperability with Acrobat-authored measurements is untested. Geospatial and 3D measuring are outside this component.
|
||||
Imported single-unit decimal rectilinear scales support differing X and Y conversion factors when CYX is present. Unit labels are text strings and may be non-ASCII ("m²"). Imported compound units (such as feet and inches, up to 8 units), fractions and values cut off to whole units (ISO 32000-2 §12.9.2 number format arrays) are read too: readings are labelled with them (`3 ft 6 1/2 in`, a last unit that rounds up carrying into the one before) and a measurement added with such a scale writes them back. Authoring them, differing coordinate and distance units, and non-rectilinear scales are not supported: `list` reports such measurements, and ones with invalid geometry, under `unsupported` with a reason instead of failing, and leaves their PDF data untouched. A polygon whose last vertex repeats the first is treated as closed. Interoperability with Acrobat-authored measurements is untested. Geospatial and 3D measuring are outside this component.
|
||||
|
||||
Synthetic tests cover geometry, calibration, viewport precedence, coordinate transforms, saved annotations and captions, snapping targets, cyclic forms, malformed arguments, permissions, undo, save/reopen, rendering and spreadsheet-safe CSV. No sample PDF or font assets are added.
|
||||
|
||||
+85
-35
@@ -3,7 +3,9 @@
|
||||
//! annotations use the measurement intents of line, polygon and polyline annotations (§12.5.6).
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod number_format;
|
||||
pub mod snap;
|
||||
use number_format::{Formats, NumberFormat};
|
||||
use pdfcraft_annot::{Meta, NewAnnotation, Shape, Style};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString};
|
||||
use serde::Serialize;
|
||||
@@ -67,8 +69,17 @@ pub struct Scale {
|
||||
pub distance_factor: f64,
|
||||
pub area_factor: f64,
|
||||
pub area_unit: String,
|
||||
/// Decimal places of a distance. With [`Scale::formats`], those of the last distance unit
|
||||
/// when it shows decimals (0 otherwise); the formats, not this, label the readings.
|
||||
pub precision: u8,
|
||||
pub ratio: String,
|
||||
/// The number format arrays of an imported scale whose units are compound (feet and inches)
|
||||
/// or whose values show as fractions or cut off to whole units (ISO 32000-2 §12.9.2):
|
||||
/// readings are labelled with them, and a measurement added with this scale writes them
|
||||
/// back. `unit`, `area_unit` and the factors are their first units'. `None` for single-unit
|
||||
/// decimal scales, which `unit`, `area_unit` and `precision` describe.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub formats: Option<Formats>,
|
||||
}
|
||||
impl Default for Scale {
|
||||
fn default() -> Self {
|
||||
@@ -81,6 +92,7 @@ impl Default for Scale {
|
||||
area_unit: "in^2".into(),
|
||||
precision: 2,
|
||||
ratio: "1 in = 1 in".into(),
|
||||
formats: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,6 +107,7 @@ impl Scale {
|
||||
area_unit: format!("{unit}^2"),
|
||||
precision,
|
||||
ratio: format!("1 pt = {units_per_user_unit} {unit}"),
|
||||
formats: None,
|
||||
};
|
||||
out.validate()?;
|
||||
Ok(out)
|
||||
@@ -142,6 +155,15 @@ impl Scale {
|
||||
if self.ratio.len() > 256 || self.ratio.chars().any(char::is_control) {
|
||||
return Err(invalid("invalid scale ratio"));
|
||||
}
|
||||
if let Some(formats) = &self.formats {
|
||||
formats.validate().map_err(invalid)?;
|
||||
if formats.y.is_some() {
|
||||
let yf = self.y / formats.cyx;
|
||||
if !yf.is_finite() || !(1e-12..=1e12).contains(&yf) {
|
||||
return Err(invalid("scale factors must be finite and between 1e-12 and 1e12"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn dictionary(&self) -> Result<Dict> {
|
||||
@@ -159,10 +181,34 @@ impl Scale {
|
||||
d.set(b"SS".to_vec(), PdfString::text(""));
|
||||
Object::Array(vec![Object::Dict(d)])
|
||||
};
|
||||
// An imported array is written as read, its first unit given this scale's label and factor.
|
||||
let imported = |formats: &[NumberFormat], unit: &str, factor: f64| {
|
||||
let first = formats.first().map(|f| NumberFormat { unit: unit.into(), factor, ..f.clone() });
|
||||
Object::Array(first.iter().chain(formats.iter().skip(1)).map(NumberFormat::dictionary).collect())
|
||||
};
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Type".to_vec(), Object::name("Measure"));
|
||||
d.set(b"Subtype".to_vec(), Object::name("RL"));
|
||||
d.set(b"R".to_vec(), PdfString::text(&self.ratio));
|
||||
if let Some(f) = &self.formats {
|
||||
d.set(b"X".to_vec(), imported(&f.x, &self.unit, self.x));
|
||||
match &f.y {
|
||||
// Y keeps its own units, and the CYX that converts them to X's.
|
||||
Some(ys) => {
|
||||
let unit = ys.first().map_or(self.unit.as_str(), |f| f.unit.as_str());
|
||||
d.set(b"Y".to_vec(), imported(ys, unit, self.y / f.cyx));
|
||||
d.set(b"CYX".to_vec(), Object::Real(f.cyx));
|
||||
}
|
||||
None if self.x != self.y => {
|
||||
d.set(b"Y".to_vec(), imported(&f.x, &self.unit, self.y));
|
||||
d.set(b"CYX".to_vec(), Object::Real(1.0));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
d.set(b"D".to_vec(), imported(&f.distance, &self.unit, self.distance_factor));
|
||||
d.set(b"A".to_vec(), imported(&f.area, &self.area_unit, self.area_factor));
|
||||
return Ok(d);
|
||||
}
|
||||
d.set(b"X".to_vec(), format(&self.unit, self.x));
|
||||
if self.x != self.y {
|
||||
d.set(b"Y".to_vec(), format(&self.unit, self.y));
|
||||
@@ -172,50 +218,51 @@ impl Scale {
|
||||
d.set(b"A".to_vec(), format(&self.area_unit, self.area_factor));
|
||||
Ok(d)
|
||||
}
|
||||
/// Single-unit decimal scales are editable. Compound/fractional and non-rectilinear
|
||||
/// imports are refused explicitly; their dictionaries and appearance remain untouched.
|
||||
/// Single-unit decimal scales are editable. Compound units (feet and inches), fractions and
|
||||
/// values cut off to whole units read too, keeping their number format arrays in
|
||||
/// [`Scale::formats`] (ISO 32000-2 §12.9.2). Non-rectilinear scales and formats that can't be
|
||||
/// shown are refused explicitly; their dictionaries and appearance remain untouched.
|
||||
pub fn read(doc: &Document, object: &Object) -> Result<Self> {
|
||||
let o = doc.resolve(object);
|
||||
let d = o.as_dict().ok_or_else(|| invalid("invalid measure dictionary"))?;
|
||||
if d.get(b"Subtype").map(|o| doc.resolve(o)).is_some_and(|o| !matches!(*o, Object::Null) && o.as_name() != Some(b"RL")) {
|
||||
return Err(invalid("only rectilinear measurement scales are supported"));
|
||||
}
|
||||
let format = |key: &[u8]| -> Result<(String, f64, u8)> {
|
||||
let a = doc.resolve(d.get(key).ok_or_else(|| invalid("measurement scale lacks a number format"))?);
|
||||
let a = a.as_array().ok_or_else(|| invalid("invalid measurement number format"))?;
|
||||
if a.len() != 1 {
|
||||
return Err(invalid("compound measurement units are not supported yet"));
|
||||
let format = |key: &[u8]| -> Result<Vec<NumberFormat>> {
|
||||
let a = d.get(key).ok_or_else(|| invalid("measurement scale lacks a number format"))?;
|
||||
number_format::read(doc, a).map_err(invalid)
|
||||
};
|
||||
// The unit and factor a number format array converts to first.
|
||||
let first = |a: &[NumberFormat]| a.first().map(|f| (f.unit.clone(), f.factor)).ok_or_else(|| invalid("empty number format"));
|
||||
let xs = format(b"X")?;
|
||||
let (unit, x) = first(&xs)?;
|
||||
let ys = if d.contains(b"Y") { Some(format(b"Y")?) } else { None };
|
||||
let (y, cyx) = match &ys {
|
||||
Some(ys) => {
|
||||
let cyx = d.get(b"CYX").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("Y scale requires CYX for lengths and areas"))?;
|
||||
(first(ys)?.1 * cyx, cyx)
|
||||
}
|
||||
let o = doc.resolve(a.first().ok_or_else(|| invalid("empty number format"))?);
|
||||
let f = o.as_dict().ok_or_else(|| invalid("invalid number format dictionary"))?;
|
||||
let fmt = f.get(b"F").map(|o| doc.resolve(o));
|
||||
let precision = match fmt.as_deref().and_then(Object::as_name) {
|
||||
Some(b"R") => 0,
|
||||
None | Some(b"D") => {
|
||||
let denom = f.get(b"D").and_then(|o| doc.resolve(o).as_int()).unwrap_or(100);
|
||||
(0..=6).find(|p| 10_i64.pow(*p) == denom).ok_or_else(|| invalid("unsupported measurement precision"))?
|
||||
}
|
||||
_ => return Err(invalid("fractional measurement formats are not supported yet")),
|
||||
};
|
||||
Ok((
|
||||
text(doc, f, b"U"),
|
||||
f.get(b"C").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("missing conversion factor"))?,
|
||||
precision as u8,
|
||||
))
|
||||
None => (x, 1.0),
|
||||
};
|
||||
let (unit, x, _) = format(b"X")?;
|
||||
let y = if d.contains(b"Y") {
|
||||
let (_, y, _) = format(b"Y")?;
|
||||
y * d.get(b"CYX").and_then(|o| doc.resolve(o).as_f64()).ok_or_else(|| invalid("Y scale requires CYX for lengths and areas"))?
|
||||
} else {
|
||||
x
|
||||
};
|
||||
let (distance_unit, distance_factor, precision) = format(b"D")?;
|
||||
let distances = format(b"D")?;
|
||||
let (distance_unit, distance_factor) = first(&distances)?;
|
||||
if unit != distance_unit {
|
||||
return Err(invalid("different coordinate and distance units are not supported yet"));
|
||||
}
|
||||
let (area_unit, area_factor, _) = format(b"A")?;
|
||||
let out = Self { x, y, unit, distance_factor, area_factor, area_unit, precision, ratio: text(doc, d, b"R") };
|
||||
let areas = format(b"A")?;
|
||||
let (area_unit, area_factor) = first(&areas)?;
|
||||
let plain = [&xs, &distances, &areas].into_iter().chain(ys.as_ref()).all(|a| number_format::plain_precision(a).is_some());
|
||||
// The decimals a distance shows: of its only unit, or of its last one when compound.
|
||||
let precision = number_format::plain_precision(&distances)
|
||||
.or_else(|| {
|
||||
distances
|
||||
.last()
|
||||
.filter(|f| f.remainder == number_format::Remainder::Decimal)
|
||||
.and_then(|f| u8::try_from(f.denominator.max(1).ilog10()).ok())
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let formats = (!plain).then_some(Formats { x: xs, y: ys, cyx, distance: distances, area: areas });
|
||||
let out = Self { x, y, unit, distance_factor, area_factor, area_unit, precision, ratio: text(doc, d, b"R"), formats };
|
||||
out.validate()?;
|
||||
Ok(out)
|
||||
}
|
||||
@@ -319,10 +366,13 @@ pub fn reading(kind: Kind, points: &[Point], scale: &Scale) -> Result<Reading> {
|
||||
length *= scale.distance_factor;
|
||||
let value = if kind == Kind::Area { area } else { length };
|
||||
let unit = if kind == Kind::Area { scale.area_unit.clone() } else { scale.unit.clone() };
|
||||
let label = format!("{value:.precision$} {unit}", precision = usize::from(scale.precision));
|
||||
if !value.is_finite() {
|
||||
return Err(invalid("measurement overflows its scale"));
|
||||
}
|
||||
let label = match &scale.formats {
|
||||
Some(f) => number_format::format(value, if kind == Kind::Area { &f.area } else { &f.distance }),
|
||||
None => format!("{value:.precision$} {unit}", precision = usize::from(scale.precision)),
|
||||
};
|
||||
Ok(Reading { kind, value, unit, label, delta_x: delta[0], delta_y: delta[1], angle: delta[1].atan2(delta[0]).to_degrees(), length, area })
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -479,7 +529,7 @@ const MAX_LISTED_BYTES: usize = 32 << 20;
|
||||
/// The bytes a listed measurement keeps in points and text.
|
||||
fn retained(m: &Measurement) -> usize {
|
||||
let s = &m.scale;
|
||||
[m.id.len(), m.author.len(), m.label.len(), s.unit.len(), s.area_unit.len(), s.ratio.len()]
|
||||
[m.id.len(), m.author.len(), m.label.len(), s.unit.len(), s.area_unit.len(), s.ratio.len(), s.formats.as_ref().map_or(0, Formats::held_bytes)]
|
||||
.into_iter()
|
||||
.fold(m.points.len().saturating_mul(std::mem::size_of::<Point>()), usize::saturating_add)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
//! Number format arrays (ISO 32000-2 §12.9.2, number format dictionaries).
|
||||
//!
|
||||
//! A rectilinear measure dictionary's `X`, `Y`, `D` and `A` entries are arrays of number format
|
||||
//! dictionaries. The first element's `C` converts to the largest unit; each later element's `C`
|
||||
//! is how many of its (smaller) unit make one of the previous element's. A value shows as whole
|
||||
//! units of every element but the last, then what is left in the last unit, shown as its `F`
|
||||
//! says: decimals to `1/D` (`/D`), a fraction in `D`ths (`/F`), or whole units rounded (`/R`) or
|
||||
//! cut off (`/T`). With miles, feet, and inches in eighths, 1.4505 mi shows as
|
||||
//! "1 mi 2,378 ft 7 5/8 in".
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, Object, PdfString};
|
||||
use serde::Serialize;
|
||||
|
||||
/// Most elements one number format array is read with (miles, yards, feet and inches are four).
|
||||
pub const MAX_UNITS: usize = 8;
|
||||
/// Longest unit label or separator, in characters, as for a scale's own unit labels.
|
||||
const MAX_TEXT: usize = 24;
|
||||
/// Largest denominator of a fraction (`F /F`).
|
||||
const MAX_DENOMINATOR: i64 = 1 << 16;
|
||||
/// A remainder this close below a whole step of the last unit, in steps, counts as the step:
|
||||
/// `3.5 ft` stored as `3.4999999999 ft` still cuts to 6 in, not 5 in.
|
||||
const NUDGE: f64 = 1e-6;
|
||||
|
||||
/// How the part of the last unit below a whole one shows (`F`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Remainder {
|
||||
/// `/D`: decimals, to `1 / denominator`.
|
||||
Decimal,
|
||||
/// `/F`: a fraction in `denominator`ths.
|
||||
Fraction,
|
||||
/// `/R`: rounded to whole units.
|
||||
Round,
|
||||
/// `/T`: cut off to whole units.
|
||||
Truncate,
|
||||
}
|
||||
|
||||
/// One number format dictionary.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct NumberFormat {
|
||||
/// `U`: the unit's label.
|
||||
pub unit: String,
|
||||
/// `C`: this unit in one of the previous element's unit (or, for the first element, in what
|
||||
/// the measure dictionary's entry converts from).
|
||||
pub factor: f64,
|
||||
/// `F`.
|
||||
pub remainder: Remainder,
|
||||
/// `D`: the decimal precision (a power of ten) or the fraction's denominator; 1 for whole units.
|
||||
pub denominator: i64,
|
||||
/// `FD`: decimals keep their trailing zeros and fractions are not reduced.
|
||||
pub exact: bool,
|
||||
/// `RT`: between groups of thousands.
|
||||
pub thousands: String,
|
||||
/// `RD`: the decimal point.
|
||||
pub decimal: String,
|
||||
/// `PS`: before the label.
|
||||
pub before: String,
|
||||
/// `SS`: after the label.
|
||||
pub after: String,
|
||||
/// `O /P`: the label goes before the number instead of after it.
|
||||
pub prefix: bool,
|
||||
}
|
||||
|
||||
impl NumberFormat {
|
||||
/// Steps of this unit counted by its remainder: `1/denominator` for decimals and fractions.
|
||||
fn steps(&self) -> f64 {
|
||||
match self.remainder {
|
||||
Remainder::Decimal | Remainder::Fraction => self.denominator.max(1) as f64,
|
||||
Remainder::Round | Remainder::Truncate => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `count` steps of this unit (whole, finite and not negative) as text.
|
||||
fn number(&self, count: f64) -> String {
|
||||
let denominator = self.denominator.max(1);
|
||||
match self.remainder {
|
||||
Remainder::Round | Remainder::Truncate => grouped(&format!("{count:.0}"), &self.thousands),
|
||||
Remainder::Decimal => {
|
||||
let places = denominator.ilog10() as usize;
|
||||
let text = format!("{:.places$}", count / denominator as f64);
|
||||
let (whole, part) = text.split_once('.').unwrap_or((&text, ""));
|
||||
let part = if self.exact { part } else { part.trim_end_matches('0') };
|
||||
let whole = grouped(whole, &self.thousands);
|
||||
if part.is_empty() { whole } else { format!("{whole}{}{part}", self.decimal) }
|
||||
}
|
||||
Remainder::Fraction => {
|
||||
// The numerator is below the denominator however large and inexact the count is.
|
||||
let numerator = (count.rem_euclid(denominator as f64) as i64).clamp(0, denominator - 1);
|
||||
let whole = ((count - numerator as f64) / denominator as f64).round().max(0.0);
|
||||
let text = grouped(&format!("{whole:.0}"), &self.thousands);
|
||||
if numerator == 0 {
|
||||
return text;
|
||||
}
|
||||
let g = if self.exact { 1 } else { gcd(numerator, denominator) };
|
||||
let fraction = format!("{}/{}", numerator / g, denominator / g);
|
||||
if whole == 0.0 { fraction } else { format!("{text} {fraction}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This format as a number format dictionary, every entry written out.
|
||||
pub(crate) fn dictionary(&self) -> Object {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Type".to_vec(), Object::name("NumberFormat"));
|
||||
d.set(b"U".to_vec(), PdfString::text(&self.unit));
|
||||
d.set(b"C".to_vec(), Object::Real(self.factor));
|
||||
let f = match self.remainder {
|
||||
Remainder::Decimal => "D",
|
||||
Remainder::Fraction => "F",
|
||||
Remainder::Round => "R",
|
||||
Remainder::Truncate => "T",
|
||||
};
|
||||
d.set(b"F".to_vec(), Object::name(f));
|
||||
if matches!(self.remainder, Remainder::Decimal | Remainder::Fraction) {
|
||||
d.set(b"D".to_vec(), Object::Int(self.denominator));
|
||||
}
|
||||
d.set(b"FD".to_vec(), Object::Bool(self.exact));
|
||||
d.set(b"RT".to_vec(), PdfString::text(&self.thousands));
|
||||
d.set(b"RD".to_vec(), PdfString::text(&self.decimal));
|
||||
d.set(b"PS".to_vec(), PdfString::text(&self.before));
|
||||
d.set(b"SS".to_vec(), PdfString::text(&self.after));
|
||||
d.set(b"O".to_vec(), Object::name(if self.prefix { "P" } else { "S" }));
|
||||
Object::Dict(d)
|
||||
}
|
||||
}
|
||||
|
||||
/// The number format arrays of an imported scale that a single-unit decimal scale can't stand
|
||||
/// for: compound units (feet and inches), fractions, or values cut off to whole units.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct Formats {
|
||||
/// `X`: changes along the x axis (and the y axis when there is no `Y`).
|
||||
pub x: Vec<NumberFormat>,
|
||||
/// `Y`: changes along the y axis, in its own units, as read.
|
||||
pub y: Option<Vec<NumberFormat>>,
|
||||
/// `CYX`: y-axis units in one x-axis unit, as read with `y` (1 without it).
|
||||
pub cyx: f64,
|
||||
/// `D`: distances.
|
||||
pub distance: Vec<NumberFormat>,
|
||||
/// `A`: areas.
|
||||
pub area: Vec<NumberFormat>,
|
||||
}
|
||||
|
||||
impl Formats {
|
||||
/// Every array, `y` after `x` when there is one.
|
||||
fn arrays(&self) -> impl Iterator<Item = &Vec<NumberFormat>> {
|
||||
[&self.x, &self.distance, &self.area].into_iter().chain(self.y.as_ref())
|
||||
}
|
||||
|
||||
/// Checks every array as [`crate::Scale::validate`] checks a scale's own fields.
|
||||
pub(crate) fn validate(&self) -> Result<(), &'static str> {
|
||||
if !self.cyx.is_finite() || !(1e-12..=1e12).contains(&self.cyx) {
|
||||
return Err("scale factors must be finite and between 1e-12 and 1e12");
|
||||
}
|
||||
self.arrays().try_for_each(|a| validate(a))
|
||||
}
|
||||
|
||||
/// Bytes held, elements and their text, for a listing's bound on what it keeps.
|
||||
pub(crate) fn held_bytes(&self) -> usize {
|
||||
self.arrays()
|
||||
.flatten()
|
||||
.flat_map(|f| [&f.unit, &f.thousands, &f.decimal, &f.before, &f.after])
|
||||
.fold(0usize, |n, s| n.saturating_add(s.len()))
|
||||
.saturating_add(self.arrays().map(Vec::len).sum::<usize>().saturating_mul(std::mem::size_of::<NumberFormat>()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The decimal places of a single-element decimal (`/D`) or rounded (`/R`) array: what a
|
||||
/// single-unit decimal scale's `precision` describes. `None` for anything else.
|
||||
pub(crate) fn plain_precision(formats: &[NumberFormat]) -> Option<u8> {
|
||||
match formats {
|
||||
[f] if f.remainder == Remainder::Decimal => u8::try_from(f.denominator.max(1).ilog10()).ok(),
|
||||
[f] if f.remainder == Remainder::Round => Some(0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the number format array `object` (resolving references), refusing a structure it can't
|
||||
/// read or a precision it can't show. Labels, separators and later units' factors are checked
|
||||
/// only when they are shown ([`Formats::validate`]): a single-unit decimal array is read for its
|
||||
/// unit, factor and precision alone, as it always was.
|
||||
pub(crate) fn read(doc: &Document, object: &Object) -> Result<Vec<NumberFormat>, &'static str> {
|
||||
let a = doc.resolve(object);
|
||||
let a = a.as_array().ok_or("invalid measurement number format")?;
|
||||
if a.is_empty() {
|
||||
return Err("empty number format");
|
||||
}
|
||||
if a.len() > MAX_UNITS {
|
||||
return Err("number formats of more than 8 units are not supported");
|
||||
}
|
||||
a.iter().enumerate().map(|(i, o)| read_one(doc, &doc.resolve(o), i + 1 == a.len())).collect()
|
||||
}
|
||||
|
||||
fn read_one(doc: &Document, o: &Object, is_last: bool) -> Result<NumberFormat, &'static str> {
|
||||
let f = o.as_dict().ok_or("invalid number format dictionary")?;
|
||||
let get = |k: &[u8]| f.get(k).map(|v| doc.resolve(v));
|
||||
let text = |k: &[u8], default: &str| get(k).and_then(|v| v.as_string().map(PdfString::to_text)).unwrap_or_else(|| default.into());
|
||||
// ISO 32000-2 §12.9.2: only the last element formats a remainder (`/F`, `/D`, `/FD`);
|
||||
// earlier elements always format whole units.
|
||||
let (remainder, denominator, exact) = if is_last {
|
||||
let remainder = match get(b"F").as_deref().and_then(Object::as_name) {
|
||||
None | Some(b"D") => Remainder::Decimal,
|
||||
Some(b"F") => Remainder::Fraction,
|
||||
Some(b"R") => Remainder::Round,
|
||||
Some(b"T") => Remainder::Truncate,
|
||||
Some(_) => return Err("unknown measurement number format"),
|
||||
};
|
||||
let denominator = match remainder {
|
||||
Remainder::Decimal => get(b"D").and_then(|v| v.as_int()).unwrap_or(100),
|
||||
Remainder::Fraction => get(b"D").and_then(|v| v.as_int()).unwrap_or(16),
|
||||
Remainder::Round | Remainder::Truncate => 1,
|
||||
};
|
||||
let denominator_ok = match remainder {
|
||||
Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == denominator),
|
||||
Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&denominator),
|
||||
Remainder::Round | Remainder::Truncate => true,
|
||||
};
|
||||
if !denominator_ok {
|
||||
return Err("unsupported measurement precision");
|
||||
}
|
||||
(remainder, denominator, matches!(get(b"FD").as_deref(), Some(Object::Bool(true))))
|
||||
} else {
|
||||
(Remainder::Decimal, 100, false)
|
||||
};
|
||||
// An empty RD means the default decimal point.
|
||||
let decimal = Some(text(b"RD", ".")).filter(|s| !s.is_empty()).unwrap_or_else(|| ".".into());
|
||||
Ok(NumberFormat {
|
||||
unit: text(b"U", ""),
|
||||
factor: get(b"C").and_then(|v| v.as_f64()).ok_or("missing conversion factor")?,
|
||||
remainder,
|
||||
denominator,
|
||||
exact,
|
||||
thousands: text(b"RT", ","),
|
||||
decimal,
|
||||
before: text(b"PS", " "),
|
||||
after: text(b"SS", " "),
|
||||
prefix: get(b"O").as_deref().and_then(Object::as_name) == Some(b"P".as_slice()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks an array: 1 to [`MAX_UNITS`] elements, factors as a scale's, labels and separators of
|
||||
/// at most 24 printable characters, and on the last element a decimal precision of 0 to 6 places
|
||||
/// or a fraction denominator of 1 to 65,536.
|
||||
fn validate(formats: &[NumberFormat]) -> Result<(), &'static str> {
|
||||
if formats.is_empty() || formats.len() > MAX_UNITS {
|
||||
return Err("number formats have 1 to 8 units");
|
||||
}
|
||||
for (i, f) in formats.iter().enumerate() {
|
||||
if !f.factor.is_finite() || !(1e-12..=1e12).contains(&f.factor) {
|
||||
return Err("scale factors must be finite and between 1e-12 and 1e12");
|
||||
}
|
||||
if f.unit.trim().is_empty() || f.unit.chars().count() > MAX_TEXT || f.unit.chars().any(char::is_control) {
|
||||
return Err("unit labels must be 1 to 24 printable characters");
|
||||
}
|
||||
if [&f.thousands, &f.decimal, &f.before, &f.after].iter().any(|s| s.chars().count() > MAX_TEXT || s.chars().any(char::is_control)) {
|
||||
return Err("number format separators must be at most 24 printable characters");
|
||||
}
|
||||
if i + 1 == formats.len() {
|
||||
let denominator_ok = match f.remainder {
|
||||
Remainder::Decimal => (0..=6).any(|p| 10_i64.pow(p) == f.denominator),
|
||||
Remainder::Fraction => (1..=MAX_DENOMINATOR).contains(&f.denominator),
|
||||
Remainder::Round | Remainder::Truncate => f.denominator == 1,
|
||||
};
|
||||
if !denominator_ok {
|
||||
return Err("unsupported measurement precision");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `value`, in the first element's unit, as `formats` show it (ISO 32000-2 §12.9.2): whole units
|
||||
/// of every element but the last, then the rest in the last element's unit. A last unit that
|
||||
/// rounds up to a whole one of the unit before carries into it ("1 ft 0 in", not "0 ft 12 in").
|
||||
/// Not-a-number and infinite values show as nothing.
|
||||
pub(crate) fn format(value: f64, formats: &[NumberFormat]) -> String {
|
||||
let Some(last) = formats.last() else { return String::new() };
|
||||
if !value.is_finite() {
|
||||
return String::new();
|
||||
}
|
||||
let steps = last.steps();
|
||||
let mut wholes = Vec::with_capacity(formats.len());
|
||||
let mut rest = value.abs();
|
||||
for (i, next) in formats.iter().enumerate().skip(1) {
|
||||
// The nudge is a fraction of a step of the last unit, however many units lie between.
|
||||
let per_step = formats.iter().skip(i).fold(steps, |p, f| p * f.factor);
|
||||
let nudge = if per_step.is_finite() && per_step > 1.0 { NUDGE / per_step } else { NUDGE };
|
||||
let whole = (rest + nudge).floor();
|
||||
wholes.push(whole);
|
||||
rest = ((rest - whole) * next.factor).max(0.0);
|
||||
}
|
||||
let mut count = if last.remainder == Remainder::Truncate { (rest * steps + NUDGE).floor() } else { (rest * steps).round() };
|
||||
carry(&mut count, steps, &mut wholes, formats);
|
||||
let mut out = String::new();
|
||||
if value < 0.0 && (count > 0.0 || wholes.iter().any(|w| *w > 0.0)) {
|
||||
out.push('-');
|
||||
}
|
||||
for (whole, f) in wholes.iter().zip(formats) {
|
||||
push_segment(&mut out, &grouped(&format!("{whole:.0}"), &f.thousands), f);
|
||||
}
|
||||
push_segment(&mut out, &last.number(count), last);
|
||||
out.trim().to_string()
|
||||
}
|
||||
|
||||
/// Carries a last unit's `count` of `steps` that reached a whole one of the unit before into
|
||||
/// it, and then each whole count of a unit into the unit before that. Only whole conversion
|
||||
/// factors carry: a unit that isn't a whole number of the next has no whole count to carry.
|
||||
fn carry(count: &mut f64, steps: f64, wholes: &mut [f64], formats: &[NumberFormat]) {
|
||||
let full = formats.last().map_or(0.0, |f| f.factor * steps);
|
||||
let Some(previous) = wholes.last_mut() else { return };
|
||||
if !is_whole(full) || *count < full {
|
||||
return;
|
||||
}
|
||||
*count -= full;
|
||||
*previous += 1.0;
|
||||
for i in (1..wholes.len()).rev() {
|
||||
let per = formats.get(i).map_or(0.0, |f| f.factor);
|
||||
let (Some(&w), true) = (wholes.get(i), is_whole(per)) else { continue };
|
||||
if w >= per
|
||||
&& let Some([before, here]) = wholes.get_mut(i - 1..=i)
|
||||
{
|
||||
*here -= per;
|
||||
*before += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_whole(v: f64) -> bool {
|
||||
v.is_finite() && v >= 1.0 && v.fract() == 0.0
|
||||
}
|
||||
|
||||
fn push_segment(out: &mut String, number: &str, f: &NumberFormat) {
|
||||
let label = [f.before.as_str(), &f.unit, &f.after].concat();
|
||||
if f.prefix {
|
||||
out.push_str(&label);
|
||||
out.push_str(number);
|
||||
} else {
|
||||
out.push_str(number);
|
||||
out.push_str(&label);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ASCII digits of a whole number with `separator` between groups of three, from the right.
|
||||
fn grouped(digits: &str, separator: &str) -> String {
|
||||
let n = digits.len();
|
||||
let mut out = String::with_capacity(n + n / 3 * separator.len());
|
||||
for (i, c) in digits.chars().enumerate() {
|
||||
if i > 0 && (n - i).is_multiple_of(3) {
|
||||
out.push_str(separator);
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn gcd(mut a: i64, mut b: i64) -> i64 {
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
a.max(1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn unit(unit: &str, factor: f64, remainder: Remainder, denominator: i64) -> NumberFormat {
|
||||
NumberFormat {
|
||||
unit: unit.into(),
|
||||
factor,
|
||||
remainder,
|
||||
denominator,
|
||||
exact: false,
|
||||
thousands: ",".into(),
|
||||
decimal: ".".into(),
|
||||
before: " ".into(),
|
||||
after: " ".into(),
|
||||
prefix: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn feet_inches(denominator: i64) -> Vec<NumberFormat> {
|
||||
vec![unit("ft", 1.0 / 864.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Fraction, denominator)]
|
||||
}
|
||||
|
||||
/// A file of a catalog, an empty page tree and `objects`, numbered from 3.
|
||||
fn doc_with(objects: &[&str]) -> Document {
|
||||
let pdf = pdfcraft_testkit::Pdf::new().obj("<< /Type /Catalog /Pages 2 0 R >>").obj("<< /Type /Pages /Kids [] /Count 0 >>").objs(objects);
|
||||
Document::open(Arc::new(pdf.build())).unwrap()
|
||||
}
|
||||
|
||||
/// Reads `array`, stored by reference as the object after `objects` (numbered from 3).
|
||||
fn parsed(objects: &[&str], array: &str) -> Result<Vec<NumberFormat>, &'static str> {
|
||||
let doc = doc_with(&[objects, &[array]].concat());
|
||||
let num = u32::try_from(objects.len() + 3).unwrap();
|
||||
read(&doc, &Object::Ref(pdfcraft_cos::ObjRef { num, generation: 0 }))
|
||||
}
|
||||
|
||||
/// The miles, feet and eighths of inches that show "1 mi 2,378 ft 7 5/8 in".
|
||||
#[test]
|
||||
fn compound_units_show_whole_units_then_the_rest() {
|
||||
let formats =
|
||||
vec![unit("mi", 1.0, Remainder::Decimal, 100), unit("ft", 5280.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Fraction, 8)];
|
||||
assert_eq!(format(1.4505, &formats), "1 mi 2,378 ft 7 5/8 in");
|
||||
// A remainder reduces (4/8 is 1/2) unless FD keeps its denominator.
|
||||
assert_eq!(format(3.0 + 6.5 / 12.0, &feet_inches(8)), "3 ft 6 1/2 in");
|
||||
let mut exact = feet_inches(8);
|
||||
exact[1].exact = true;
|
||||
assert_eq!(format(3.0 + 6.5 / 12.0, &exact), "3 ft 6 4/8 in");
|
||||
// No fractional part: the whole number alone; under one unit: the fraction alone.
|
||||
assert_eq!(format(2.5, &feet_inches(16)), "2 ft 6 in");
|
||||
assert_eq!(format(1.0 / 96.0, &feet_inches(16)), "0 ft 1/8 in");
|
||||
}
|
||||
|
||||
/// A remainder that rounds up to a whole one of the unit before carries into it, through
|
||||
/// every unit that becomes whole in turn.
|
||||
#[test]
|
||||
fn a_remainder_that_rounds_up_carries() {
|
||||
assert_eq!(format(1.0 - 1e-4, &feet_inches(16)), "1 ft 0 in");
|
||||
let formats = vec![unit("yd", 1.0, Remainder::Decimal, 100), unit("ft", 3.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Round, 1)];
|
||||
assert_eq!(format(2.0 - 1e-4, &formats), "2 yd 0 ft 0 in");
|
||||
// A factor that isn't whole has no whole count to carry: the rounded rest stays.
|
||||
let odd = vec![unit("a", 1.0, Remainder::Decimal, 100), unit("b", 2.5, Remainder::Round, 1)];
|
||||
assert_eq!(format(1.9, &odd), "1 a 2 b");
|
||||
// A whole unit stored a hair below itself is still whole, factor whole or not.
|
||||
assert_eq!(format(2.0 - 1e-10, &odd), "2 a 0 b");
|
||||
// ... but a value a step of the last unit short of it is not, however small the step.
|
||||
let metres = vec![unit("km", 1.0, Remainder::Decimal, 100), unit("m", 1000.0, Remainder::Decimal, 1000)];
|
||||
assert_eq!(format(1.0 - 9e-7, &metres), "0 km 999.999 m");
|
||||
let miles =
|
||||
vec![unit("mi", 1.0, Remainder::Decimal, 100), unit("ft", 5280.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Fraction, 64)];
|
||||
assert_eq!(format(1.0 - 9e-7, &miles), "0 mi 5,279 ft 11 15/16 in");
|
||||
// A value stored a hair below a whole step still cuts to it.
|
||||
let cut = vec![unit("ft", 1.0, Remainder::Decimal, 100), unit("in", 12.0, Remainder::Truncate, 1)];
|
||||
assert_eq!(format(3.4999999999, &cut), "3 ft 6 in");
|
||||
assert_eq!(format(3.49, &cut), "3 ft 5 in");
|
||||
}
|
||||
|
||||
/// Single-unit decimals, rounding and cutting, with the spec's separators and label position.
|
||||
#[test]
|
||||
fn decimals_separators_and_label_position() {
|
||||
let mut decimal = unit("m", 1.0, Remainder::Decimal, 1000);
|
||||
assert_eq!(format(1234.5, std::slice::from_ref(&decimal)), "1,234.5 m");
|
||||
decimal.exact = true;
|
||||
assert_eq!(format(1234.5, std::slice::from_ref(&decimal)), "1,234.500 m");
|
||||
let euro = NumberFormat { thousands: ".".into(), decimal: ",".into(), ..decimal.clone() };
|
||||
assert_eq!(format(1_234_567.25, std::slice::from_ref(&euro)), "1.234.567,250 m");
|
||||
assert_eq!(format(7.0, &[unit("m", 1.0, Remainder::Decimal, 100)]), "7 m");
|
||||
assert_eq!(format(7.6, &[unit("m", 1.0, Remainder::Round, 1)]), "8 m");
|
||||
assert_eq!(format(7.6, &[unit("m", 1.0, Remainder::Truncate, 1)]), "7 m");
|
||||
let prefixed = NumberFormat { prefix: true, before: String::new(), after: String::new(), ..unit("$", 1.0, Remainder::Decimal, 100) };
|
||||
assert_eq!(format(12.5, &[prefixed]), "$12.5");
|
||||
let tight = vec![
|
||||
NumberFormat { before: String::new(), after: String::new(), ..unit("'", 1.0, Remainder::Decimal, 100) },
|
||||
NumberFormat { before: String::new(), after: String::new(), ..unit("\"", 12.0, Remainder::Fraction, 4) },
|
||||
];
|
||||
assert_eq!(format(12.0 + 3.25 / 12.0, &tight), "12'3 1/4\"");
|
||||
// Negative values keep their sign; nothing shows for none and for non-finite values.
|
||||
assert_eq!(format(-2.5, &feet_inches(16)), "-2 ft 6 in");
|
||||
assert_eq!(format(-0.0, &feet_inches(16)), "0 ft 0 in");
|
||||
assert_eq!(format(1.0, &[]), "");
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert_eq!(format(bad, &feet_inches(16)), "");
|
||||
}
|
||||
// The largest values a scale allows show in full, without an exponent.
|
||||
let huge = format(1e30, &feet_inches(16));
|
||||
assert!(huge.starts_with("1,000,000,000,000,000,019,884,624,838,656 ft"), "{huge}");
|
||||
// A fraction of a value too large to be exact still has a numerator below its denominator.
|
||||
let fraction = format(1e30, &[unit("in", 1.0, Remainder::Fraction, 3)]);
|
||||
let tokens: Vec<&str> = fraction.split_whitespace().collect();
|
||||
assert!(matches!(tokens.as_slice(), [_, "in"] | [_, "1/3" | "2/3", "in"]), "{fraction}");
|
||||
}
|
||||
|
||||
/// Every entry is read with its default, references resolved, and written back as read.
|
||||
#[test]
|
||||
fn arrays_read_with_defaults_and_write_back() {
|
||||
let source = "[<< /U (ft) /C 0.5 >> << /U 3 0 R /C 4 0 R /F 5 0 R /D 8 /FD true /RT (.) /RD () /PS () /SS (-) /O /P >>]";
|
||||
let read_back = parsed(&["(in)", "12", "/F"], source).unwrap();
|
||||
assert_eq!(read_back[0], unit("ft", 0.5, Remainder::Decimal, 100));
|
||||
let inches = &read_back[1];
|
||||
assert_eq!((inches.unit.as_str(), inches.factor, inches.remainder, inches.denominator), ("in", 12.0, Remainder::Fraction, 8));
|
||||
assert!(inches.exact && inches.prefix);
|
||||
assert_eq!((inches.thousands.as_str(), inches.decimal.as_str(), inches.before.as_str(), inches.after.as_str()), (".", ".", "", "-"));
|
||||
assert_eq!(parsed(&[], "[<< /U (in) /C 1 /F /F >>]").unwrap()[0].denominator, 16);
|
||||
// Written out and read again, nothing changes.
|
||||
let written = Object::Array(read_back.iter().map(NumberFormat::dictionary).collect());
|
||||
assert_eq!(read(&doc_with(&[]), &written).unwrap(), read_back);
|
||||
assert_eq!(plain_precision(&read_back), None);
|
||||
assert_eq!(plain_precision(&read_back[..1]), Some(2));
|
||||
assert_eq!(plain_precision(&[unit("m", 1.0, Remainder::Round, 1)]), Some(0));
|
||||
assert_eq!(plain_precision(&[unit("m", 1.0, Remainder::Fraction, 16)]), None);
|
||||
assert_eq!(plain_precision(&[unit("m", 1.0, Remainder::Truncate, 1)]), None);
|
||||
}
|
||||
|
||||
/// What can't be shown faithfully is refused with a reason, before anything is formatted.
|
||||
#[test]
|
||||
fn unreadable_arrays_are_refused() {
|
||||
let units = |n: usize| format!("[{}]", vec!["<< /U (u) /C 1 >>"; n].join(" "));
|
||||
let nine = units(9);
|
||||
for (source, reason) in [
|
||||
("[]", "empty number format"),
|
||||
("<< /U (ft) /C 1 >>", "invalid measurement number format"),
|
||||
(nine.as_str(), "number formats of more than 8 units are not supported"),
|
||||
("[(ft)]", "invalid number format dictionary"),
|
||||
("[<< /U (ft) /C 1 /F /X >>]", "unknown measurement number format"),
|
||||
("[<< /U (ft) >>]", "missing conversion factor"),
|
||||
("[<< /U (ft) /C 0 >>]", "scale factors must be finite and between 1e-12 and 1e12"),
|
||||
("[<< /C 1 >>]", "unit labels must be 1 to 24 printable characters"),
|
||||
("[<< /U (ft) /C 1 /D 12 >>]", "unsupported measurement precision"),
|
||||
("[<< /U (ft) /C 1 /D 10000000 >>]", "unsupported measurement precision"),
|
||||
("[<< /U (ft) /C 1 /F /F /D 0 >>]", "unsupported measurement precision"),
|
||||
("[<< /U (ft) /C 1 /F /F /D 65537 >>]", "unsupported measurement precision"),
|
||||
("[<< /U (ft) /C 1 /SS (aaaaaaaaaaaaaaaaaaaaaaaaa) >>]", "number format separators must be at most 24 printable characters"),
|
||||
] {
|
||||
assert_eq!(parsed(&[], source).and_then(|f| validate(&f).map(|()| f)), Err(reason), "{source}");
|
||||
}
|
||||
assert_eq!(parsed(&[], "[<< /U (ft) /C 1 /F /F /D 65536 >>]").unwrap()[0].denominator, 65536);
|
||||
// Only the last element's `/F` and `/D` format a remainder; earlier elements' `/F` and `/D` are ignored.
|
||||
assert_eq!(parsed(&[], "[<< /U (ft) /C 1 /F /X /D 12 >> << /U (in) /C 12 /F /F /D 16 >>]").map(|f| f.len()), Ok(2));
|
||||
assert_eq!(parsed(&[], &units(MAX_UNITS)).map(|f| f.len()), Ok(MAX_UNITS));
|
||||
}
|
||||
|
||||
/// What formats hold is counted for the listing bound.
|
||||
#[test]
|
||||
fn formats_count_their_text() {
|
||||
let f = Formats {
|
||||
x: feet_inches(16),
|
||||
y: Some(feet_inches(16)),
|
||||
cyx: 1.0,
|
||||
distance: feet_inches(16),
|
||||
area: vec![unit("ft²", 1.0, Remainder::Decimal, 100)],
|
||||
};
|
||||
// Each element holds its label and "," "." " " " " (4 bytes).
|
||||
let elements = 3 * 2 + 1;
|
||||
assert_eq!(f.held_bytes(), 3 * ((2 + 4) + (2 + 4)) + ("ft²".len() + 4) + elements * std::mem::size_of::<NumberFormat>());
|
||||
assert_eq!(f.validate(), Ok(()));
|
||||
let bad = Formats { cyx: 0.0, ..f.clone() };
|
||||
assert_eq!(bad.validate(), Err("scale factors must be finite and between 1e-12 and 1e12"));
|
||||
let bad = Formats { y: Some(Vec::new()), ..f };
|
||||
assert_eq!(bad.validate(), Err("number formats have 1 to 8 units"));
|
||||
}
|
||||
}
|
||||
@@ -283,13 +283,14 @@ fn unsupported_measurements_are_reported_not_fatal() {
|
||||
let mut d = fixture("", "", &[]);
|
||||
add(&mut d, &new(Kind::Distance, vec![[0.0, 0.0], [3.0, 4.0]]), &Meta::default()).unwrap();
|
||||
add(&mut d, &new(Kind::Distance, vec![[10.0, 0.0], [13.0, 4.0]]), &Meta::default()).unwrap();
|
||||
// An imported compound feet-and-inches format (two NumberFormat dictionaries).
|
||||
// An imported format this crate can't show (an unknown /F).
|
||||
let (r, _) = annot(&d, 0, 1).unwrap();
|
||||
let format = |unit: &str, c: f64| {
|
||||
let mut f = Dict::new();
|
||||
f.set(b"Type".to_vec(), Object::name("NumberFormat"));
|
||||
f.set(b"U".to_vec(), PdfString::text(unit));
|
||||
f.set(b"C".to_vec(), Object::Real(c));
|
||||
f.set(b"F".to_vec(), Object::name("X"));
|
||||
Object::Dict(f)
|
||||
};
|
||||
d.update_dict(r, |a| {
|
||||
@@ -302,7 +303,7 @@ fn unsupported_measurements_are_reported_not_fatal() {
|
||||
assert_eq!(listing.measurements.len(), 1);
|
||||
assert_eq!(listing.unsupported.len(), 1);
|
||||
assert_eq!((listing.unsupported[0].page, listing.unsupported[0].index), (0, 1));
|
||||
assert!(listing.unsupported[0].reason.contains("compound"), "{}", listing.unsupported[0].reason);
|
||||
assert_eq!(listing.unsupported[0].reason, "unknown measurement number format");
|
||||
// Invalid geometry on an imported annotation is reported the same way.
|
||||
let (r, _) = annot(&d, 0, 0).unwrap();
|
||||
d.update_dict(r, |a| a.set(b"L".to_vec(), nums([0.0, 0.0, f64::NAN, 1.0]))).unwrap();
|
||||
@@ -632,3 +633,79 @@ fn indirect_scale_fields_and_closed_area_edges_are_handled() {
|
||||
assert_eq!(item.label, "Floor Plan");
|
||||
assert_eq!(item.scale, Scale { y: 3.0, ..Scale::new(2.0, "m", 3).unwrap() });
|
||||
}
|
||||
|
||||
/// An Acrobat-style drawing scale of 1 in = 1 ft whose distances show in feet and sixteenths of
|
||||
/// inches (ISO 32000-2 §12.9.2): a viewport and a saved measurement using it read, are labelled
|
||||
/// in feet and inches, and a measurement added inside the viewport keeps the formats.
|
||||
#[test]
|
||||
fn compound_and_fractional_scales_read_label_and_carry_into_new_measurements() {
|
||||
let feet_inches = "[<< /Type /NumberFormat /U (ft) /C 0.0138888888888889 /D 100 >> << /U (in) /C 12 /F /F /D 16 >>]";
|
||||
let measure = format!(
|
||||
"<< /Type /Measure /Subtype /RL /R (1 in = 1 ft) /X {feet_inches} /D [<< /U (ft) /C 1 >> << /U (in) /C 12 /F /F /D 16 >>] /A [<< /U (sq ft) /C 1 /F /T >>] >>"
|
||||
);
|
||||
let mut d = fixture("", &format!("/VP [<< /Type /Viewport /BBox [0 0 612 792] /Measure {measure} >>]"), &[]);
|
||||
let scale = scale_at(&d, 0, [10.0, 10.0]).unwrap();
|
||||
assert_eq!((scale.unit.as_str(), scale.area_unit.as_str(), scale.precision), ("ft", "sq ft", 0));
|
||||
close(scale.x, 1.0 / 72.0);
|
||||
let formats = scale.formats.as_ref().unwrap();
|
||||
assert_eq!(formats.distance.len(), 2);
|
||||
// 3 ft 6 1/2 in at 1 in = 1 ft is 3 in and 6.5 / 12 in on the page: 216 + 39 points.
|
||||
let distance = reading(Kind::Distance, &[[0.0, 0.0], [0.0, 255.0]], &scale).unwrap();
|
||||
close(distance.value, 255.0 / 72.0);
|
||||
assert_eq!(distance.label, "3 ft 6 1/2 in");
|
||||
// Just short of 2 ft carries into the feet; an area of 2.9 sq ft is cut off to 2.
|
||||
assert_eq!(reading(Kind::Distance, &[[0.0, 0.0], [143.99, 0.0]], &scale).unwrap().label, "2 ft 0 in");
|
||||
let side = (2.9f64).sqrt() * 72.0;
|
||||
assert_eq!(reading(Kind::Area, &[[0.0, 0.0], [side, 0.0], [side, side], [0.0, side]], &scale).unwrap().label, "2 sq ft");
|
||||
|
||||
// Added inside the viewport, as the Measure tool and measure_distance do, the measurement
|
||||
// keeps the compound formats and reads the same after a save.
|
||||
let mut m = new(Kind::Distance, vec![[0.0, 0.0], [0.0, 255.0]]);
|
||||
m.scale = scale.clone();
|
||||
add(&mut d, &m, &Meta { date: None, id: "plan".into() }).unwrap();
|
||||
let (_, dict) = annot(&d, 0, 0).unwrap();
|
||||
assert_eq!(text(&d, &dict, b"Contents"), "3 ft 6 1/2 in");
|
||||
let saved = d.resolve(dict.get(b"Measure").unwrap());
|
||||
let saved_d = d.resolve(saved.as_dict().unwrap().get(b"D").unwrap());
|
||||
let inches = saved_d.as_array().unwrap()[1].as_dict().unwrap().clone();
|
||||
assert_eq!(inches.get(b"F").and_then(Object::as_name), Some(b"F".as_slice()));
|
||||
assert_eq!(inches.get(b"D").and_then(Object::as_int), Some(16));
|
||||
let reopened = Document::open(Arc::new(write_full(&d, &SaveOptions::default()).unwrap())).unwrap();
|
||||
let listing = list(&reopened);
|
||||
assert!(listing.unsupported.is_empty(), "{:?}", listing.unsupported);
|
||||
assert_eq!(listing.measurements[0].reading.label, "3 ft 6 1/2 in");
|
||||
close(listing.measurements[0].scale.x, scale.x);
|
||||
assert_eq!(listing.measurements[0].scale.formats.as_ref().map(|f| (f.x.len(), f.distance.len(), f.area.len())), Some((2, 2, 1)));
|
||||
// A plain decimal scale keeps no formats and labels as before.
|
||||
assert_eq!(Scale::read(&d, &Object::Dict(Scale::new(2.0, "m", 3).unwrap().dictionary().unwrap())).unwrap().formats, None);
|
||||
}
|
||||
|
||||
/// A compound Y in units of its own (metres and centimetres against feet and inches) is written
|
||||
/// back as read, with its CYX, so a viewer showing y coordinates reads the same units.
|
||||
#[test]
|
||||
fn a_compound_y_keeps_its_units_and_cyx() {
|
||||
let x = "[<< /U (ft) /C 0.0138888888888889 >> << /U (in) /C 12 /F /F /D 16 >>]";
|
||||
let y = "[<< /U (m) /C 0.000352778 >> << /U (cm) /C 100 /D 10 >>]";
|
||||
let measure = format!("<< /Type /Measure /Subtype /RL /X {x} /Y {y} /CYX 3.28084 /D {x} /A [<< /U (sq ft) /C 1 >>] >>");
|
||||
let d = fixture("", &format!("/VP [<< /Type /Viewport /BBox [0 0 612 792] /Measure {measure} >>]"), &[]);
|
||||
let scale = scale_at(&d, 0, [10.0, 10.0]).unwrap();
|
||||
close(scale.y, 0.000352778 * 3.28084);
|
||||
let written = scale.dictionary().unwrap();
|
||||
close(written.get(b"CYX").and_then(Object::as_f64).unwrap(), 3.28084);
|
||||
let ys = written.get(b"Y").and_then(Object::as_array).unwrap();
|
||||
let first = ys[0].as_dict().unwrap();
|
||||
assert_eq!(text(&d, first, b"U"), "m");
|
||||
close(first.get(b"C").and_then(Object::as_f64).unwrap(), 0.000352778);
|
||||
assert_eq!(text(&d, ys[1].as_dict().unwrap(), b"U"), "cm");
|
||||
let again = Scale::read(&d, &Object::Dict(written)).unwrap();
|
||||
close(again.y, scale.y);
|
||||
let formats = again.formats.unwrap();
|
||||
assert_eq!((formats.y.unwrap()[1].factor, formats.cyx), (100.0, 3.28084));
|
||||
// If `Scale.y` is mutated so `self.y / cyx` exceeds the factor bound, `dictionary()` refuses it.
|
||||
let mut overflow_y = scale;
|
||||
if let Some(f) = &mut overflow_y.formats {
|
||||
f.cyx = 1e-12;
|
||||
}
|
||||
overflow_y.y = 2.0;
|
||||
assert!(overflow_y.dictionary().is_err());
|
||||
}
|
||||
|
||||
+16
-12
@@ -130,18 +130,22 @@ pub fn program_is_usable(program: &Path) -> bool {
|
||||
/// executable FILE (on Unix the executable bits must be set; elsewhere being a file is what
|
||||
/// the OS requires). A directory or a missing file is simply unavailable — never a panic.
|
||||
fn program_is_executable(program: &Path) -> bool {
|
||||
if !program.is_absolute() || !program.is_file() {
|
||||
return false;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::metadata(program).is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
true
|
||||
}
|
||||
program.is_absolute() && program.is_file() && has_execute_permission(program)
|
||||
}
|
||||
|
||||
/// Unix: an executable bit is set.
|
||||
#[cfg(unix)]
|
||||
fn has_execute_permission(program: &Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::metadata(program).is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
|
||||
/// Elsewhere, being a file is what the OS requires. A function of its own: inlined above, the
|
||||
/// Windows build reduced to `if … { return false; } true`, which clippy's `needless_bool`
|
||||
/// refuses (Rust 1.100).
|
||||
#[cfg(not(unix))]
|
||||
fn has_execute_permission(_program: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// One row of Tesseract's TSV output. `level` 5 rows are the words; `conf` is −1 on the header
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! refers to.
|
||||
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString};
|
||||
|
||||
@@ -164,6 +165,8 @@ pub(crate) fn remove_invalid(doc: &mut Document, pages: &[ObjRef]) -> Result<(us
|
||||
fn referenced_names(doc: &Document) -> HashSet<Vec<u8>> {
|
||||
let mut out = HashSet::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut named_refs = HashSet::new();
|
||||
let mut named_held: std::collections::HashMap<*const Object, Arc<Object>> = std::collections::HashMap::new();
|
||||
let mut stack = vec![Object::Dict(doc.trailer().clone())];
|
||||
if let Some(r) = doc.root() {
|
||||
stack.push(Object::Ref(r));
|
||||
@@ -180,11 +183,26 @@ fn referenced_names(doc: &Document) -> HashSet<Vec<u8>> {
|
||||
// string, and an unresolved ref has no name, so the destination it uses would
|
||||
// look unreferenced and be removed. A GoToR or GoToE /D names a destination in
|
||||
// another document, so it does not count as a use of this one's.
|
||||
if let Some(n) = d.get(b"Dest").and_then(|x| dest_name(doc.resolve(x).as_ref())) {
|
||||
// A name given by reference is copied once, however many dictionaries (or aliases
|
||||
// of the object) name it. The objects are kept so an address is never reused.
|
||||
let mut named = |x: Option<&Object>| {
|
||||
let x = x?;
|
||||
if let Object::Ref(r) = x
|
||||
&& !named_refs.insert(*r)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let held = doc.resolve(x);
|
||||
if matches!(x, Object::Ref(_)) && named_held.insert(Arc::as_ptr(&held), held.clone()).is_some() {
|
||||
return None;
|
||||
}
|
||||
dest_name(held.as_ref())
|
||||
};
|
||||
if let Some(n) = named(d.get(b"Dest")) {
|
||||
out.insert(n);
|
||||
}
|
||||
if d.name(b"S") == Some(b"GoTo")
|
||||
&& let Some(n) = d.get(b"D").and_then(|x| dest_name(doc.resolve(x).as_ref()))
|
||||
&& let Some(n) = named(d.get(b"D"))
|
||||
{
|
||||
out.insert(n);
|
||||
}
|
||||
|
||||
@@ -4439,6 +4439,36 @@ fn indirectly_referenced_destination_is_kept() {
|
||||
assert!(!left.contains(&b"unused".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_links_naming_one_destination_string_by_reference_keep_it() {
|
||||
// The name string is copied once however many links name it by reference; it is still a use.
|
||||
let mut doc = Document::new_empty();
|
||||
let p = page(&mut doc, &[], "BT ET");
|
||||
let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t.as_bytes().to_vec()));
|
||||
let name_ref = Object::Ref(doc.add(s("target")));
|
||||
let links: Vec<Object> = (0..50)
|
||||
.map(|_| {
|
||||
let mut link = Dict::new();
|
||||
link.set(b"Subtype".to_vec(), Object::name("Link"));
|
||||
link.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]));
|
||||
link.set(b"Dest".to_vec(), name_ref.clone());
|
||||
Object::Ref(doc.add(Object::Dict(link)))
|
||||
})
|
||||
.collect();
|
||||
doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(links))).unwrap();
|
||||
let fit = Object::Array(vec![Object::Ref(p), Object::name("Fit")]);
|
||||
let mut tree = Dict::new();
|
||||
tree.set(b"Names".to_vec(), Object::Array(vec![s("target"), fit.clone(), s("unused"), fit]));
|
||||
let tree = doc.add(Object::Dict(tree));
|
||||
let mut names = Dict::new();
|
||||
names.set(b"Dests".to_vec(), Object::Ref(tree));
|
||||
let root = doc.root().unwrap();
|
||||
doc.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names))).unwrap();
|
||||
let report = optimize(&mut doc, &Settings::default()).unwrap();
|
||||
assert_eq!(report.unreferenced_dests, 1);
|
||||
assert_eq!(named_dest_keys(&doc), vec![b"target".to_vec()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destination_named_only_by_a_remote_or_embedded_go_to_is_removed() {
|
||||
// The /D of a GoToR or GoToE action names a destination in another document. A local
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! An `OPENSSL_ia32cap` left in the environment must not stop PdfCraft (#2916).
|
||||
//!
|
||||
//! aws-lc, the cryptography library behind digital signatures (through `aws-lc-rs`) and TLS,
|
||||
//! reads `OPENSSL_ia32cap` when it detects the CPU's features on x86 and x86-64. A value that
|
||||
//! asks for a feature the processor doesn't have makes it print "Fatal Error: HW capability
|
||||
//! found: …, but HW capability requested: …" and call `abort()`. On Windows that is exit code
|
||||
//! 0xC0000409 with no window, no message and nothing in the log. Tuning guides and other
|
||||
//! programs leave the variable set for every program, so PdfCraft never started on those PCs
|
||||
//! while other apps did.
|
||||
//!
|
||||
//! Two parts keep PdfCraft running:
|
||||
//! - `.cargo/config.toml` builds aws-lc with `BORINGSSL_NO_STATIC_INITIALIZER`, so it detects
|
||||
//! the CPU when `CRYPTO_library_init` is called instead of in a static initializer before
|
||||
//! `main`.
|
||||
//! - [`run_without_cpu_override`], the first thing each executable's `main` does, runs the
|
||||
//! program again without the variable. Then `main` calls `pdfcraft_sign::init_crypto`, so the
|
||||
//! CPU is detected at start as before, and every operation gets its fast code.
|
||||
//!
|
||||
//! Removing the variable from this process instead wouldn't work: aws-lc reads it through the C
|
||||
//! runtime's `getenv`, whose copy of the environment `std::env::remove_var` doesn't change on
|
||||
//! Windows, and the workspace has no `unsafe` to call the C runtime with.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write as _;
|
||||
|
||||
/// The variable aws-lc reads on x86 and x86-64.
|
||||
pub const IA32CAP: &str = "OPENSSL_ia32cap";
|
||||
|
||||
/// Set in the program started again to the value it was started without, for its log.
|
||||
pub const DROPPED: &str = "PDFCRAFT_DROPPED_OPENSSL_IA32CAP";
|
||||
|
||||
/// When `OPENSSL_ia32cap` is set: run this executable again, with the same arguments and
|
||||
/// standard streams but without the variable, and return its exit code once it ends.
|
||||
///
|
||||
/// `None` when the variable isn't set, on processors aws-lc doesn't read it for (not x86), on
|
||||
/// macOS (Finder hands files to the process it started, through Apple events, so a second one
|
||||
/// would never get them), or when the program can't be started again. Then the caller carries
|
||||
/// on: a value that asks for a missing CPU feature still stops it, at its first use of aws-lc.
|
||||
pub fn run_without_cpu_override() -> Option<i32> {
|
||||
if !cfg!(any(target_arch = "x86", target_arch = "x86_64")) || cfg!(target_os = "macos") {
|
||||
return None;
|
||||
}
|
||||
let value = std::env::var_os(IA32CAP)?;
|
||||
let run = || {
|
||||
let exe = std::env::current_exe()?;
|
||||
std::process::Command::new(exe).args(std::env::args_os().skip(1)).env_remove(IA32CAP).env(DROPPED, &value).status()
|
||||
};
|
||||
match run() {
|
||||
// A process ended by a signal (Unix) has no code: report a failure.
|
||||
Ok(status) => Some(status.code().unwrap_or(1)),
|
||||
Err(e) => {
|
||||
// No logger yet; unlike `eprintln!`, this never panics on a closed standard error.
|
||||
let _ = writeln!(std::io::stderr(), "{IA32CAP} is set to {}, and starting again without it failed: {e}", shown(&value));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The value this program was started without, when [`run_without_cpu_override`] started it.
|
||||
pub fn dropped() -> Option<String> {
|
||||
std::env::var_os(DROPPED).map(|v| shown(&v))
|
||||
}
|
||||
|
||||
/// A value for a message: lossy where it isn't Unicode, and short.
|
||||
fn shown(value: &OsString) -> String {
|
||||
value.to_string_lossy().chars().take(64).collect()
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
//! pdfcraft-platform — L7 operating-system services shared by the desktop app (`ui-egui`) and the
|
||||
//! automation tools (`automation`), which sit on the same layer and can't depend on each other,
|
||||
//! and by the two executables (`owner_only`, for the `--control` file).
|
||||
//! and by the two executables (`owner_only`, for the `--control` file; `crypto_env`, before
|
||||
//! anything uses aws-lc).
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod crypto_env;
|
||||
pub mod desktop_theme;
|
||||
pub mod owner_only;
|
||||
pub mod staging;
|
||||
|
||||
+15
-10
@@ -69,12 +69,17 @@ pub fn embed(doc: &Document, evidence: &Evidence) -> Result<Vec<u8>, SignError>
|
||||
let mut dss = Dict::new();
|
||||
dss.set(b"Type".to_vec(), Object::name("DSS"));
|
||||
dss.set(b"Filter".to_vec(), Object::name("Adobe.PPKLite"));
|
||||
dss.set(b"Certs".to_vec(), Object::Ref(doc.add(Object::Array(cert_refs.clone()))));
|
||||
if !ocsp_refs.is_empty() {
|
||||
dss.set(b"OCSPs".to_vec(), Object::Ref(doc.add(Object::Array(ocsp_refs.clone()))));
|
||||
// Each list is one indirect array the store and every signature's VRI entry point to, so the
|
||||
// output does not grow with signatures times evidence.
|
||||
let cert_list = Object::Ref(doc.add(Object::Array(cert_refs)));
|
||||
let ocsp_list = (!ocsp_refs.is_empty()).then(|| Object::Ref(doc.add(Object::Array(ocsp_refs))));
|
||||
let crl_list = (!crl_refs.is_empty()).then(|| Object::Ref(doc.add(Object::Array(crl_refs))));
|
||||
dss.set(b"Certs".to_vec(), cert_list.clone());
|
||||
if let Some(l) = &ocsp_list {
|
||||
dss.set(b"OCSPs".to_vec(), l.clone());
|
||||
}
|
||||
if !crl_refs.is_empty() {
|
||||
dss.set(b"CRLs".to_vec(), Object::Ref(doc.add(Object::Array(crl_refs.clone()))));
|
||||
if let Some(l) = &crl_list {
|
||||
dss.set(b"CRLs".to_vec(), l.clone());
|
||||
}
|
||||
// Keep any existing /VRI entries, then cover every signature in the file.
|
||||
let mut vri =
|
||||
@@ -82,12 +87,12 @@ pub fn embed(doc: &Document, evidence: &Evidence) -> Result<Vec<u8>, SignError>
|
||||
for contents in crate::pdf::signature_contents(&doc) {
|
||||
let mut e = Dict::new();
|
||||
e.set(b"Type".to_vec(), Object::name("VRI"));
|
||||
e.set(b"Cert".to_vec(), Object::Array(cert_refs.clone()));
|
||||
if !ocsp_refs.is_empty() {
|
||||
e.set(b"OCSP".to_vec(), Object::Array(ocsp_refs.clone()));
|
||||
e.set(b"Cert".to_vec(), cert_list.clone());
|
||||
if let Some(l) = &ocsp_list {
|
||||
e.set(b"OCSP".to_vec(), l.clone());
|
||||
}
|
||||
if !crl_refs.is_empty() {
|
||||
e.set(b"CRL".to_vec(), Object::Array(crl_refs.clone()));
|
||||
if let Some(l) = &crl_list {
|
||||
e.set(b"CRL".to_vec(), l.clone());
|
||||
}
|
||||
vri.set(vri_key(&contents).into_bytes(), Object::Dict(e));
|
||||
}
|
||||
|
||||
@@ -37,6 +37,16 @@ pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, s
|
||||
pub use timestamp::{TimestampAuthority, TimestampQuery, TimestampToken};
|
||||
pub use x509::{Certificate, Name};
|
||||
|
||||
/// Detect the CPU's features for aws-lc now. This build has it do so on first use rather than in
|
||||
/// a static initializer before `main` (`.cargo/config.toml`, `pdfcraft_platform::crypto_env`), and
|
||||
/// aws-lc-rs asks for it before most operations but not all: an RSA key generation went without,
|
||||
/// and ran on aws-lc's portable code. So each executable calls this once at start, after
|
||||
/// `crypto_env` has run it again without an `OPENSSL_ia32cap` that would stop it here.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn init_crypto() {
|
||||
aws_lc_rs::init();
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SignError {
|
||||
#[error("malformed data: {0}")]
|
||||
|
||||
@@ -1050,6 +1050,13 @@ fn embedding_ltv_evidence_adds_a_dss_and_keeps_signatures_valid() {
|
||||
doc.get(root).as_dict().unwrap().get(b"DSS").map(|d| doc.resolve(d)).and_then(|d| d.as_dict().cloned()).unwrap();
|
||||
assert_eq!(dss_dict.name(b"Type"), Some(b"DSS".as_slice()));
|
||||
assert!(dss_dict.contains(b"Certs") && dss_dict.contains(b"OCSPs") && dss_dict.contains(b"CRLs") && dss_dict.contains(b"VRI"));
|
||||
// A signature's /VRI entry points at the store's arrays instead of holding its own copy of each.
|
||||
let vri = dss_dict.get(b"VRI").map(|v| doc.resolve(v)).and_then(|v| v.as_dict().cloned()).unwrap();
|
||||
let entry = vri.iter().next().and_then(|(_, e)| e.as_dict().cloned()).unwrap();
|
||||
for (vri_key, dss_key) in [(&b"Cert"[..], &b"Certs"[..]), (b"OCSP", b"OCSPs"), (b"CRL", b"CRLs")] {
|
||||
assert!(matches!(entry.get(vri_key), Some(pdfcraft_cos::Object::Ref(_))));
|
||||
assert_eq!(entry.get(vri_key), dss_dict.get(dss_key));
|
||||
}
|
||||
// The earlier signature still validates; the DSS counts as a permitted change.
|
||||
let s = signatures(&doc, <v, &TrustStore::default()).into_iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
|
||||
assert_eq!(s.status, Status::Unknown);
|
||||
|
||||
@@ -177,6 +177,8 @@ impl PdfCraftApp {
|
||||
open_prepare_gate: None,
|
||||
pinned: Default::default(),
|
||||
recent_check: Default::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
reveal_errors: Default::default(),
|
||||
pinned_tools: Vec::new(),
|
||||
pin_tool_search: String::new(),
|
||||
toast: None,
|
||||
@@ -608,6 +610,7 @@ impl PdfCraftApp {
|
||||
worker.set_context(ctx);
|
||||
}
|
||||
self.poll_pending_opens();
|
||||
self.show_reveal_errors();
|
||||
self.poll_pending_destinations();
|
||||
}
|
||||
self.check_restored_recent();
|
||||
|
||||
@@ -207,9 +207,29 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
let mut open = None;
|
||||
let mut remove = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let mut reveal = None;
|
||||
for r in app.recent.iter().take(app.recent_limit) {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &r.name));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// The Menu key or Shift+F10 on the focused row opens the same menu a secondary
|
||||
// click does, under the row, so Reveal works from the keyboard.
|
||||
let by_key =
|
||||
resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Menu) || (i.modifiers.shift && i.key_pressed(egui::Key::F10)));
|
||||
let mut popup = egui::Popup::context_menu(&resp);
|
||||
if by_key {
|
||||
popup = popup.open_memory(egui::SetOpenCommand::Bool(true)).anchor(rect).align(egui::RectAlign::BOTTOM_START);
|
||||
}
|
||||
popup.show(|ui| {
|
||||
let label = if cfg!(target_os = "macos") { tl!("Reveal in Finder") } else { tl!("Reveal in File Explorer") };
|
||||
if ui.button(label).clicked() {
|
||||
reveal = Some(r.path.clone());
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
let press = theme::Press::track(ui, &resp);
|
||||
// The row, not its response: the pointer stays "in" the row over its remove button.
|
||||
let hovered = ui.rect_contains_pointer(rect);
|
||||
@@ -260,6 +280,10 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
if let Some(p) = open {
|
||||
app.open_recent(&p);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(p) = reveal {
|
||||
app.reveal_path(std::path::Path::new(&p));
|
||||
}
|
||||
if let Some(p) = remove {
|
||||
app.recent.retain(|r| r.path != p);
|
||||
}
|
||||
@@ -315,6 +339,23 @@ mod tests {
|
||||
assert!(h.state().pinned_tools.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_focused_recent_row_opens_its_reveal_menu_from_the_keyboard() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
for chord in [(egui::Modifiers::NONE, egui::Key::Menu), (egui::Modifiers::SHIFT, egui::Key::F10)] {
|
||||
let mut h = review_home_harness();
|
||||
h.state_mut().recent = vec![crate::RecentFile { name: "notes.pdf".into(), path: "/nowhere/notes.pdf".into(), pages: 2, size: 2048 }];
|
||||
h.run_steps(3);
|
||||
assert!(!egui::Popup::is_any_open(&h.ctx));
|
||||
h.get_by_label("notes.pdf").focus();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(chord.0, chord.1);
|
||||
h.run_steps(3);
|
||||
assert!(egui::Popup::is_any_open(&h.ctx), "{chord:?} did not open the Reveal menu");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translated_card_description_leaves_room_for_the_action() {
|
||||
if !crate::i18n::needs_catalogs() {
|
||||
|
||||
@@ -518,6 +518,9 @@ pub struct PdfCraftApp {
|
||||
pub pinned: folders_ui::PinnedFolders,
|
||||
/// The recent files restored from settings, checked off the UI thread (#5682).
|
||||
recent_check: persist::recent_check::RecentCheck,
|
||||
/// Failures of the Reveal worker, taken each frame and shown as a notification.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
reveal_errors: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
|
||||
/// Tools pinned to Home, in user-defined order.
|
||||
pub pinned_tools: Vec<String>,
|
||||
/// Search query for the Pin a tool selection dialog.
|
||||
|
||||
@@ -15,6 +15,39 @@ pub(crate) enum Action {
|
||||
}
|
||||
|
||||
impl crate::PdfCraftApp {
|
||||
/// Reveal a local file without opening it or changing document/Recent state. The existence
|
||||
/// check and the file manager call can block (a disconnected network mount, a slow `dbus-send`
|
||||
/// or `explorer.exe`), so they run on a worker; a failure is shown by
|
||||
/// [`Self::show_reveal_errors`]. Tests run it inline ([`PdfCraftApp::run_inline`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn reveal_path(&mut self, path: &std::path::Path) {
|
||||
let path = path.to_path_buf();
|
||||
let errors = self.reveal_errors.clone();
|
||||
let ctx = self.ctx.clone();
|
||||
let work = move || {
|
||||
if let Err(e) = reveal(&path) {
|
||||
errors.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(e);
|
||||
if let Some(ctx) = &ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
};
|
||||
if self.run_inline {
|
||||
work();
|
||||
} else if let Err(e) = std::thread::Builder::new().name("pdfcraft-reveal".into()).spawn(work) {
|
||||
self.notify_error(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the failures the reveal worker has reported (called each frame).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn show_reveal_errors(&mut self) {
|
||||
let errors = std::mem::take(&mut *self.reveal_errors.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
|
||||
for e in errors {
|
||||
self.notify_error(e);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn tab_action(&mut self, action: Action) {
|
||||
match action {
|
||||
Action::Close(tab) => {
|
||||
@@ -47,10 +80,8 @@ impl crate::PdfCraftApp {
|
||||
}
|
||||
Action::Reveal(id) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(path) = self.session.get(id).and_then(|d| d.path.clone())
|
||||
&& let Err(e) = reveal(std::path::Path::new(&path))
|
||||
{
|
||||
self.notify_error(e);
|
||||
if let Some(path) = self.session.get(id).and_then(|d| d.path.clone()) {
|
||||
self.reveal_path(std::path::Path::new(&path));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = id;
|
||||
@@ -60,6 +91,7 @@ impl crate::PdfCraftApp {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// Blocking: call it from a worker thread ([`crate::PdfCraftApp::reveal_path`]).
|
||||
fn reveal(path: &std::path::Path) -> Result<(), String> {
|
||||
// Absolute paths also prevent a filename starting with '-' becoming an option.
|
||||
let path = std::path::absolute(path).map_err(|e| e.to_string())?;
|
||||
@@ -69,16 +101,6 @@ fn reveal(path: &std::path::Path) -> Result<(), String> {
|
||||
let platform = std::env::consts::OS;
|
||||
let run =
|
||||
|program: &str, args: &[std::ffi::OsString]| reveal_process(program, args).output().map(|o| o.status.success()).map_err(|e| e.to_string());
|
||||
if matches!(platform, "linux" | "freebsd") {
|
||||
// `dbus-send --print-reply` waits up to 2 s for the file manager (then xdg-open may run),
|
||||
// so it runs off the UI thread; a failure there is only logged.
|
||||
let spawned = std::thread::Builder::new().name("pdfcraft-reveal".into()).spawn(move || {
|
||||
if let Err(e) = reveal_via(platform, &path, run) {
|
||||
log::warn!("reveal {}: {e}", path.display());
|
||||
}
|
||||
});
|
||||
return spawned.map(|_| ()).map_err(|e| e.to_string());
|
||||
}
|
||||
reveal_via(platform, &path, run)
|
||||
}
|
||||
|
||||
@@ -242,6 +264,16 @@ mod tests {
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_reveal_is_reported_back_to_the_ui_thread() {
|
||||
let mut app = crate::PdfCraftApp::new();
|
||||
app.run_inline = true;
|
||||
app.reveal_path(std::path::Path::new("/pdfcraft-no-such-dir/missing.pdf"));
|
||||
assert!(app.toast.is_none(), "nothing is shown until the UI thread takes the report");
|
||||
app.show_reveal_errors();
|
||||
assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("The file no longer exists"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_file_manager_falls_back_safely_and_reports_failure() {
|
||||
let path = std::path::Path::new("/tmp/年度 & reports/file.pdf");
|
||||
|
||||
@@ -233,6 +233,16 @@ pub(crate) fn keep_asking_while_probing(ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog's height outside its scrolling settings: the title, a notice of up to two lines,
|
||||
/// the Cancel / Recognize text row and the modal's own margins.
|
||||
const OCR_DIALOG_RESERVE: f32 = 220.0;
|
||||
/// The least the settings scroll in, however short the window: small enough that the title and the
|
||||
/// buttons still fit the smallest window at the largest interface size (173 pt), as Preferences.
|
||||
const OCR_MIN_SCROLL: f32 = 40.0;
|
||||
|
||||
/// The Recognize Text dialog: the title, the settings groups (scrolling when the window is too
|
||||
/// short for them), any engine notice, and the Cancel / Recognize text row. Returns
|
||||
/// `(recognize, cancel)`, which of those buttons was clicked this frame.
|
||||
pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (bool, bool) {
|
||||
let pages = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(1, |d| d.info.pages.len().max(1));
|
||||
let d = &mut app.ocr_draft;
|
||||
@@ -248,115 +258,127 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
};
|
||||
group(ui, "Pages", &mut |ui| {
|
||||
widgets::radio_value(ui, &mut d.pages, OcrPages::All, tl!("All pages"));
|
||||
widgets::radio_value(ui, &mut d.pages, OcrPages::Current, tl!("Current page"));
|
||||
ui.horizontal(|ui| {
|
||||
widgets::radio_value(ui, &mut d.pages, OcrPages::Range, tl!("From"));
|
||||
let on = d.pages == OcrPages::Range;
|
||||
ui.add_enabled(on, egui::DragValue::new(&mut d.from).range(1..=pages));
|
||||
ui.label(tl!("to"));
|
||||
ui.add_enabled(on, egui::DragValue::new(&mut d.to).range(1..=pages));
|
||||
// The settings outgrow a short window or a large display scale (#6599): they scroll, and
|
||||
// the notices and the Cancel / Recognize text row stay below the scroll, always in reach.
|
||||
let max = (ui.ctx().content_rect().height() - OCR_DIALOG_RESERVE).max(OCR_MIN_SCROLL);
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("ocr-dialog-scroll")
|
||||
.max_height(max)
|
||||
// Only applies when the settings overflow: the dialog then opens at its full height
|
||||
// instead of growing frame by frame, as Preferences does.
|
||||
.min_scrolled_height(max)
|
||||
.auto_shrink([false, true])
|
||||
.show(ui, |ui| {
|
||||
group(ui, "Pages", &mut |ui| {
|
||||
widgets::radio_value(ui, &mut d.pages, OcrPages::All, tl!("All pages"));
|
||||
widgets::radio_value(ui, &mut d.pages, OcrPages::Current, tl!("Current page"));
|
||||
ui.horizontal(|ui| {
|
||||
widgets::radio_value(ui, &mut d.pages, OcrPages::Range, tl!("From"));
|
||||
let on = d.pages == OcrPages::Range;
|
||||
ui.add_enabled(on, egui::DragValue::new(&mut d.from).range(1..=pages));
|
||||
ui.label(tl!("to"));
|
||||
ui.add_enabled(on, egui::DragValue::new(&mut d.to).range(1..=pages));
|
||||
});
|
||||
});
|
||||
group(ui, "Settings", &mut |ui| {
|
||||
egui::Grid::new("ocr-settings").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
|
||||
ui.label(tl!("Document language"));
|
||||
let name = LANGUAGES.iter().find(|l| l.0 == d.language).map_or("English", |l| l.1);
|
||||
craft_ui::ComboBox::from_id_salt("ocr-language").selected_text(tl!(name)).width(220.0).show_ui(ui, |ui| {
|
||||
for (code, name) in LANGUAGES {
|
||||
ui.selectable_value(&mut d.language, (*code).to_string(), tl!(*name));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Engine"));
|
||||
let engine_name = match d.engine {
|
||||
EngineChoice::Auto => tl!("Automatic"),
|
||||
EngineChoice::Ocrs => tl!("Built-in"),
|
||||
EngineChoice::Tesseract => tl!("Tesseract"),
|
||||
};
|
||||
craft_ui::ComboBox::from_id_salt("ocr-engine").selected_text(engine_name).width(220.0).show_ui(ui, |ui| {
|
||||
let choices: [(EngineChoice, &str); 3] =
|
||||
[(EngineChoice::Auto, "Automatic"), (EngineChoice::Ocrs, "Built-in"), (EngineChoice::Tesseract, "Tesseract")];
|
||||
for (choice, name) in choices {
|
||||
ui.selectable_value(&mut d.engine, choice, tl!(name));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Combine engines"));
|
||||
let strategy_name = match d.strategy {
|
||||
MergeStrategy::PrimaryOnly => tl!("Primary only"),
|
||||
MergeStrategy::ConfidenceWeighted => tl!("Confidence weighted"),
|
||||
MergeStrategy::RoverVote => tl!("ROVER vote"),
|
||||
};
|
||||
craft_ui::ComboBox::from_id_salt("ocr-strategy").selected_text(strategy_name).width(220.0).show_ui(ui, |ui| {
|
||||
let choices: [(MergeStrategy, &str); 3] = [
|
||||
(MergeStrategy::PrimaryOnly, "Primary only"),
|
||||
(MergeStrategy::ConfidenceWeighted, "Confidence weighted"),
|
||||
(MergeStrategy::RoverVote, "ROVER vote"),
|
||||
];
|
||||
for (choice, name) in choices {
|
||||
ui.selectable_value(&mut d.strategy, choice, tl!(name));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Output"));
|
||||
let mode_name = match d.output_mode {
|
||||
OutputMode::Searchable => tl!("Searchable Image (Exact)"),
|
||||
OutputMode::EditableText => tl!("Editable text"),
|
||||
};
|
||||
craft_ui::ComboBox::from_id_salt("ocr-output").selected_text(mode_name).width(220.0).show_ui(ui, |ui| {
|
||||
let s = ui
|
||||
.selectable_label(d.output_mode == OutputMode::Searchable, tl!("Searchable Image (Exact)"))
|
||||
.on_hover_text(tl!("Adds invisible text over each word; the page image is not changed"));
|
||||
if s.clicked() {
|
||||
d.output_mode = OutputMode::Searchable;
|
||||
}
|
||||
let e = ui
|
||||
.selectable_label(d.output_mode == OutputMode::EditableText, tl!("Editable text"))
|
||||
.on_hover_text(tl!("Writes a new document of visible text; the scan is not changed"));
|
||||
if e.clicked() {
|
||||
d.output_mode = OutputMode::EditableText;
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Downsample to"));
|
||||
craft_ui::ComboBox::from_id_salt("ocr-dpi").selected_text(format!("{} dpi", d.dpi)).width(220.0).show_ui(ui, |ui| {
|
||||
for v in [600, 300, 150, 72] {
|
||||
ui.selectable_value(&mut d.dpi, v, format!("{v} dpi"));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.add(crate::widgets::checkbox(&mut d.text_pages, tl!("Also recognize pages that already have text")))
|
||||
.on_hover_text(tl!("Pictures on those pages are recognized too; words already in the page's text are not added again"));
|
||||
ui.add(crate::widgets::checkbox(&mut d.auto_rotate, tl!("Straighten pages scanned sideways or upside down")));
|
||||
ui.add(crate::widgets::checkbox(&mut d.deskew, tl!("Straighten skewed text lines")));
|
||||
ui.add(crate::widgets::checkbox(&mut d.denoise, tl!("Remove scan speckle")));
|
||||
ui.add(crate::widgets::checkbox(&mut d.binarize, tl!("Black and white (binarize)")));
|
||||
});
|
||||
group(ui, "Skip", &mut |ui| {
|
||||
ui.add(crate::widgets::checkbox(&mut d.skip_text_pages, tl!("Skip pages that already have text")))
|
||||
.on_hover_text(tl!("Pages with renderable text are left alone and reported as skipped"));
|
||||
ui.add(crate::widgets::checkbox(&mut d.skip_text_files, tl!("Skip files that already have text")))
|
||||
.on_hover_text(tl!("In multiple files: a file with any text is its own skipped bucket, and nothing is written for it"));
|
||||
ui.add(crate::widgets::checkbox(&mut d.force_ocr, tl!("Force OCR (override skip options)")))
|
||||
.on_hover_text(tl!("Reads pages and files even where the skip options would leave them alone"));
|
||||
});
|
||||
group(ui, "Output folder", &mut |ui| {
|
||||
ui.horizontal(|ui| match &d.output_folder {
|
||||
Some(f) => {
|
||||
ui.monospace(f).on_hover_text(tl!("The searchable copies are written here under the source names"));
|
||||
if ui.small_button(tl!("Clear")).clicked() {
|
||||
d.output_folder = None;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.label(tl!("Automatic")).on_hover_text(tl!("A folder is asked for when a multiple-file run starts"));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
group(ui, "Settings", &mut |ui| {
|
||||
egui::Grid::new("ocr-settings").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
|
||||
ui.label(tl!("Document language"));
|
||||
let name = LANGUAGES.iter().find(|l| l.0 == d.language).map_or("English", |l| l.1);
|
||||
craft_ui::ComboBox::from_id_salt("ocr-language").selected_text(tl!(name)).width(220.0).show_ui(ui, |ui| {
|
||||
for (code, name) in LANGUAGES {
|
||||
ui.selectable_value(&mut d.language, (*code).to_string(), tl!(*name));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Engine"));
|
||||
let engine_name = match d.engine {
|
||||
EngineChoice::Auto => tl!("Automatic"),
|
||||
EngineChoice::Ocrs => tl!("Built-in"),
|
||||
EngineChoice::Tesseract => tl!("Tesseract"),
|
||||
};
|
||||
craft_ui::ComboBox::from_id_salt("ocr-engine").selected_text(engine_name).width(220.0).show_ui(ui, |ui| {
|
||||
let choices: [(EngineChoice, &str); 3] =
|
||||
[(EngineChoice::Auto, "Automatic"), (EngineChoice::Ocrs, "Built-in"), (EngineChoice::Tesseract, "Tesseract")];
|
||||
for (choice, name) in choices {
|
||||
ui.selectable_value(&mut d.engine, choice, tl!(name));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Combine engines"));
|
||||
let strategy_name = match d.strategy {
|
||||
MergeStrategy::PrimaryOnly => tl!("Primary only"),
|
||||
MergeStrategy::ConfidenceWeighted => tl!("Confidence weighted"),
|
||||
MergeStrategy::RoverVote => tl!("ROVER vote"),
|
||||
};
|
||||
craft_ui::ComboBox::from_id_salt("ocr-strategy").selected_text(strategy_name).width(220.0).show_ui(ui, |ui| {
|
||||
let choices: [(MergeStrategy, &str); 3] = [
|
||||
(MergeStrategy::PrimaryOnly, "Primary only"),
|
||||
(MergeStrategy::ConfidenceWeighted, "Confidence weighted"),
|
||||
(MergeStrategy::RoverVote, "ROVER vote"),
|
||||
];
|
||||
for (choice, name) in choices {
|
||||
ui.selectable_value(&mut d.strategy, choice, tl!(name));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Output"));
|
||||
let mode_name = match d.output_mode {
|
||||
OutputMode::Searchable => tl!("Searchable Image (Exact)"),
|
||||
OutputMode::EditableText => tl!("Editable text"),
|
||||
};
|
||||
craft_ui::ComboBox::from_id_salt("ocr-output").selected_text(mode_name).width(220.0).show_ui(ui, |ui| {
|
||||
let s = ui
|
||||
.selectable_label(d.output_mode == OutputMode::Searchable, tl!("Searchable Image (Exact)"))
|
||||
.on_hover_text(tl!("Adds invisible text over each word; the page image is not changed"));
|
||||
if s.clicked() {
|
||||
d.output_mode = OutputMode::Searchable;
|
||||
}
|
||||
let e = ui
|
||||
.selectable_label(d.output_mode == OutputMode::EditableText, tl!("Editable text"))
|
||||
.on_hover_text(tl!("Writes a new document of visible text; the scan is not changed"));
|
||||
if e.clicked() {
|
||||
d.output_mode = OutputMode::EditableText;
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tl!("Downsample to"));
|
||||
craft_ui::ComboBox::from_id_salt("ocr-dpi").selected_text(format!("{} dpi", d.dpi)).width(220.0).show_ui(ui, |ui| {
|
||||
for v in [600, 300, 150, 72] {
|
||||
ui.selectable_value(&mut d.dpi, v, format!("{v} dpi"));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.add(crate::widgets::checkbox(&mut d.text_pages, tl!("Also recognize pages that already have text")))
|
||||
.on_hover_text(tl!("Pictures on those pages are recognized too; words already in the page's text are not added again"));
|
||||
ui.add(crate::widgets::checkbox(&mut d.auto_rotate, tl!("Straighten pages scanned sideways or upside down")));
|
||||
ui.add(crate::widgets::checkbox(&mut d.deskew, tl!("Straighten skewed text lines")));
|
||||
ui.add(crate::widgets::checkbox(&mut d.denoise, tl!("Remove scan speckle")));
|
||||
ui.add(crate::widgets::checkbox(&mut d.binarize, tl!("Black and white (binarize)")));
|
||||
});
|
||||
group(ui, "Skip", &mut |ui| {
|
||||
ui.add(crate::widgets::checkbox(&mut d.skip_text_pages, tl!("Skip pages that already have text")))
|
||||
.on_hover_text(tl!("Pages with renderable text are left alone and reported as skipped"));
|
||||
ui.add(crate::widgets::checkbox(&mut d.skip_text_files, tl!("Skip files that already have text")))
|
||||
.on_hover_text(tl!("In multiple files: a file with any text is its own skipped bucket, and nothing is written for it"));
|
||||
ui.add(crate::widgets::checkbox(&mut d.force_ocr, tl!("Force OCR (override skip options)")))
|
||||
.on_hover_text(tl!("Reads pages and files even where the skip options would leave them alone"));
|
||||
});
|
||||
group(ui, "Output folder", &mut |ui| {
|
||||
ui.horizontal(|ui| match &d.output_folder {
|
||||
Some(f) => {
|
||||
ui.monospace(f).on_hover_text(tl!("The searchable copies are written here under the source names"));
|
||||
if ui.small_button(tl!("Clear")).clicked() {
|
||||
d.output_folder = None;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.label(tl!("Automatic")).on_hover_text(tl!("A folder is asked for when a multiple-file run starts"));
|
||||
}
|
||||
});
|
||||
});
|
||||
keep_asking_while_probing(ui.ctx());
|
||||
// The web build has no model files: it downloads the models the first time they're needed.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -465,3 +465,44 @@ fn ocr_verify_screen_focus_ring_and_empty_walk() {
|
||||
assert!(moved, "Ctrl+Tab moves the focus");
|
||||
assert_eq!(h.state().ocr_verify.focus, start, "the ring returns after the four panes");
|
||||
}
|
||||
|
||||
/// #6599: in a short window (a small screen, or a large display scale) the dialog's settings
|
||||
/// scroll, and Cancel and Recognize text stay on screen below them instead of running off it.
|
||||
#[test]
|
||||
fn recognize_text_keeps_its_buttons_in_a_short_window() {
|
||||
use egui::accesskit::Role;
|
||||
// 173 is the smallest window (520 pt) at the largest interface size (300%), 208 is 250%.
|
||||
// 640 pt across is a 1280-pixel-wide screen at 200%. At 1100 pt everything fits (the dialog
|
||||
// is about 935 pt tall) and nothing scrolls.
|
||||
let width = 640.0;
|
||||
for height in [173.0, 208.0, 260.0, 400.0, 480.0, 560.0, 700.0, 900.0, 1100.0] {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(width, height)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("scan.pdf", None, scan()).unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
assert!(h.state_mut().execute("ocr.recognize"));
|
||||
h.run_steps(6);
|
||||
let on_screen = |r: egui::Rect| r.min.x >= 0.0 && r.max.x <= width && r.min.y >= 0.0 && r.max.y <= height;
|
||||
let title = h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Recognize Text")).rect();
|
||||
let run = h.get_by_role_and_label(Role::Button, "Recognize text").rect();
|
||||
let cancel = h.get_by_role_and_label(Role::Button, "Cancel").rect();
|
||||
assert!(on_screen(title), "{height}: the title at {title:?} is off the window");
|
||||
assert!(on_screen(run), "{height}: Recognize text at {run:?} is off the window");
|
||||
assert!(on_screen(cancel), "{height}: Cancel at {cancel:?} is off the window");
|
||||
// The last group scrolls in between the title and the buttons, which do not move.
|
||||
h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Output folder")).scroll_to_me();
|
||||
h.run_steps(4);
|
||||
let last = h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Output folder")).rect();
|
||||
assert!(last.min.y >= title.max.y && last.max.y <= run.min.y, "{height}: Output folder {last:?} between {title:?} and {run:?}");
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Recognize text").rect(), run, "{height}: the buttons stay put");
|
||||
let title_after = h.get_by(|n| n.role() == Role::Label && n.value().as_deref() == Some("Recognize Text")).rect();
|
||||
assert_eq!(title_after, title, "{height}: the title stays put");
|
||||
// On screen is not enough: a click reaches Cancel and closes the dialog.
|
||||
h.get_by_role_and_label(Role::Button, "Cancel").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().dialog.is_none(), "{height}: Cancel closes the dialog");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2133,3 +2133,38 @@ fn full_screen_neither_is_remembered_nor_hides_the_last_view() {
|
||||
view.leave_presentation();
|
||||
assert_eq!((view.fit, view.zoom, view.layout, view.continuous), (Fit::None, 0.5, PageLayout::TwoUp, false), "the remembered view");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn home_recent_context_menu_reveals_the_target_without_opening_or_removing_it() {
|
||||
let missing = std::env::temp_dir().join(format!("pdfcraft-recent-missing-{}", std::process::id())).join("jährlicher report.pdf");
|
||||
assert!(!missing.exists());
|
||||
let expected = missing.to_string_lossy().into_owned();
|
||||
let target = expected.clone();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1600.0)).build_eframe(move |_| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
for (name, path) in [("first.pdf", ".".to_owned()), ("target.pdf", target)] {
|
||||
app.recent.push(pdfcraft_ui_egui::RecentFile { name: name.into(), path, pages: 1, size: 0 });
|
||||
}
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
let label = if cfg!(target_os = "macos") { "Reveal in Finder" } else { "Reveal in File Explorer" };
|
||||
h.get_by_label("target.pdf").click_secondary();
|
||||
h.run_steps(3);
|
||||
assert!(!h.get_by_label(label).accesskit_node().is_disabled());
|
||||
assert!(h.state().views.is_empty(), "right-click must not open the PDF");
|
||||
assert_eq!(h.state().recent.len(), 2);
|
||||
h.get_by_label(label).click();
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label(label).is_none(), "choosing the action closes its menu");
|
||||
assert!(h.state().views.is_empty(), "reveal must not open the PDF");
|
||||
assert_eq!(h.state().active, None);
|
||||
assert_eq!(h.state().recent.len(), 2, "reveal must not remove missing recent files");
|
||||
assert_eq!(h.state().recent[1].path, expected);
|
||||
assert!(
|
||||
h.state().toast.as_ref().is_some_and(|(text, _)| text.contains("The file no longer exists")),
|
||||
"the selected path is checked and the existing reveal error is shown"
|
||||
);
|
||||
}
|
||||
|
||||
+5
-2
@@ -23,6 +23,8 @@
|
||||
> **2026-11-04 (M6, PR #5699 review):** Bound worker capacity and synchronous deadlines, isolate expired/pending realms before edits, keep script prompts above other dialogs, and cover block ASI, control-position regex literals, event routing and complete undo state. Validation is reported in the PR; parity remains partial.
|
||||
> **2026-11-03 (M6, PR #5699 follow-up):** Accept independent top-level statements separated by automatic semicolon insertion while retaining continuation-chain limits; assert cyclic calculation results and preserve upstream multiline Fill & Sign coverage.
|
||||
|
||||
> **Last reviewed:** 2026-11-05 | **Last updated:** 2026-11-05 | **Change:** minor (M3, #5452: native Recent rows gain Reveal in Finder / File Explorer; estimates unchanged)
|
||||
|
||||
> **Last reviewed:** 2026-10-28 | **Last updated:** 2026-10-28 | **Change:** minor (M10, #4119 partial: Enhance scanned file cleans scanned pages in place: background removal, edge shadow removal, despeckle; estimates unchanged)
|
||||
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged)
|
||||
|
||||
@@ -43,7 +45,6 @@
|
||||
> **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)
|
||||
|
||||
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 review follow-up: preserve image crop/tag/stream ownership, resize in page orientation, harden clipboard and text formatting, and reload installed fonts; estimates unchanged)
|
||||
|
||||
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: GBK rasters compared with explicit Unicode and independently selected installed faces; wrong-glyph and wrong-family negative controls fail; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: integrate main fa5f9f8c; retain CJK viewer and upstream raster regressions, restore explicit display_config imports; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-30 | **Last updated:** 2026-10-30 | **Change:** minor (M6: scripts can read and change a push-button's normal caption with undo/redo and save/reopen coverage; estimates unchanged)
|
||||
@@ -252,7 +253,7 @@ total matches the parity estimate.
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. Forms without Resources use page Properties for ActualText and layer visibility; own dictionaries stop fallback. Oversized missing inline-image samples, including header and terminator overhead, no longer pin the content window (#3107 / PR #3438); normal large streamed images retain deterministic sample boundaries. Radial luminosity fades have synthetic coverage for the existing #2132 mask guard, including per-pixel references, antialiased clips, previews, scales and tiles; no additional production fix was needed. Dotted TOC leaders no longer inflate letter tracking or hide word spaces (#3086); phrase search and selection are covered. Short tracked ellipses retain their gap samples and remain searchable. Missing spacing glyphs in non-embedded Japanese CID substitutes render blank without changing PDF advances or Unicode (#3601). The desktop viewer can use installed CJK fonts, including Windows GBK Song/Hei/Kai/FangSong and subset-prefixed Founder names; Combine thumbnails and accessibility figure previews use the same display-only fallback, without changing export or print font policy (#234, continuation of #1567, review #4172). Print previews exclude installed faces and isolate their font cache; GBK regressions cover view/print switching for inline and pooled whole-page/tile rendering. Installed-font helpers and their regression contracts have function documentation. GBK regression rasters match explicit-Unicode references with independently selected installed faces; wrong-glyph and wrong-family negative controls fail. Integration with main fa5f9f8c retains viewer fallback across the split engine session modules, renderer tests and Combine thumbnail workers. |
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. The renderer keeps its one-point crop-size floor in physical points after UserUnit scaling, with regression coverage for crop origins, rotations and f32 reciprocal rounding. Existing unit policy and nearly-zero fallback are retained. |
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). Native Recent rows also offer Reveal in Finder / File Explorer (#5452). |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. Wrapped revision buttons stay above Binding in Document Properties (#2739); a synthetic UI test checks layout and saved revision content. |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Later native-open replies stay queued while a modal or picker owns the foreground; regressions cover recipient ownership, completion/cancellation and one-shot wakes. |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. #1980: exact quit modifiers preserve Ctrl+Alt+Q email input; Ctrl+Q/Cmd+Q asks before discarding unsaved documents. |
|
||||
@@ -341,6 +342,8 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st
|
||||
|
||||
## Revision history
|
||||
|
||||
**2026-10-31 · minor:** M3/#5452: native Home Recent context menus reuse tab reveal, retaining missing-file errors and leaving documents and history unchanged. Estimates unchanged.
|
||||
|
||||
**2026-11-09 · patch:** M4 #4594: reconcile upstream license notices, roadmap entries and UI test modules without changing the Document Properties draft guard or dependency policy. Estimates unchanged.
|
||||
|
||||
**2026-10-27 · minor:** M10 #5005: vector printing preserves annotation optional-content membership.
|
||||
|
||||
@@ -682,8 +682,8 @@ milestone = "M3"
|
||||
status = "shipped"
|
||||
commands = ["file.open_recent", "file.clear_recent"]
|
||||
tools = []
|
||||
evidence = ["crates/ui-egui/tests/it/ui.rs::persistence_round_trips_and_tolerates_garbage", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_lists_files_and_opens_one", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_is_disabled_while_the_list_is_empty", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_at_the_foot_of_open_recent_empties_the_list", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_runs_from_the_palette_and_is_saved", "crates/ui-egui/tests/it/ui.rs::home_removes_one_recent_file_or_clears_them_all"]
|
||||
notes = "never reads other apps' lists; File ▸ Open Recent lists them (#290), an already-open file focuses its tab instead of reopening it, from any open path (#1620); Clear Recent Files at the foot of Open Recent, on Home and in the palette, and a remove button on each Home row (#430); missing: the row's remove button shows on pointer hover only (keyboard users clear the whole list)"
|
||||
evidence = ["crates/ui-egui/tests/it/ui.rs::persistence_round_trips_and_tolerates_garbage", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_lists_files_and_opens_one", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_is_disabled_while_the_list_is_empty", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_at_the_foot_of_open_recent_empties_the_list", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_runs_from_the_palette_and_is_saved", "crates/ui-egui/tests/it/ui.rs::home_removes_one_recent_file_or_clears_them_all", "crates/ui-egui/tests/it/ui.rs::home_recent_context_menu_reveals_the_target_without_opening_or_removing_it"]
|
||||
notes = "never reads other apps' lists; File ▸ Open Recent lists them (#290), an already-open file focuses its tab instead of reopening it, from any open path (#1620); Clear Recent Files at the foot of Open Recent, on Home and in the palette, and a remove button on each Home row (#430); native Home rows offer Reveal in Finder / File Explorer through their context menu (#5452), reusing tab reveal without opening or removing the file (browser has no local file manager); missing: the row's remove button shows on pointer hover only (keyboard users clear the whole list)"
|
||||
|
||||
[[feature]]
|
||||
id = "core.reopen-last-session"
|
||||
@@ -4638,7 +4638,7 @@ milestone = "M6"
|
||||
status = "shipped"
|
||||
commands = ["form.fields"]
|
||||
tools = ["form_fill", "form_fields"]
|
||||
evidence = ["crates/ui-egui/tests/it/forms.rs::typing_into_a_text_field_and_tabbing_on", "crates/ui-egui/tests/it/forms.rs::auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box", "crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/engine/src/tests.rs::filling_a_form_shows_saves_and_undoes", "crates/automation/tests/it/automation.rs::orphan_form_fields_through_tools", "crates/forms/src/tests.rs::fields_sharing_a_name_take_the_same_value", "crates/ui-egui/tests/it/forms.rs::hovering_a_field_shows_its_tooltip", "crates/forms/src/tests.rs::zero_max_len_is_unlimited_and_overrides_inherited_limit", "crates/engine/src/tests.rs::password_field_values_are_kept_in_memory_but_written_to_no_file", "crates/forms/src/tests.rs::a_cleared_password_field_returns_to_its_default_value", "crates/forms/src/tests.rs::a_text_field_says_what_fits_it_as_its_appearance_draws_it", "crates/forms/src/tests.rs::an_edit_to_a_full_field_keeps_what_fits", "crates/ui-egui/tests/it/forms.rs::a_field_that_doesnt_scroll_stops_taking_text_when_full", "crates/ui-egui/tests/it/forms.rs::a_multi_line_auto_sized_field_that_doesnt_scroll_stops_when_full", "crates/engine/src/tests.rs::an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box", "crates/xfa/src/tests.rs::fields_that_dont_scroll_are_written_with_do_not_scroll", "crates/forms/src/tests.rs::comb_fields_show_their_cells", "crates/forms/src/tests.rs::thai_a_field_font_cannot_hold_is_drawn_from_the_thai_face", "crates/automation/tests/it/automation.rs::thai_in_fill_sign_text_comments_fields_and_page_marks_is_drawn_and_found"]
|
||||
evidence = ["crates/ui-egui/tests/it/forms.rs::typing_into_a_text_field_and_tabbing_on", "crates/ui-egui/tests/it/forms.rs::auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box", "crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/engine/src/tests.rs::filling_a_form_shows_saves_and_undoes", "crates/automation/tests/it/automation.rs::orphan_form_fields_through_tools", "crates/forms/src/tests.rs::fields_sharing_a_name_take_the_same_value", "crates/ui-egui/tests/it/forms.rs::hovering_a_field_shows_its_tooltip", "crates/forms/src/tests.rs::zero_max_len_is_unlimited_and_overrides_inherited_limit", "crates/engine/src/tests.rs::password_field_values_are_kept_in_memory_but_written_to_no_file", "crates/forms/src/tests.rs::a_cleared_password_field_returns_to_its_default_value", "crates/forms/src/tests.rs::a_text_field_says_what_fits_it_as_its_appearance_draws_it", "crates/forms/src/tests.rs::an_edit_to_a_full_field_keeps_what_fits", "crates/ui-egui/tests/it/forms.rs::a_field_that_doesnt_scroll_stops_taking_text_when_full", "crates/ui-egui/tests/it/forms.rs::a_multi_line_auto_sized_field_that_doesnt_scroll_stops_when_full", "crates/engine/src/tests.rs::an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box", "crates/xfa/src/tests.rs::fields_that_dont_scroll_are_written_with_do_not_scroll", "crates/forms/src/tests.rs::comb_fields_show_their_cells", "crates/forms/src/tests.rs::thai_a_field_font_cannot_hold_is_drawn_from_the_thai_face", "crates/automation/tests/it/automation.rs::thai_in_fill_sign_text_comments_fields_and_page_marks_is_drawn_and_found", "crates/engine/tests/form_edit_reads.rs::a_form_edit_reads_the_fields_once_however_many_the_form_holds"]
|
||||
notes = "in-place editor; Thai the field's /DA font can't hold is drawn from the craft-fonts Thai face as Add text draws it (Type 3 glyphs with a ToUnicode map beside the field's font, /DA kept, no /NeedAppearances asked for; the ink of stacked marks and descenders kept inside the border, an automatic size shrinking for it), and refused, saying what to do, in a build without a Thai face (#2354); comb and list fields still draw Thai as `?`, marked; Enter or clicking away commits, Escape cancels; auto-size (0 Tf) fields shrink, and multiline ones wrap, the text being typed to fit the box, on screen as on the page (the screen measures in the interface font, so its size can be a little smaller than the page's Helvetica fit); fixed sizes are kept and clip, as in Acrobat; a field that doesn't scroll (DoNotScroll, ISO 32000-2 Table 228, and XFA's hScrollPolicy/vScrollPolicy=\"off\", written as it) takes no more text than its appearance shows, measured in the field's own font, padding and size (the smallest automatic size, 4 pt, for 0 Tf): typing into a full field adds nothing, and a paste or a replaced selection keeps what fits (form_fill isn't interactive and still takes any value); no format/keystroke JavaScript yet (M6.4); resting the pointer on any field shows its tooltip (/TU), as Acrobat does (#3854); imported MaxLen 0 permits text input and overrides inherited limits; positive limits remain enforced. A text field with the Password flag is saved as Acrobat saves it (#3926, black-box test): the typed value is written to no file (Save, Save As, Reduce File Size, recovery, Extract/Split/Combine, signing); the field gets back its default value (/DV) or is left empty, and its asterisks are redrawn from that value. /DV and the field's scripts stay. Known limits, which Acrobat shares: a script that copies the password into an ordinary field saves it there (Acrobat recalculates a Calculate copy on save, PdfCraft does not), and an incremental save leaves a password stored by an earlier revision in that revision. A comb field with a border colour shows its MaxLen cells as lines in that colour, in the appearances PdfCraft saves and in display-only ones (up to 500 cells)."
|
||||
|
||||
[[feature]]
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+46
-8
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::object::macros::object;
|
||||
use crate::object::r#ref::MaybeRef;
|
||||
use crate::object::{FromBytes, Object, ObjectLike};
|
||||
use crate::object::{FromBytes, Null, Object, ObjectLike};
|
||||
use crate::reader::Reader;
|
||||
use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
|
||||
use alloc::vec::Vec;
|
||||
@@ -129,18 +129,37 @@ impl<'a> Iterator for ArrayIter<'a> {
|
||||
self.reader.skip_white_spaces_and_comments();
|
||||
|
||||
if !self.reader.at_end() {
|
||||
// Objects are already guaranteed to be valid.
|
||||
let item = self
|
||||
// PdfCraft patch (46): the first pass validated each item by skipping it, but a lone
|
||||
// sign (`+`, `++`) is skipped as a number and no number is read from it. Such an item
|
||||
// reads as null in its slot instead of unwrapping the failed read.
|
||||
let start = self.reader.clone();
|
||||
if let Some(item) = self
|
||||
.reader
|
||||
.read_with_context::<MaybeRef<Object<'_>>>(&self.ctx)
|
||||
.unwrap();
|
||||
return Some(item);
|
||||
{
|
||||
return Some(item);
|
||||
}
|
||||
self.reader = skip_unreadable_item(start, &self.ctx)?;
|
||||
return Some(MaybeRef::NotRef(Object::Null(Null)));
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (46): step over an array item at `start` that the first pass skipped but no
|
||||
/// object is read from. `None` (end the iteration) if it can't be skipped or the skip makes no
|
||||
/// progress, so a caller never loops.
|
||||
fn skip_unreadable_item<'a>(mut start: Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Reader<'a>> {
|
||||
let from = start.offset();
|
||||
if ctx.in_content_stream() {
|
||||
start.skip::<Object<'_>>(true)?;
|
||||
} else {
|
||||
start.skip::<MaybeRef<Object<'_>>>(false)?;
|
||||
}
|
||||
(start.offset() > from).then_some(start)
|
||||
}
|
||||
|
||||
/// An iterator over the array that resolves objects of a specific type.
|
||||
pub struct ResolvedArrayIter<'a, T> {
|
||||
flex_iter: FlexArrayIter<'a>,
|
||||
@@ -197,9 +216,28 @@ impl<'a> FlexArrayIter<'a> {
|
||||
return self.reader.read_with_context::<T>(&self.ctx);
|
||||
}
|
||||
|
||||
return match self.reader.read_with_context::<MaybeRef<T>>(&self.ctx)? {
|
||||
MaybeRef::Ref(r) => self.ctx.xref().get_with::<T>(r.into(), &self.ctx),
|
||||
MaybeRef::NotRef(i) => Some(i),
|
||||
let start = self.reader.clone();
|
||||
return match self.reader.read_with_context::<MaybeRef<T>>(&self.ctx) {
|
||||
Some(MaybeRef::Ref(r)) => self.ctx.xref().get_with::<T>(r.into(), &self.ctx),
|
||||
Some(MaybeRef::NotRef(i)) => Some(i),
|
||||
// PdfCraft patch (46): an item no object is read from (a lone sign such as `+`)
|
||||
// reads as null in its slot, as in `raw_iter`, instead of ending the iteration
|
||||
// and losing the items after it. An object of another type still ends it. The
|
||||
// slot is passed only when null is a `T`: a typed read that fails leaves it in
|
||||
// place, as a value of another type is, so the caller can read it as another type.
|
||||
None => {
|
||||
let mut probe = start.clone();
|
||||
if probe
|
||||
.read_with_context::<MaybeRef<Object<'a>>>(&self.ctx)
|
||||
.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let after = skip_unreadable_item(start, &self.ctx)?;
|
||||
let item = Object::Null(Null).cast::<T>()?;
|
||||
self.reader = after;
|
||||
Some(item)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+13
-8
@@ -100,9 +100,12 @@ impl<'a> Dict<'a> {
|
||||
pub fn entries(&self) -> impl Iterator<Item = (Name<'a>, MaybeRef<Object<'a>>)> + '_ {
|
||||
let mut sorted_keys = self.keys().collect::<Vec<_>>();
|
||||
sorted_keys.sort_by(|n1, n2| n1.as_ref().cmp(n2.as_ref()));
|
||||
sorted_keys.into_iter().map(|k| {
|
||||
let obj = self.get_raw(k.deref()).unwrap();
|
||||
(k, obj)
|
||||
// PdfCraft patch (46): an entry whose value the first pass skipped but no object is read
|
||||
// from (a lone sign such as `+` or `++`) is left out, as `get` leaves it unread, rather
|
||||
// than unwrapping the failed read.
|
||||
sorted_keys.into_iter().filter_map(|k| {
|
||||
let obj = self.get_raw(k.deref())?;
|
||||
Some((k, obj))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -163,11 +166,13 @@ impl Debug for Dict<'_> {
|
||||
|
||||
for (key, val) in offsets {
|
||||
r.jump(*val);
|
||||
debug_struct.field(
|
||||
&format!("{:?}", key.as_str()),
|
||||
&r.read_with_context::<MaybeRef<Object<'_>>>(&ReaderContext::dummy())
|
||||
.unwrap(),
|
||||
);
|
||||
// PdfCraft patch (46): an entry no object is read from is left out, as in
|
||||
// `entries`, instead of unwrapping the failed read.
|
||||
if let Some(value) =
|
||||
r.read_with_context::<MaybeRef<Object<'_>>>(&ReaderContext::dummy())
|
||||
{
|
||||
debug_struct.field(&format!("{:?}", key.as_str()), &value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
Reference in New Issue
Block a user