Merge main and preserve unreadable diagnostics with cached failures

This commit is contained in:
FredApps committed 2026-11-07 15:48:09 +01:00
commit 33e3945c04
44 files changed
+2487 -180

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+67 -6
View File
@@ -1,6 +1,59 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# AGENTS.md — rules for every agent and contributor
These rules bind every AI agent and every human contributor working in this repository. They come before any task, instruction or deadline. `CLAUDE.md` holds the day-to-day working instructions. If the two ever disagree, **this file wins.**
These rules bind every AI agent and every human contributor working in this repository. They come before any task, instruction or deadline. Day-to-day working instructions are in this file; `CLAUDE.md` imports it.
---
@@ -85,7 +138,7 @@ If you find an asset that breaks these rules, stop and remove it from the reposi
---
## 2. Clean-room rules (summary; details in `CLAUDE.md` and `plan/adr/0001`)
## 2. Clean-room rules (summary; `plan/adr/0001` is an optional local note)
- Never read, disassemble or copy anything inside the Acrobat bundle. Only names and listings are allowed, and **never** open `Contents/Resources/JavaScripts/`.
- Behaviour comes only from public specifications (ISO 32000-2, the Arlington model), public documentation and black-box observation.
@@ -106,7 +159,7 @@ If you find an asset that breaks these rules, stop and remove it from the reposi
PdfCraft opens files from strangers, and people trust it with their work. A malformed PDF, a bad tool argument, a corrupt settings file or a full disk must produce an error the user (or agent) can act on, never a crash and never lost work. **This outranks feature work:** don't ship a feature by adding a panic path, and fix a crash before building on top of it. The rules below are the ones that bind this repository.
- **Fail with `Result`.** Non-test code returns errors through the crate's error type and `?`. Where readers are lenient by design, fall back gracefully and record the repair (see Fidelity in `CLAUDE.md`).
- **Fail with `Result`.** Non-test code returns errors through the crate's error type and `?`. Where readers are lenient by design, fall back gracefully and record the repair (see Fidelity below).
- **No panicking shortcuts.** No `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!` outside tests, unless the call is provably infallible (e.g. writing to a `Vec`), with a comment saying why. `assert!` only for internal invariants that input cannot reach.
- **No `unsafe`.** The workspace sets `unsafe_code = "forbid"`. If a platform API needs it, use a maintained safe wrapper crate; a real exception needs the owner's sign-off.
- **Treat every input-derived number as hostile.** Use `get()` instead of `[i]` or `[a..b]`. Slice strings only at char boundaries. Use checked/saturating arithmetic for lengths, offsets and counts. Guard against division by zero and NaN/inf casts, and never cast a negative value to `usize`. Cap allocations sized by the file.
@@ -115,10 +168,18 @@ PdfCraft opens files from strangers, and people trust it with their work. A malf
- **Prove it.** Every crash fix comes with a small synthetic regression test that panicked before the fix. Turn fuzzer findings (`cargo xtask fuzz`) into such tests before fixing them.
- **Enforced by clippy.** Root `clippy.toml` lets tests use `unwrap`/`expect`/`panic!`. A crate that is clean carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new crates start with it.
## 5. Everything else
## 5. Page interaction, fidelity and gates
Follow `CLAUDE.md`. It covers quality gates, layering, commit rules and how to run and look at the app.
- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd. `cos`, `filters`, `crypt` and `arlington` stay standalone.
- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state. `page_pointer::tests::page_modules_read_the_pointer_only_through_page_pointer` enforces it.
- **Page cursor.** Page modules claim the cursor for what is under the pointer (`view.cursor.claim`, `crates/ui-egui/src/canvas/page_cursor.rs`) and never set it themselves. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.
- **Page presses.** A page module decides what is under a point in one hit test (`Hit` in `crates/ui-egui/src/canvas/page_router.rs`) and acts on a press only through that router. `page_pointer::tests::page_modules_act_on_a_press_only_through_the_router` enforces it.
- **Fidelity.** The PDF object graph is the model. Preserve unknown data. Saves are incremental unless a full rewrite is required. Never silently drop or repair data without recording it.
- **Fonts** are the optional build input `CRAFT_FONTS_DIR`. Code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty.
- **Quality gates** before every commit: `cargo fmt --check`, clippy with `-D warnings`, the tests, `cargo xtask layers`, `cargo xtask assets`, and the wasm check. New workspace crates include `workspace = true` under `[lints]`. Scope `cargo clippy -p <crate> --all-targets -- -D warnings` and `cargo test -p <crate>` to the crates you touched; the workspace sweep is CI's job.
- **Review at four zooms** as you go: the clause, the function, the module, and the project (layering, wasm, undo, save fidelity, a matching automation tool, an honest `parity/` entry). Prove a test fails before the fix by reverting the fix once.
- `plan/` is an optional gitignored notebook. Do not ask for it and do not stop when it is absent. Public status is [`ROADMAP.md`](ROADMAP.md), [`docs/gaps.md`](docs/gaps.md) and [`docs/roadmap.md`](docs/roadmap.md). "Shipped" in `parity/` means exists and tested, not parity with Acrobat.
- `cargo run -p pdfcraft -- <file.pdf>` opens the app. `pdfcraft-cli run` drives the engine headlessly. `cargo xtask fuzz` findings stay in `fuzz-out/` and become synthetic tests. For UI work, look at a screenshot from `--control` or the `shot` example.
## Contributor credits (About window)
+1 -65
View File
@@ -1,65 +1 @@
# PdfCraft — instructions for agents
PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Adobe Acrobat Pro parity. It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. It is the sibling of `../photocraft` (a Photoshop-class editor) and follows the same conventions.
## Start every session here
1. Read `plan/STATUS.md`: the current milestone, the next unchecked task and any blockers. `ROADMAP.md` is the one-page summary (stage, numbers, progress log) and `docs/roadmap.md` the milestone table; at the end of every session update the milestone row and add a line to the ROADMAP.md progress log.
- Read `docs/gaps.md` (the ranked gaps: Acrobat interop, the open-issue backlog, the renderer and a fidelity harness, editing existing content, Pro workflows, 1.0 polish) and `docs/target-app-parity.md` (the numbers and how they are measured) before choosing work. Prefer the gaps over new P2/P3 features, and keep both documents true when things change (`docs/` progress docs carry a status line and a revision history).
- "Shipped" in `parity/` means "exists and tested", not "as good as Acrobat". Don't mark a feature shipped on a generic test, and say in its notes what is still missing.
2. Read that task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README of the crate you're touching.
3. Follow the **autonomous operation protocol** in `plan/execution-plan.md` §7 (orient → plan → implement + test → verify → record → commit). Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local-only, like PhotoCraft). The machine-readable parity checklist lives in `parity/` (committed).
## Non-negotiables
- **Assets: read `AGENTS.md` §1 before adding or showing any icon, image, font or document.** No assets from Adobe products, ever. Only openly licensed or contributor-original assets are allowed, each with an entry in `ATTRIBUTION.toml`. `cargo xtask assets` enforces this. `AGENTS.md` overrides this file.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts).** Never commit font files here (`AGENTS.md` §1.4). It is the optional build input `CRAFT_FONTS_DIR`: `git clone https://github.com/storytold/craft-fonts ../craft-fonts && CRAFT_FONTS_DIR=../craft-fonts cargo test --workspace` embeds the Japanese fonts (UI fallback, Japanese text in edited PDFs) and runs their tests, which otherwise skip. Code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty.
- **Clean-room.**
- Never read, disassemble or copy anything inside the Acrobat bundle (names and listings only). **Never open `Contents/Resources/JavaScripts/`.**
- Behaviour comes from public docs, specs (ISO 32000-2, the Arlington model) and black-box observation (`plan/acrobat/`).
- Never copy GPL/AGPL code. MuPDF, Ghostscript, Poppler, veraPDF and DSS run only as external oracle processes.
- See `plan/README.md` §Clean-room and `plan/adr/0001`.
- **Privacy.** When observing Acrobat, use synthetic fixtures only. Never capture the Home view, recent files or account info. Capture by window id (`plan/acrobat/tools/`). Never commit Acrobat outputs, corpus files or personal data.
- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd (`plan/architecture.md` §3). `cos`/`filters`/`crypt`/`arlington` stay standalone.
- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state (`hover_pos`, `interact_pos`, `latest_pos`, `press_origin`, button reads); `page_pointer::tests::page_modules_read_the_pointer_only_through_page_pointer` enforces it.
- **Page cursor.** Page modules claim the cursor for what is under the pointer (`view.cursor.claim(Layer::…, icon)`, `crates/ui-egui/src/canvas/page_cursor.rs`), never set it (`set_cursor_icon`, `cursor_icon =`, `on_hover_cursor`); `document_area` sets it once, from the claim on the highest layer the active tool reaches. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.
- **Page presses.** A page module decides what of its own is under a point in one hit test, which returns a `Hit` (owner, layer, cursor, tip; `crates/ui-egui/src/canvas/page_router.rs`) and gives its cursor, its tip and its press. It acts on a press only when the press is its own or, for the active tool, nobody's: the page view tells it which (`PagePress`: its own, nobody's, or another page's), and it never tests the press point again or asks another module whether it wants it. Escape cancels any press the pages hold (`cancel_on_escape`), and that press is ignored until the button is up. `page_pointer::tests::page_modules_act_on_a_press_only_through_the_router` enforces it.
- **Fidelity.** The PDF object graph is the model. Preserve unknown data. Saves are incremental unless a full rewrite is required. Never silently drop or repair data without recording it.
- **Never panic.** Every PDF, script, MCP call, settings file and keystroke is untrusted input, and none of it may crash the app or lose the user's work. This outranks feature work. Return `Result` (the crate's error enum) and propagate with `?`, or fall back leniently and record it. In non-test code:
- No `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` unless it is provably infallible, with a comment saying why.
- No indexing or slicing with input-derived positions (use `get`, and slice strings only at char boundaries).
- Use checked or saturating arithmetic on input-derived numbers, and guard against division by zero and NaN/inf casts.
- Cap allocations sized by input, and bound recursion with depth limits or seen-sets.
- Handle lock poisoning.
- No `unsafe` (`unsafe_code = "forbid"`).
- Every crash fix gets a synthetic regression test. See `AGENTS.md` §4.
- **Rust only** in the product and build (`xtask`). No handwritten JS/TS.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Review every update as you make it, at four zooms.** Not an end-of-task pass — a per-update habit, so a defect never gets built on. **Clause:** checked arithmetic, `get()` not `[i]`, char-boundary slicing, the right error through `?`, `<` against `<=`, the 1-based/0-based seam, capped allocations. **Function:** is it total — name an input that panics; walk empty, zero, max, malformed, cyclic; is the return type honest. **File/module:** two sources of truth, dead or duplicated code, is the public surface still smallest and the doc comment still true. **Project:** layering, wasm, undo/redo, save fidelity, encryption and permissions, a matching `automation` tool or registry entry, and whether a `parity/` status or note just became untrue. Scale the zoom to the change, and fix what a level turns up before widening.
- Tests mirror the zooms: property → unit → crate integration → end-to-end.
- **Prove a test fails before the fix by actually reverting the fix.** A test nobody has seen fail is not evidence. This has caught two worthless tests in this repo: one confinement test passed with path resolution switched off entirely, because the tools failed on a nonexistent document id before reaching the path.
- **Rebasing is a review step, not a mechanical one.** Read every hunk you resolve, and the auto-merged hunks in the files you touched too — `main` moves fast enough that a file can change by hundreds of lines under a branch.
- **External PRs are held to safety, security and completeness before style.** Provenance first (no Adobe-derived asset, no committed font, no copied GPL/AGPL code, behaviour from the spec and not from reading another implementation), then no new panic path or `unsafe`, then `--root` confinement on every path including ones reached by nested dispatch, opt-in-only MCP and control channel, no new outbound network, then a headless `automation` tool, tests at the right zoom and an honest `parity/` entry. Provenance is the part a contributor cannot be expected to know, and the only part that cannot be undone after merge.
- **Quality gates** before every commit: `cargo fmt --check`, clippy with `-D warnings`, the tests, `cargo xtask layers`, `cargo xtask assets`, and the wasm check once `xtask ci` exists (M0).
- New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare the required crate-level lint attributes before modules or other crate items; crate-level `//!` documentation may precede them.
- **Scope builds and tests to the crates you touched** — `cargo clippy -p <crate> -j 2 --all-targets` and `cargo test -p <crate> -j 2`, under a `timeout`. A full `--workspace` build has locked up a development machine's CPU; it is CI's job and CI runs it on every PR. Run the workspace sweep locally only when you have a reason to and the machine is free.
- **Check for existing work before starting a fix or feature.** Search the issues and PRs, open and closed, with `gh issue list -R storytold/pdfcraft --state all --search "<terms>"` and the same with `gh pr list` (try a few phrasings), and check whether a merged fix is already on `main` (`git merge-base --is-ancestor <commit> origin/main`). If one is, the report is likely from an older build: say so rather than fixing it again. If an open PR covers it, review or build on that PR instead of opening a competing one. If an issue exists, reference it in the PR (`Fixes #123`).
- **Commits and PRs:** `main` is the only integration branch and is **never pushed to directly**. Branch from an up-to-date `main` as `<type>/<slug>` (`feat/`, `fix/`, `docs/`, `chore/`, `refactor/`), one task id per commit (e.g. `M1.4: xref stream reader`), commit only green states, and open a PR into `main` using `.github/pull_request_template.md`. Merge only when CI is green.
- **`main` moves fast enough that PRs rot.** It took 396 commits in the three days to 2026-10-12, and most open PRs are conflicting at any given time. Rebase your own branch the same day `main` moves under it, and ask the author to rebase theirs — never rewrite a contributor's branch. Conflict risk tracks how *contested* the files are, not how large the change is: tooling, tests and docs are nearly free, while `crates/fonts`, `ui-egui` and the i18n catalogues are where several people collide at once.
## Running and looking at the app
- `cargo run -p pdfcraft -- <file.pdf>` opens the desktop app.
- `cargo run -p pdfcraft-cli -- run --script steps.json --root DIR` drives the engine headlessly through the automation tools (`pdfcraft-cli tools` lists them). Use it, together with `page_render`, to check engine changes. `pdfcraft-cli mcp` is the opt-in MCP server (AGENTS.md §3).
- `cargo xtask fuzz --time 300` mutation-fuzzes open/render/edit/save in child processes. Findings land in `fuzz-out/findings/` (git-ignored; never commit corpus-derived files). Turn every real finding into a small synthetic regression test before fixing it.
- `cargo xtask parity [--partial]` reports Acrobat-parity progress from `parity/acrobat-features.toml`. Update the entry when a feature ships.
- `cargo xtask demo-pdf` builds `dist/demo/pdfcraft-showcase.pdf` (needs Chrome) for visual checks.
- For UI work, **look at the result**. Either launch `pdfcraft --control FILE doc.pdf` and use `pdfcraft-cli ui --control FILE screenshot --out x.png` (plus `inspect`, `click`, `key`, `type`, `command`, `set`), or take a headless shot with `cargo run -p pdfcraft-ui-egui --example shot`. Compare against `plan/acrobat/02-ui-ux.md`. Control-channel tests use kittest (`crates/ui-egui/tests/control.rs`).
- Parallel agents: use a separate `CARGO_TARGET_DIR` per agent and separate git worktrees.
## Current bootstrap debt (tracked in STATUS.md)
- `pdfcraft-render` renders through the `hayro` crate directly and inspects documents through `lopdf`. Both get replaced by `cos` / `model` / the DisplayList device (M1–M2, ADR-0004).
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
@AGENTS.md
Generated
+14 -1
View File
@@ -1312,10 +1312,21 @@ dependencies = [
"zip",
]
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
dependencies = [
"js-sys",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
]
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
dependencies = [
"wasm-bindgen",
"web-sys",
@@ -4754,11 +4765,13 @@ dependencies = [
name = "pdfcraft-web"
version = "0.18.1"
dependencies = [
"craft-web-api",
"craft-web-host",
"eframe",
"egui",
"js-sys",
"pdfcraft-ui-egui",
"serde_json",
"wasm-bindgen-futures",
"web-sys",
]
+4 -1
View File
@@ -12,9 +12,12 @@ workspace = true
[dependencies]
pdfcraft-ui-egui = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" }
# The page command API (storytold/craft-libs#413): window.pdfcraft over the UI control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen-futures = "0.4"
+127
View File
@@ -0,0 +1,127 @@
//! `window.pdfcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the app's
//! UI control channel (`pdfcraft_ui_egui::control`), opt-in with `?control`.
//!
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
//! `screenshot`, as promises with a timeout). This module is PdfCraft's part: a [`Request`] that
//! sends each call through the app's [`ControlClient`] and waits for the reply, and the table that
//! names PdfCraft's methods: its control channel drives the UI, so `commands` is `ui.commands`,
//! `execute` runs a registry command with `ui.command`, `docInspect` is `ui.state` and `uiInspect`
//! is `ui.inspect`.
//!
//! The channel keeps the accessibility tree of every frame, so it is off unless the page asks for it
//! (`?control`), as FigCraft's is. PdfCraft's control requests cannot be withdrawn, so a call the page
//! gave up on may still run (or be rejected) when the app reaches it, as it does for a desktop client that timed out.
use serde_json::{Value, json};
/// The reply of a control request as the protocol's `{ok, result}` / `{ok: false, error}` object.
fn reply_object(reply: Result<Value, String>) -> Value {
match reply {
Ok(result) => json!({"ok": true, "result": result}),
Err(error) => json!({"ok": false, "error": error}),
}
}
/// The params of `ui.command`. `execute(command, params)` sends `{command, params}`; `ui.command`
/// takes `{id}` (and `params` for `ui.panel`). A request that already names an `id` is the page's own
/// `request("ui.command", {id})` and goes through unchanged.
fn command_params(params: Value) -> Value {
match params.get("command").and_then(Value::as_str) {
Some(command) if params.get("id").is_none() => json!({"id": command, "params": params.get("params").cloned().unwrap_or(Value::Null)}),
_ => params,
}
}
#[cfg(target_arch = "wasm32")]
pub use web::install;
#[cfg(target_arch = "wasm32")]
mod web {
use std::rc::Rc;
use std::sync::mpsc::{Receiver, TryRecvError};
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use pdfcraft_ui_egui::control::{ControlClient, Reply};
use serde_json::{Value, json};
use wasm_bindgen_futures::JsFuture;
use super::{command_params, reply_object};
/// The app id in `window.<app>`.
const APP: &str = "pdfcraft";
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
const POLL_MS: i32 = 16;
/// PdfCraft's control methods behind each function.
fn methods() -> Methods {
Methods {
commands: Some("ui.commands"),
execute: Some("ui.command"),
doc_inspect: Some("ui.state"),
ui_inspect: Some("ui.inspect"),
screenshot: Some("ui.screenshot"),
}
}
/// Put `window.pdfcraft` on the page, sending its calls through `client`. An existing
/// `window.pdfcraft` keeps the functions it already has.
pub fn install(client: ControlClient) {
let request: Request = Rc::new(move |method, params| {
let params = if method == "ui.command" { command_params(params) } else { params };
Box::pin(wait(client.send(&method, params)))
});
if let Err(e) = Rc::new(PageApi::new(APP, methods(), request)).install() {
eframe::web_sys::console::warn_1(&format!("PdfCraft: couldn't install window.{APP}: {e:?}").into());
}
}
/// The app's reply, polled about once a frame.
async fn wait(reply: Receiver<Reply>) -> Value {
loop {
match reply.try_recv() {
Ok(reply) => return reply_object(reply),
Err(TryRecvError::Empty) => sleep(POLL_MS).await,
Err(TryRecvError::Disconnected) => return json!({"ok": false, "error": "the app dropped the request"}),
}
}
}
async fn sleep(ms: i32) {
let promise = js_sys::Promise::new(&mut |resolve, _| {
if let Some(window) = web_sys::window() {
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
}
});
let _ = JsFuture::from(promise).await;
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn execute_becomes_a_ui_command_by_id() {
assert_eq!(command_params(json!({"command": "file.word_count", "params": {"a": 1}})), json!({"id": "file.word_count", "params": {"a": 1}}));
assert_eq!(command_params(json!({"command": "file.save", "params": {}})), json!({"id": "file.save", "params": {}}));
}
#[test]
fn a_request_that_names_an_id_goes_through_unchanged() {
let own = json!({"id": "file.save"});
assert_eq!(command_params(own.clone()), own);
let both = json!({"id": "ui.panel", "command": "x", "params": {"reset": true}});
assert_eq!(command_params(both.clone()), both, "an id wins over a command");
assert_eq!(command_params(json!({})), json!({}));
}
#[test]
fn replies_become_the_protocols_objects() {
assert_eq!(reply_object(Ok(json!({"n": 1}))), json!({"ok": true, "result": {"n": 1}}));
assert_eq!(reply_object(Err("boom".to_string())), json!({"ok": false, "error": "boom"}));
}
}
+8
View File
@@ -3,6 +3,9 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(any(target_arch = "wasm32", test))]
mod api;
#[cfg(target_arch = "wasm32")]
fn main() {
use pdfcraft_ui_egui::PdfCraftApp;
@@ -68,6 +71,11 @@ fn main() {
&"PdfCraft: ?host=parent needs a framing page on the same origin; saves download instead".into(),
);
}
// `?control`: `window.pdfcraft`, the page's command API (`api`). Opt-in: the control
// channel keeps the accessibility tree of every frame.
if query_param("control").is_some() {
api::install(app.attach_control(&cc.egui_ctx));
}
Ok(Box::new(app))
}),
)
+5
View File
@@ -26,6 +26,11 @@ its undo/redo history.
`page_add_text`, `content_update` and `text_edit` take per-line `aligns`. An `"inherit"` entry
follows the box-level `align`; legacy `null` entries remain accepted with the same meaning.
`page_add_text` and `content_update` take one of `color` (`#RRGGBB` or a name, painted in
DeviceRGB), `gray` (0 black to 1 white, DeviceGray `g`) and `cmyk` (`[c, m, y, k]`, each 0 to 1,
DeviceCMYK `k`), so text added to a print file can be 100 K black. `content_list` reports `gray` or
`cmyk` for such text.
`Content` is `Json(Value)` or `Png { data, width, height }`. Errors are `UnknownTool`, `InvalidArgs` (the call didn't match the schema) or `Failed` (a readable message for the agent).
## Conventions
+36 -5
View File
@@ -2,7 +2,7 @@
//! move/resize/retype/restyle it, delete it. Geometry is in points from the top-left of the
//! displayed page (y down), like every other tool.
use pdfcraft_engine::{ADDED_CHAR_SPACING_LIMIT, AddedContent, AddedText, Edit, FontFamily, TextAlign};
use pdfcraft_engine::{ADDED_CHAR_SPACING_LIMIT, AddedContent, AddedText, Edit, FontFamily, TextAlign, TextInk};
use serde_json::{Value, json};
use crate::comments::parse_color;
@@ -30,6 +30,27 @@ fn rect_arg(a: &Args, key: &str) -> Result<Option<[f64; 4]>> {
.transpose()
}
const INK_ARGS: &str = "give one of color (#RRGGBB or a name), gray (0 black to 1 white) and cmyk ([c, m, y, k], each 0 to 1)";
/// `gray` or `cmyk`: the text painted in DeviceGray or DeviceCMYK rather than RGB. At most one of
/// them and `color`.
fn ink_arg(a: &Args) -> Result<Option<TextInk>> {
if ["color", "gray", "cmyk"].iter().filter(|k| a.get(k).is_some()).count() > 1 {
return Err(bad(INK_ARGS));
}
let unit = |v: Option<f64>, key: &str| v.filter(|v| (0.0..=1.0).contains(v)).ok_or_else(|| bad(format!("{key} takes numbers from 0 to 1")));
if let Some(g) = a.get("gray") {
return Ok(Some(TextInk::Gray(unit(g.as_f64(), "gray")?)));
}
let Some(c) = a.get("cmyk") else { return Ok(None) };
let parts = c.as_array().filter(|p| p.len() == 4).ok_or_else(|| bad("cmyk must be [c, m, y, k]"))?;
let mut cmyk = [0.0; 4];
for (out, v) in cmyk.iter_mut().zip(parts) {
*out = unit(v.as_f64(), "cmyk")?;
}
Ok(Some(TextInk::Cmyk(cmyk)))
}
/// Apply the style arguments to `t`.
fn style(a: &Args, t: &mut AddedText) -> Result<()> {
if let Some(s) = a.opt_num("size")? {
@@ -49,8 +70,12 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {
if let Some(i) = a.opt_bool("italic")? {
t.italic = i;
}
if let Some(c) = a.opt_str("color")? {
t.color = parse_color(c)?;
if let Some(ink) = ink_arg(a)? {
t.set_ink(Some(ink));
} else if let Some(c) = a.opt_str("color")? {
// An RGB colour paints in RGB, even one that is the ink's look.
t.set_ink(None);
t.set_color(parse_color(c)?);
}
if let Some(al) = a.opt_str("align")? {
t.align = parse_align(al)?;
@@ -124,6 +149,12 @@ impl Automation {
v["bold"] = json!(t.bold);
v["italic"] = json!(t.italic);
v["char_spacing"] = json!(t.char_spacing);
// Text painted in a print colour space says so; RGB text has neither.
match t.painted_ink() {
Some(TextInk::Gray(g)) => v["gray"] = json!(g),
Some(TextInk::Cmyk(c)) => v["cmyk"] = json!(c),
None => {}
}
}
AddedContent::Image(_) => v["type"] = json!("image"),
}
@@ -205,8 +236,8 @@ impl Automation {
if a.get("text").is_some() {
return Err(bad("images have no text"));
}
if ["font", "size", "bold", "italic", "color", "align", "aligns", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
return Err(bad("font, size, bold, italic, color, align, aligns and char_spacing apply to text"));
if ["font", "size", "bold", "italic", "color", "gray", "cmyk", "align", "aligns", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
return Err(bad("font, size, bold, italic, color, gray, cmyk, align, aligns and char_spacing apply to text"));
}
if let Some(deg) = a.opt_int("rotate")? {
if deg.rem_euclid(90) != 0 {
+50 -2
View File
@@ -20,6 +20,10 @@ pub(crate) const FIND_MAX_WARNINGS: usize = 100;
pub(crate) const FIND_MAX_WARNING_BYTES: usize = 1024;
/// HTML that one `text_extract` with `format: "html"` returns across all its pages; a page past
/// it gets none. `html_truncated` covers this and any page whose own copy hit its caps.
const MAX_EXTRACT_HTML_BYTES: usize = 32 << 20;
impl Automation {
// ---- pages and text ----------------------------------------------------------------------
@@ -201,6 +205,16 @@ impl Automation {
}
pub(crate) fn text_extract(&mut self, a: &Args) -> Result<Value> {
self.text_extract_within(a, MAX_EXTRACT_HTML_BYTES)
}
/// [`Self::text_extract`] with at most `html_budget` bytes of HTML across all pages.
pub(crate) fn text_extract_within(&mut self, a: &Args, html_budget: usize) -> Result<Value> {
let html = match a.opt_str("format")?.unwrap_or("text") {
"text" => false,
"html" => true,
other => return Err(ToolError::InvalidArgs(format!("format must be \"text\" or \"html\", not {other:?}"))),
};
let doc = self.doc_to_copy(a)?;
let id = doc.id;
let pages = match a.opt_ints("pages")? {
@@ -214,8 +228,42 @@ impl Automation {
Some(r) => t.column_text(&t.glyphs_in(r)),
None => t.plain_text(),
};
let out: Vec<Value> = pages.iter().zip(texts).map(|(p, t)| json!({ "page": p + 1, "text": text(&t) })).collect();
Ok(json!({ "pages": out }))
let doc = self.doc(a)?;
let mut out = Vec::with_capacity(pages.len());
// `spent`: the budget ran out, so later pages get no HTML. `cut`: some page's HTML is
// missing part of its text, by the budget or by the copy's own caps.
let (mut html_left, mut spent, mut cut) = (html_budget, false, false);
for (&p, t) in pages.iter().zip(texts) {
let mut page = json!({ "page": p + 1, "text": text(&t) });
if html {
// Copy with formatting: the same glyphs as an HTML fragment, within one budget for
// the whole call; a page past it gets none and the call says so.
let mut copy = pdfcraft_engine::RichCopy::default();
if !spent {
let glyphs: Vec<usize> = match rect {
Some(r) => t.glyphs_in(r),
None => (0..t.glyphs.len()).collect(),
};
copy = doc.rich_copy(p, &t, &glyphs).map_err(failed)?;
match html_left.checked_sub(copy.html.len()) {
Some(left) => html_left = left,
None => {
spent = true;
copy = pdfcraft_engine::RichCopy::default();
}
}
}
cut |= spent || copy.truncated;
page["html"] = json!(copy.html);
page["styles_incomplete"] = json!(copy.styles_incomplete || spent);
}
out.push(page);
}
let mut result = json!({ "pages": out });
if html {
result["html_truncated"] = json!(cut);
}
Ok(result)
}
/// Matches in document order, extracting page text in growing batches and stopping as soon as
+32
View File
@@ -550,3 +550,35 @@ fn tool_file_reads_refuse_inputs_exceeding_512_mib() {
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn text_extract_html_has_one_budget_across_pages() {
let mut a = Automation::new();
let id = search_document(&mut a, 3);
let args = json!({ "doc": id.0, "format": "html" });
let full = a.text_extract(&Args(&args)).unwrap();
assert_eq!(full["html_truncated"], false);
let sizes: Vec<usize> = full["pages"].as_array().unwrap().iter().map(|p| p["html"].as_str().unwrap().len()).collect();
assert!(sizes.iter().all(|n| *n > 0), "{full}");
// Room for two pages: the third gets no HTML, and the call says so.
let capped = a.text_extract_within(&Args(&args), sizes[0] + sizes[1] + sizes[2] - 1).unwrap();
let pages = capped["pages"].as_array().unwrap();
assert_eq!(capped["html_truncated"], true);
assert_eq!(pages[1]["html"], full["pages"][1]["html"]);
assert_eq!(pages[2]["html"], "");
assert_eq!(pages[2]["styles_incomplete"], true);
assert_eq!(pages[2]["text"], "Page 3", "the plain text is not capped by the HTML budget");
// Plain text alone says nothing about HTML.
assert!(a.text_extract(&Args(&json!({ "doc": id.0 }))).unwrap().get("html_truncated").is_none());
// A smaller page after the one that overflowed still gets none: "Page 1" fits what "Page 10"
// did not.
let id = search_document(&mut a, 10);
let args = json!({ "doc": id.0, "pages": [10, 1], "format": "html" });
let full = a.text_extract(&Args(&args)).unwrap();
let (ten, one) = (full["pages"][0]["html"].as_str().unwrap().len(), full["pages"][1]["html"].as_str().unwrap().len());
assert!(one < ten, "{full}");
let capped = a.text_extract_within(&Args(&args), ten - 1).unwrap();
assert_eq!(capped["pages"][0]["html"], "");
assert_eq!(capped["pages"][1]["html"], "", "no HTML after the budget ran out: {capped}");
assert_eq!(capped["pages"][1]["styles_incomplete"], true);
}
+10 -5
View File
@@ -216,13 +216,14 @@ pub fn tools() -> Vec<ToolDef> {
.with(schema(json!({ "doc": doc(), "pages": pages("to count (default: all)"),
"exclude_tables": { "type": "boolean" }, "exclude_code": { "type": "boolean" }, "exclude_images": { "type": "boolean" }
}), &["doc"])),
t("text_extract", "Extract text", "Extract the text of some or all pages, in reading order. With rect, only the text inside that rectangle on each page, as Column select takes it: one row per visual line, side-by-side pieces (table cells) separated by a tab.")
t("text_extract", "Extract text", "Extract the text of some or all pages, in reading order. With rect, only the text inside that rectangle on each page, as Column select takes it: one row per visual line, side-by-side pieces (table cells) separated by a tab. With format \"html\", each page also carries html, the same text as Copy with formatting puts on the clipboard (paragraphs, bold, italic, size, colour and font family), and styles_incomplete when some styles had to be left out. With rect, the html is that text in line order, not split into the column's rows and cells. The HTML of one call is capped at 32 MiB in total; pages past the cap carry empty html with styles_incomplete. html_truncated is set when that cap is reached or when a page's own copy was cut at its span or size cap.")
.ro()
.cmd("edit.column_select")
.with(schema(
json!({
"doc": doc(), "pages": pages("to extract (default: all)"),
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Column select: [x0, y0, x1, y1] in points from the top-left of the displayed page; a glyph counts when its centre is inside." }
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Column select: [x0, y0, x1, y1] in points from the top-left of the displayed page; a glyph counts when its centre is inside." },
"format": { "type": "string", "enum": ["text", "html"], "description": "text (default) or html: also return each page's text as formatted HTML." }
}),
&["doc"],
)),
@@ -718,13 +719,13 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc"],
)),
t("content_list", "List added content", "Text and images added with page_add_text/page_add_image (or Edit a PDF ▸ Add content), per page with a 1-based index, rect (points from the top-left of the page), and text style.")
t("content_list", "List added content", "Text and images added with page_add_text/page_add_image (or Edit a PDF ▸ Add content), per page with a 1-based index, rect (points from the top-left of the page), and text style; text painted in gray or CMYK also has gray (its level) or cmyk ([c, m, y, k]).")
.ro()
.with(schema(json!({ "doc": doc() }), &["doc"])),
t(
"page_add_text",
"Add text to a page",
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right, char_spacing (points after each character). Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name, painted in RGB) or, for print, gray (0 black to 1 white, painted in DeviceGray) or cmyk ([c, m, y, k], each 0 to 1, painted in DeviceCMYK; [0, 0, 0, 1] is 100 K black), one of the three, align left/center/right, char_spacing (points after each character). Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
)
.cmd("edit.text")
.with(schema(
@@ -735,6 +736,8 @@ pub fn tools() -> Vec<ToolDef> {
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"gray": { "type": "number", "minimum": 0, "maximum": 1, "description": "DeviceGray level, 0 black to 1 white (instead of color)." },
"cmyk": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 1 }, "minItems": 4, "maxItems": 4, "description": "DeviceCMYK [c, m, y, k], each 0 to 1 (instead of color); [0, 0, 0, 1] is 100 K black." },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
"aligns": { "type": "array", "maxItems": 4096, "items": { "type": "string", "enum": ["left", "center", "right", "justify", "inherit"] }, "description": "Each paragraph's (line's) own alignment, by index; inherit (or legacy null) follows align." },
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
@@ -751,13 +754,15 @@ pub fn tools() -> Vec<ToolDef> {
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "path": { "type": "string" }, "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 } }),
&["doc", "page", "path"],
)),
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align, char_spacing in points) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color or gray or cmyk as page_add_text takes them, align, char_spacing in points) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
.with(schema(
json!({
"doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 }, "text": { "type": "string" },
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"gray": { "type": "number", "minimum": 0, "maximum": 1, "description": "DeviceGray level, 0 black to 1 white (instead of color)." },
"cmyk": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 1 }, "minItems": 4, "maxItems": 4, "description": "DeviceCMYK [c, m, y, k], each 0 to 1 (instead of color); [0, 0, 0, 1] is 100 K black." },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
"aligns": { "type": "array", "maxItems": 4096, "items": { "type": "string", "enum": ["left", "center", "right", "justify", "inherit"] }, "description": "Each paragraph's (line's) own alignment, by index; inherit (or legacy null) follows align." },
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
+137 -21
View File
@@ -2538,6 +2538,7 @@ fn protecting_through_tools() {
// Copying wasn't allowed either (#568): no text or images come out, though search works.
for (tool, args) in [
("text_extract", json!({ "doc": re })),
("text_extract", json!({ "doc": re, "format": "html" })),
("text_word_count", json!({ "doc": re })),
("text_paragraphs", json!({ "doc": re, "page": 1 })),
("doc_export_text", json!({ "doc": re, "path": "out.txt" })),
@@ -5214,6 +5215,83 @@ fn adding_content_through_tools() {
assert!(matches!(a.call("content_delete", &json!({ "doc": doc, "page": 1, "index": 5 })), Err(ToolError::Failed(_))));
}
/// #6440: `page_add_text` paints text in CMYK or gray for a print file, so its black is 100 K
/// (`0 0 0 1 k`) rather than DeviceRGB; `content_update` restyles it either way.
#[test]
fn added_text_takes_a_cmyk_or_gray_ink_through_tools() {
let dir = workdir("content-ink");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "page_add_text", json!({ "doc": doc, "page": 1, "text": "PROOF", "at": [20, 20], "cmyk": [0, 0, 0, 1] }));
ok(&mut a, "page_add_text", json!({ "doc": doc, "page": 1, "text": "Note", "at": [20, 80], "gray": 0.5 }));
let items = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
assert_eq!((&items[0]["cmyk"], &items[1]["gray"]), (&json!([0.0, 0.0, 0.0, 1.0]), &json!(0.5)));
// The item streams of the saved file.
let saved_items = |a: &mut Automation, name: &str| -> Vec<String> {
ok(a, "doc_save", json!({ "doc": doc, "path": name }));
let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join(name)).unwrap())).unwrap();
let page = &pdfcraft_model::pages(&saved)[0];
let list = saved.resolve(page.dict.get(b"Contents").unwrap()).as_array().cloned().unwrap();
list.iter()
.filter_map(|c| match &*saved.resolve(c) {
pdfcraft_cos::Object::Stream(s) if s.dict.name(b"PCMark") == Some(&b"Added"[..]) => {
Some(String::from_utf8_lossy(&s.decoded().unwrap()).into_owned())
}
_ => None,
})
.collect()
};
let streams = saved_items(&mut a, "ink.pdf");
assert!(streams[0].contains("0 0 0 1 k") && !streams[0].contains("rg"), "{}", streams[0]);
assert!(streams[1].contains("0.5 g") && !streams[1].contains("rg"), "{}", streams[1]);
// Restyled: to RGB with color, and back to CMYK.
ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 2, "color": "#000000" }));
ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 1, "cmyk": [1, 0, 0, 0] }));
let items = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
assert_eq!((&items[0]["cmyk"], items[1].get("gray")), (&json!([1.0, 0.0, 0.0, 0.0]), None));
let streams = saved_items(&mut a, "restyled.pdf");
assert!(streams[0].contains("1 0 0 0 k") && streams[1].contains("0 0 0 rg"), "{streams:?}");
// One colour at a time, four numbers from 0 to 1.
for bad in [
json!({ "color": "red", "cmyk": [0, 0, 0, 1] }),
json!({ "gray": 0.5, "cmyk": [0, 0, 0, 1] }),
json!({ "gray": 1.5 }),
json!({ "cmyk": [0, 0, 1] }),
json!({ "cmyk": [0, 0, 0, 1, 0] }),
json!({ "cmyk": [0, "x", 0, 1] }),
json!({ "cmyk": [0, 0, 0, -0.1] }),
] {
let mut args = json!({ "doc": doc, "page": 1, "text": "x", "at": [20, 200] });
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
assert!(matches!(a.call("page_add_text", &args), Err(ToolError::InvalidArgs(_))), "{bad}");
}
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["count"], 2, "nothing refused was added");
// content_update refuses them too, an image takes no ink, and a refused update changes nothing.
let mut png = Vec::new();
{
let mut enc = png::Encoder::new(&mut png, 40, 20);
enc.set_color(png::ColorType::Rgb);
let mut w = enc.write_header().unwrap();
w.write_image_data(&[200u8; 2400]).unwrap();
}
std::fs::write(dir.join("logo.png"), png).unwrap();
ok(&mut a, "page_add_image", json!({ "doc": doc, "page": 1, "path": "logo.png", "rect": [100, 200, 180, 240] }));
let before = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
for (index, bad) in [
(1, json!({ "gray": 0.5, "cmyk": [0, 0, 0, 1] })),
(2, json!({ "color": "red", "gray": 0.5 })),
(1, json!({ "size": 30, "cmyk": [0, 0, 0, 2] })),
(2, json!({ "bold": true, "gray": -1 })),
(3, json!({ "gray": 0.5 })),
(3, json!({ "cmyk": [0, 0, 0, 1] })),
] {
let mut args = json!({ "doc": doc, "page": 1, "index": index });
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
assert!(matches!(a.call("content_update", &args), Err(ToolError::InvalidArgs(_))), "{bad}");
}
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"], before, "a refused update changed nothing");
}
/// Edit ▸ Copy and Paste headlessly (#2636): an added text box or image, as it is, onto its own
/// page beside it, onto a point, and into another document.
#[test]
@@ -9311,27 +9389,15 @@ fn a_deleted_image_is_not_kept_by_reduce_or_optimize() {
/// page is turned with /Rotate 90.
fn table_pdf() -> Vec<u8> {
let body = "BT /F1 12 Tf 20 250 Td (Name) Tj 130 0 Td (Qty) Tj -130 -20 Td (Apple) Tj 130 0 Td (12) Tj -130 -20 Td (Pear) Tj 130 0 Td (7) Tj ET";
let objs = [
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Kids [4 0 R 5 0 R] /Count 2 /MediaBox [0 0 300 300] >>".to_string(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),
"<< /Type /Page /Parent 2 0 R /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>".to_string(),
"<< /Type /Page /Parent 2 0 R /Rotate 90 /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>".to_string(),
format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()),
];
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
let stream = format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len());
pdf_of(&[
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [4 0 R 5 0 R] /Count 2 /MediaBox [0 0 300 300] >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
"<< /Type /Page /Parent 2 0 R /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>",
"<< /Type /Page /Parent 2 0 R /Rotate 90 /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>",
&stream,
])
}
/// Issue #740: `text_extract` with `rect` takes what Column select takes, in the displayed-page
@@ -9372,6 +9438,56 @@ fn text_extract_with_a_rect_takes_one_column() {
}
}
/// Copy with formatting, headless: `format: "html"` adds each page's text as the HTML fragment
/// Copy puts on the clipboard, for the whole page or only what `rect` takes.
#[test]
fn text_extract_as_html_keeps_the_formatting() {
let dir = workdir("rich-copy");
std::fs::write(dir.join("table.pdf"), table_pdf()).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "table.pdf" }))["doc"].as_u64().unwrap();
let page = &ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1], "format": "html" }))["pages"][0];
let html = page["html"].as_str().unwrap();
assert!(html.starts_with("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:12pt\">Name"), "{html}");
assert!(html.contains("Pear") && html.contains("Qty"), "{html}");
assert_eq!(page["text"], "Name\nApple\nPear\nQty\n12\n7", "the plain text is unchanged");
assert_eq!(page["styles_incomplete"], false);
// Plain text by default: no html key.
assert!(ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1] }))["pages"][0].get("html").is_none());
// Only what the rect takes; nothing inside gives empty HTML.
let column = ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1], "rect": [120, 0, 300, 300], "format": "html" }));
let html = column["pages"][0]["html"].as_str().unwrap();
assert!(html.contains("Qty") && !html.contains("Name"), "{html}");
let none = ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1], "rect": [0, 0, 5, 5], "format": "html" }));
assert_eq!(none["pages"][0]["html"], "");
// An unknown format is refused.
for bad in [json!("rtf"), json!(1)] {
let e = a.call("text_extract", &json!({ "doc": doc, "format": bad })).unwrap_err();
assert!(matches!(e, ToolError::InvalidArgs(_)), "{bad}: {e}");
}
// Bold, italic, colour and size come through end to end.
let body = "BT /F1 18 Tf 20 250 Td (Big) Tj ET BT /F2 12 Tf 20 200 Td (Strong) Tj ET \
BT /F3 12 Tf 20 150 Td (Slanted) Tj ET BT 0 0 1 rg /F1 12 Tf 20 100 Td (Blue) Tj ET";
let stream = format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len());
let styled = pdf_of(&[
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>",
"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R /F3 7 0 R >> >> >>",
&stream,
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique >>",
]);
std::fs::write(dir.join("styled.pdf"), styled).unwrap();
let doc = ok(&mut a, "doc_open", json!({ "path": "styled.pdf" }))["doc"].as_u64().unwrap();
let page = &ok(&mut a, "text_extract", json!({ "doc": doc, "format": "html" }))["pages"][0];
let html = page["html"].as_str().unwrap();
assert!(html.contains("font-size:18pt\">Big"), "{html}");
assert!(html.contains("<strong>Strong</strong>"), "{html}");
assert!(html.contains("<em>Slanted</em>"), "{html}");
assert!(html.contains("color:#0000FF\">Blue"), "{html}");
}
#[test]
fn mixed_visual_region_edit_preview_save_reopen_and_undo_through_tools() {
use pdfcraft_cos::{Dict, Document, Object, Stream, write_incremental};
+3
View File
@@ -48,6 +48,9 @@ pub struct Document {
/// `fill_xref_gaps`.
located: Arc<BTreeMap<u32, (u64, u16)>>,
repair_log: Arc<Vec<String>>,
/// What loading each file object gave, a failure as well: a damaged object is otherwise
/// loaded again on every read, and a member of an object stream that can't be decoded
/// decodes the stream again (`Document::load`).
cache: Arc<Mutex<state::ObjectCache>>,
objstms: Arc<Mutex<HashMap<u32, Arc<ObjStm>>>>,
/// See [`Self::unreadable_objects`]. Shared by clones, like the caches: it describes the
+61 -25
View File
@@ -1,7 +1,9 @@
use std::collections::HashSet;
use super::reader::find;
use super::state::{LENGTHS, LoadGuard, ObjStm, ObjectReader, ReadState, Slot, SourceIdentity, held_bytes, objstm_member};
use super::state::{
LENGTHS, LoadGuard, ObjStm, ObjectReader, ReadState, Slot, SourceIdentity, loaded_bytes, note_overlay_read, objstm_member, overlay_reads,
};
use super::xref::{Revision, XrefEntry, XrefIndex};
use super::{
Arc, CosError, Cow, Dict, Document, Lexer, MAX_DECODED, MAX_JBIG2_GLOBALS, ObjRef, Object, Stream, is_whitespace, parse_indirect_shared,
@@ -530,34 +532,38 @@ impl Document {
}
pub fn try_get(&self, num: u32) -> Result<Arc<Object>, CosError> {
match self.overlay.get(&num) {
Some(Slot::Set(_, o) | Slot::RepairedSet(_, _, o)) => return Ok(o.clone()),
Some(Slot::Freed(_)) => return Ok(Arc::new(Object::Null)),
None => {}
if let Some(slot) = self.overlay.get(&num) {
note_overlay_read();
return Ok(match slot {
Slot::Set(_, o) | Slot::RepairedSet(_, _, o) => o.clone(),
Slot::Freed(_) => Arc::new(Object::Null),
});
}
if let Some(o) = self.cache.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
return Ok(o.clone());
if let Some(loaded) = self.cache.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
return loaded.clone();
}
// Loading can re-enter (indirect stream `/Length`, object streams); damaged files make
// cycles such as `6 0 obj << /Length 6 0 R >>`. Bound the nesting on every path.
let _guard =
LoadGuard::enter(num).ok_or_else(|| CosError::Syntax { offset: 0, detail: format!("reference cycle while loading object {num}") })?;
let _scope = crate::security::FollowScope::enter();
let obj = match self.load(num, 0) {
Ok(obj) => Arc::new(obj),
Err(e) => {
if !matches!(e, CosError::Poisoned) {
self.note_unreadable(num, || e.to_string());
}
return Err(e);
}
};
// The editing cache is bounded like the scan reader's: re-parsing a file-backed view
// is cheap, and returned objects outlive eviction.
let owned = held_bytes(&obj, &self.data, 0);
self.cache.lock().map_err(|_| CosError::Poisoned)?.insert(num, obj.clone(), owned);
self.evict_editor_cache_if_over_budget(num)?;
Ok(obj)
let edits_read = overlay_reads();
let loaded = self.load(num, 0).map(Arc::new);
if let Err(e) = &loaded
&& !matches!(e, CosError::Poisoned)
{
self.note_unreadable(num, || e.to_string());
}
// A failure is kept like an object, or every read of a damaged object loads it again. A
// poisoned lock says nothing about the object. Clones share the cache, so a load that read
// this document's edits (an edited object stream or `/Length`) is not kept.
if overlay_reads() == edits_read && !matches!(loaded, Err(CosError::Poisoned)) {
// The editing cache is bounded like the scan reader's: re-parsing a file-backed view
// is cheap, and returned objects outlive eviction.
self.cache.lock().map_err(|_| CosError::Poisoned)?.insert(num, loaded.clone(), loaded_bytes(&loaded, &self.data));
self.evict_editor_cache_if_over_budget(num)?;
}
loaded
}
/// Bounds for the editing cache: roomier than the scan reader's (128 objects / 8 MB)
@@ -669,11 +675,20 @@ impl Document {
None | Some(XrefEntry::Free { .. }) => Ok(Object::Null),
Some(XrefEntry::InFile { offset, .. }) => {
let resolve = |r: ObjRef| {
if let Some(known) = LENGTHS.with(|m| m.borrow().get(&r).copied()) {
if self.overlay.contains_key(&r.num) {
note_overlay_read();
}
// A length resolved through this document's edits counts as an edit read
// on every reuse.
if let Some((known, edits)) = LENGTHS.with(|m| m.borrow().get(&r).copied()) {
if edits {
note_overlay_read();
}
return known;
}
let edits_read = overlay_reads();
let length = self.try_get_reference(r).ok().and_then(|o| o.as_int());
LENGTHS.with(|m| m.borrow_mut().insert(r, length));
LENGTHS.with(|m| m.borrow_mut().insert(r, (length, overlay_reads() != edits_read)));
length
};
let off = offset as usize;
@@ -702,7 +717,9 @@ impl Document {
}
pub(super) fn objstm(&self, num: u32) -> Result<Arc<ObjStm>, CosError> {
if let Some(s) = self.objstms.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
// An edited or freed stream is this document's alone: clones share the parsed streams.
let edited = self.overlay.contains_key(&num);
if !edited && let Some(s) = self.objstms.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
return Ok(s.clone());
}
// A file entry that cannot place the stream (one that says it is itself compressed
@@ -710,6 +727,7 @@ impl Document {
// header, as a plain object with a wrong offset is. An edited or freed stream, in the
// overlay or in a saved revision's table, is what that says it is: the file's copy
// must not come back.
let edits_read = overlay_reads();
let loaded = match self.try_get(num) {
Ok(o) if matches!(*o, Object::Stream(_)) => o,
_ if self.overlay.contains_key(&num) || matches!(self.xref_entry(num), Some(XrefEntry::Free { .. })) => {
@@ -717,6 +735,8 @@ impl Document {
}
_ => Arc::new(self.scan_for(num).map(|(id, o)| self.decrypted(id, o)).ok_or(CosError::MissingObject(num))?),
};
// A stream whose load read this document's edits (its `/Length`) is as much its own as an edited one.
let own = edited || overlay_reads() != edits_read;
let Object::Stream(s) = &*loaded else { return Err(CosError::MissingObject(num)) };
let n = s.dict.int(b"N").unwrap_or(0).clamp(0, 1_000_000) as usize;
let first = usize::try_from(s.dict.int(b"First").unwrap_or(0).max(0)).ok();
@@ -724,6 +744,8 @@ impl Document {
// the file's object streams comes here without a read around it.
let _scope = crate::security::FollowScope::enter();
let readable = crate::security::following(Cow::Borrowed(s), || self.with_direct_parms(s));
#[cfg(test)]
super::tests::OBJSTM_DECODES.with(|decodes| decodes.set(decodes.get() + 1));
let data = readable.decoded_within(self.stream_limit)?;
let mut lx = Lexer::new(&data, 0);
let mut index = Vec::with_capacity(n);
@@ -732,6 +754,9 @@ impl Document {
index.push(objstm_member(onum, off, first, data.len()));
}
let stm = Arc::new(ObjStm { index, data: Arc::new(data) });
if own {
return Ok(stm);
}
// Same bound as the object cache: decoded object streams can be megabytes each.
// Insert first so the retained `num` is actually in the map.
self.objstms.lock().map_err(|_| CosError::Poisoned)?.insert(num, stm.clone());
@@ -788,6 +813,7 @@ impl Document {
pub fn set(&mut self, r: ObjRef, obj: impl Into<Object>) {
let obj = self.adopt(obj.into());
self.overlay.insert(r.num, Slot::Set(r.generation, Arc::new(obj)));
self.forget_member_failures(r.num);
if r.num >= self.next_num {
self.next_num = r.num.saturating_add(1);
}
@@ -847,6 +873,16 @@ impl Document {
/// Delete an object (its number becomes free with the next generation).
pub fn free(&mut self, r: ObjRef) {
self.overlay.insert(r.num, Slot::Freed(r.generation.saturating_add(1)));
self.forget_member_failures(r.num);
}
/// Forget cached failures of the members `stream` held in the file: they were failures of
/// the file's copy, and an edit of `stream` may read. Clones share the cache, so theirs are
/// searched again too, which costs time only. A poisoned lock leaves the cache as it is.
fn forget_member_failures(&self, stream: u32) {
if let Ok(mut cache) = self.cache.lock() {
cache.forget_failures(|n| matches!(self.entries.lookup(*n, &self.data), Some(XrefEntry::InStream { stream: s, .. }) if s == stream));
}
}
/// Free what was added since the file was read and nothing refers to any more: the objects
+33 -8
View File
@@ -6,8 +6,20 @@ thread_local! {
static LOADING: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) };
/// Indirect `/Length` values resolved during the current outermost load: a damaged file
/// retries a parse several ways, and each retry would resolve the same lengths again
/// (exponential in the chain of streams whose lengths point at further streams).
pub(super) static LENGTHS: std::cell::RefCell<HashMap<ObjRef, Option<i64>>> = std::cell::RefCell::new(HashMap::new());
/// (exponential in the chain of streams whose lengths point at further streams). Each is
/// kept with whether resolving it read unsaved edits.
pub(super) static LENGTHS: std::cell::RefCell<HashMap<ObjRef, (Option<i64>, bool)>> = std::cell::RefCell::new(HashMap::new());
/// Unsaved edits read on this thread (`Document::try_get`, and a `/Length` in `Document::load`).
static OVERLAY_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Unsaved edits read so far on this thread: a load during which this changes depended on one.
pub(super) fn overlay_reads() -> u64 {
OVERLAY_READS.with(std::cell::Cell::get)
}
pub(super) fn note_overlay_read() {
OVERLAY_READS.with(|c| c.set(c.get().wrapping_add(1)));
}
/// Marks an object as being loaded on this thread. Loading can re-enter (indirect stream
@@ -30,6 +42,14 @@ impl LoadGuard {
}
}
/// What loading a file object gave, kept in the document's cache either way.
pub(super) type Loaded = Result<Arc<Object>, CosError>;
/// The bytes a load result holds of its own ([`held_bytes`]); a failure holds none.
pub(super) fn loaded_bytes(loaded: &Loaded, data: &Arc<Vec<u8>>) -> usize {
loaded.as_ref().map_or(0, |o| held_bytes(o, data, 0))
}
impl Drop for LoadGuard {
fn drop(&mut self) {
let outermost = LOADING.with(|l| {
@@ -236,7 +256,7 @@ thread_local! {
pub(super) static SECTION_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Parsed objects by number, each with what it holds ([`held_bytes`]) measured once, when it goes
/// What loading each object gave (a failure as well), by number, each with what it holds ([`held_bytes`]) measured once, when it goes
/// in, and their sum kept beside them.
///
/// Both caches are bounded by those bytes. Summing them on every read walked every cached object
@@ -245,12 +265,12 @@ thread_local! {
/// (#5873).
#[derive(Default)]
pub(crate) struct ObjectCache {
entries: HashMap<u32, (Arc<Object>, usize)>,
entries: HashMap<u32, (Loaded, usize)>,
owned: usize,
}
impl ObjectCache {
pub(crate) fn get(&self, num: &u32) -> Option<&Arc<Object>> {
pub(crate) fn get(&self, num: &u32) -> Option<&Loaded> {
self.entries.get(num).map(|(object, _)| object)
}
@@ -259,8 +279,8 @@ impl ObjectCache {
self.entries.contains_key(num)
}
/// Keep `object` as `num`, which holds `owned` bytes (what [`held_bytes`] says of it).
pub(crate) fn insert(&mut self, num: u32, object: Arc<Object>, owned: usize) {
/// Keep what loading `num` gave, which holds `owned` bytes ([`loaded_bytes`]).
pub(crate) fn insert(&mut self, num: u32, object: Loaded, owned: usize) {
if let Some((_, before)) = self.entries.insert(num, (object, owned)) {
self.owned = self.owned.saturating_sub(before);
}
@@ -286,6 +306,11 @@ impl ObjectCache {
self.owned = 0;
}
/// Drop the cached failures `stale` picks. A failure holds no bytes, so the total stands.
pub(crate) fn forget_failures(&mut self, mut stale: impl FnMut(&u32) -> bool) {
self.entries.retain(|num, (loaded, _)| loaded.is_ok() || !stale(num));
}
pub(crate) fn retain(&mut self, mut keep: impl FnMut(&u32) -> bool) {
self.entries.retain(|num, _| keep(num));
self.owned = self.entries.values().fold(0usize, |n, (_, owned)| n.saturating_add(*owned));
@@ -293,7 +318,7 @@ impl ObjectCache {
#[cfg(test)]
pub(crate) fn values(&self) -> impl Iterator<Item = &Arc<Object>> {
self.entries.values().map(|(object, _)| object)
self.entries.values().filter_map(|(object, _)| object.as_ref().ok())
}
}
+177 -8
View File
@@ -3,6 +3,8 @@ use super::*;
std::thread_local! {
/// How many times `Document::scan_for` read the file on this thread.
pub(super) static FILE_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many times `Document::objstm` decoded an object stream on this thread.
pub(super) static OBJSTM_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// A scan that doesn't find an object isn't made again: each reads the whole file, and a file can
@@ -730,6 +732,163 @@ fn an_entry_that_misses_its_object_is_found_by_searching_but_is_not_exact() {
assert!(doc.xref_entry_is_exact(1) && doc.xref_entry_is_exact(2));
}
/// An object that can't be read at its entry or anywhere else is searched for in the whole file
/// once: every later read, in a clone too, gives the same error without searching again. An
/// edit of that number still answers for it.
#[test]
fn an_unreadable_object_is_searched_for_once() {
let bodies = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "<< /Odd Key(x) >>"];
let doc = Document::open(Arc::new(build(&bodies, "/Root 1 0 R /Info 3 0 R"))).unwrap();
FILE_SCANS.with(|scans| scans.set(0));
let first = doc.try_get(3);
assert!(first.is_err(), "{first:?}");
for _ in 0..10 {
assert_eq!(doc.try_get(3), first);
assert_eq!(*doc.get(ObjRef::new(3, 0)), Object::Null);
}
let mut edited = doc.clone();
assert_eq!(edited.try_get(3), first);
assert_eq!(FILE_SCANS.with(std::cell::Cell::get), 1, "searches for an object that isn't there");
let report = doc.unreadable_objects();
assert_eq!(report.len(), 1, "cached failures must stay listed exactly once: {report:?}");
assert_eq!(edited.unreadable_objects(), report, "clones retain the cached failure diagnostic");
edited.set(ObjRef::new(3, 0), Object::Int(7));
assert_eq!(edited.try_get(3).as_deref(), Ok(&Object::Int(7)));
assert_eq!(doc.try_get(3), first, "the edit is the clone's alone");
edited.free(ObjRef::new(3, 0));
assert_eq!(edited.try_get(3).as_deref(), Ok(&Object::Null));
}
/// A member of an object stream that can't be decoded (here, one that decodes past the document's
/// stream limit) is decoded once: every later read, in a clone too, gives the same error without
/// decoding the stream again. The stream itself loads, so no search of the file is involved.
#[test]
fn a_member_of_an_undecodable_object_stream_is_decoded_once() {
let file = object_stream_file("3 0 ", &format!("<< /Hidden ({}) >>", "x".repeat(4096)), 0);
let doc = Document::open_with_stream_limit(Arc::new(file), None, 1024).unwrap();
OBJSTM_DECODES.with(|decodes| decodes.set(0));
let first = doc.try_get(3);
assert!(matches!(first, Err(CosError::Filter(_))), "{first:?}");
for _ in 0..10 {
assert_eq!(doc.try_get(3), first);
}
assert_eq!(doc.clone().try_get(3), first);
assert_eq!(OBJSTM_DECODES.with(std::cell::Cell::get), 1, "decodes an object stream that can't be decoded");
}
/// Clones share the cache, and an edit is one clone's alone: a member of an object stream that
/// one clone freed or replaced still reads, in the others, from the file's stream.
#[test]
fn an_edited_object_stream_leaves_other_clones_members_alone() {
let file = Arc::new(object_stream_file("3 0 ", "<< /Hidden (yes) >>", 0));
let doc = Document::open(file.clone()).unwrap();
let mut freed = doc.clone();
freed.free(ObjRef::new(4, 0));
assert_eq!(freed.try_get(3), Err(CosError::MissingObject(4)));
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("yes"), "the free reached another clone");
let doc = Document::open(file).unwrap();
let mut replaced = doc.clone();
let mut dict = Dict::new();
dict.set(b"Type".to_vec(), Object::name("ObjStm"));
dict.set(b"N".to_vec(), Object::Int(1));
dict.set(b"First".to_vec(), Object::Int(4));
replaced.set(ObjRef::new(4, 0), crate::Stream::from_raw(dict, b"3 0 << /Hidden (no) >>".to_vec()));
assert_eq!(text_of(&replaced, 3, b"Hidden").as_deref(), Some("no"));
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("yes"), "the replacement reached another clone");
}
/// A member that failed to load from the file's object stream is kept as a failure, but replacing
/// or freeing that stream forgets it: the member then reads from the edit.
#[test]
fn an_edited_object_stream_forgets_its_members_failures() {
let file = Arc::new(object_stream_file("3 0 ", ") broken", 0));
let mut doc = Document::open(file.clone()).unwrap();
assert!(doc.try_get(3).is_err(), "the file's member does not parse");
let mut dict = Dict::new();
dict.set(b"Type".to_vec(), Object::name("ObjStm"));
dict.set(b"N".to_vec(), Object::Int(1));
dict.set(b"First".to_vec(), Object::Int(4));
doc.set(ObjRef::new(4, 0), crate::Stream::from_raw(dict, b"3 0 << /Hidden (fixed) >>".to_vec()));
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("fixed"), "the cached failure outlived the edit");
assert!(doc.try_get(3).is_ok());
let mut doc = Document::open(file).unwrap();
assert!(matches!(doc.try_get(3), Err(CosError::Syntax { .. })), "the file's member does not parse");
doc.free(ObjRef::new(4, 0));
assert_eq!(doc.try_get(3), Err(CosError::MissingObject(4)), "the freed stream's member");
}
/// An object stream framed by one clone's edit of its indirect `/Length` is that clone's alone:
/// the others still read its members within the file's length.
#[test]
fn an_edited_object_stream_length_leaves_other_clones_members_alone() {
let file = Arc::new(object_stream_file_with("3 0 ", "<< /Hidden (cut endstream here) >>", 0, true));
let doc = Document::open(file).unwrap();
let mut edited = doc.clone();
// Ends the stream at the `endstream` inside the member's string.
let cut = "3 0 << /Hidden (cut".len();
edited.set(ObjRef::new(6, 0), Object::Int(cut as i64));
assert_ne!(text_of(&edited, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length was not used");
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length reached another clone");
}
/// A `/Length` read through one clone's edits and reused within the same load still keeps that
/// load to the clone. Here the file's offsets are header-relative behind junk, so object 10's
/// offset first lands on object 12, whose length (object 8, in the edited object stream 9) is
/// read; object 10's own length then loads object stream 4, framed by object 8 too.
#[test]
fn a_reused_edited_length_leaves_other_clones_members_alone() {
let mut out = b"%PDF-1.5\n".to_vec();
let mut offs = [0usize; 13];
let mut obj = |out: &mut Vec<u8>, n: usize, body: &[u8]| {
offs[n] = out.len();
out.extend_from_slice(format!("{n} 0 obj\n").as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
};
let stream = |dict: &str, data: &str| format!("<< {dict} >>\nstream\n{data}\nendstream").into_bytes();
obj(&mut out, 1, b"<< /Type /Catalog /Pages 2 0 R >>");
obj(&mut out, 2, b"<< /Type /Pages /Kids [] /Count 0 /Extra 3 0 R >>");
let inner = "11 0 3 2 5 << /Hidden (cut endstream here) >>";
obj(&mut out, 4, &stream("/Type /ObjStm /N 2 /First 9 /Length 8 0 R", inner));
let lengths = format!("8 0 {}", inner.len());
obj(&mut out, 9, &stream(&format!("/Type /ObjStm /N 1 /First 4 /Length {}", lengths.len()), &lengths));
obj(&mut out, 12, &stream("/Length 8 0 R", &"x".repeat(40)));
obj(&mut out, 10, &stream("/Length 11 0 R", "PDATA"));
// A cross-reference stream: a hybrid file's /XRefStm is not looked for behind junk.
let compressed = [(3, 4, 1), (8, 9, 0), (11, 4, 0)];
let mut data = Vec::new();
for (n, off) in offs.iter().enumerate() {
let row = match compressed.iter().find(|c| c.0 == n) {
Some(&(_, stream, index)) => [2, 0, stream, index],
None if *off == 0 => [0, 0, 0, 0],
None => {
let [.., hi, lo] = u32::try_from(*off).unwrap().to_be_bytes();
[1, hi, lo, 0]
}
};
data.extend_from_slice(&row);
}
let table = out.len();
let dict = format!("<< /Type /XRef /Size 14 /W [1 2 1] /Index [0 13] /Root 1 0 R /Length {} >>", data.len());
out.extend_from_slice(format!("13 0 obj\n{dict}\nstream\n").as_bytes());
out.extend_from_slice(&data);
out.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{table}\n%%EOF\n").as_bytes());
let mut file = vec![b'J'; offs[10] - offs[12] - 1];
file.push(b'\n');
file.extend_from_slice(&out);
let doc = Document::open(Arc::new(file)).unwrap();
let mut edited = doc.clone();
let cut = "11 0 3 2 5 << /Hidden (cut".len();
let mut dict = Dict::new();
dict.set(b"Type".to_vec(), Object::name("ObjStm"));
dict.set(b"N".to_vec(), Object::Int(1));
dict.set(b"First".to_vec(), Object::Int(4));
edited.set(ObjRef::new(9, 0), crate::Stream::from_raw(dict, format!("8 0 {cut}").into_bytes()));
assert!(matches!(&*edited.get(ObjRef::new(10, 0)), Object::Stream(s) if &s.raw[..] == b"PDATA"));
assert_ne!(text_of(&edited, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length was not used");
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length reached another clone");
}
/// A classic table with `/Size` rows and object 0's free entry first, its subsection numbered
/// `1 n` instead of `0 n` (#2676): every row is one number off.
fn misnumbered_table(start: u32) -> Vec<u8> {
@@ -1255,7 +1414,7 @@ fn temporary_reader_keeps_file_views_and_evicts_data_of_its_own() {
// cleared after the next read, including a failed one.
let owned = Object::Stream(crate::Stream::from_raw(Dict::new(), vec![b'y'; ObjectReader::STREAM_BYTES + 1]));
let size = held_bytes(&owned, &reader.document.data, 0);
reader.document.cache.lock().unwrap().insert(3, Arc::new(owned), size);
reader.document.cache.lock().unwrap().insert(3, Ok(Arc::new(owned)), size);
assert_eq!(*reader.get(ObjRef::new(99, 0)), Object::Null);
assert!(reader.document.cache.lock().unwrap().is_empty(), "owned data over budget is evicted");
}
@@ -1468,8 +1627,14 @@ fn hybrid_reference_files_read_the_xref_stream_too() {
/// stream puts it at position `member` of object stream 4, which holds `header` (the number
/// and offset pairs) and then `members`.
fn object_stream_file(header: &str, members: &str, member: u8) -> Vec<u8> {
object_stream_file_with(header, members, member, false)
}
/// [`object_stream_file`], with the stream's `/Length` in object 6 when `indirect_length`.
fn object_stream_file_with(header: &str, members: &str, member: u8, indirect_length: bool) -> Vec<u8> {
let mut out = b"%PDF-1.5\n".to_vec();
let mut offs = [0usize; 6];
let size = if indirect_length { 7 } else { 6 };
let mut offs = vec![0usize; size];
let mut obj = |out: &mut Vec<u8>, n: usize, body: &[u8]| {
offs[n] = out.len();
out.extend_from_slice(format!("{n} 0 obj\n").as_bytes());
@@ -1480,7 +1645,8 @@ fn object_stream_file(header: &str, members: &str, member: u8) -> Vec<u8> {
obj(&mut out, 2, b"<< /Type /Pages /Kids [] /Count 0 /Extra 3 0 R >>");
let count = header.split_whitespace().count() / 2;
let inner = format!("{header}{members}");
let mut stm = format!("<< /Type /ObjStm /N {count} /First {} /Length {} >>\nstream\n", header.len(), inner.len()).into_bytes();
let length = if indirect_length { "6 0 R".to_string() } else { inner.len().to_string() };
let mut stm = format!("<< /Type /ObjStm /N {count} /First {} /Length {length} >>\nstream\n", header.len()).into_bytes();
stm.extend_from_slice(inner.as_bytes());
stm.extend_from_slice(b"\nendstream");
obj(&mut out, 4, &stm);
@@ -1489,13 +1655,16 @@ fn object_stream_file(header: &str, members: &str, member: u8) -> Vec<u8> {
xs.extend_from_slice(&data);
xs.extend_from_slice(b"\nendstream");
obj(&mut out, 5, &xs);
if indirect_length {
obj(&mut out, 6, inner.len().to_string().as_bytes());
}
let table = out.len();
out.extend_from_slice(b"xref\n0 6\n0000000000 65535 f \n");
out.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
for (n, off) in offs.iter().enumerate().skip(1) {
let line = if n == 3 { "0000000000 65535 f \n".to_string() } else { format!("{off:010} 00000 n \n") };
out.extend_from_slice(line.as_bytes());
}
out.extend_from_slice(format!("trailer << /Size 6 /Root 1 0 R /XRefStm {} >>\nstartxref\n{table}\n%%EOF\n", offs[5]).as_bytes());
out.extend_from_slice(format!("trailer << /Size {size} /Root 1 0 R /XRefStm {} >>\nstartxref\n{table}\n%%EOF\n", offs[5]).as_bytes());
out
}
@@ -1983,10 +2152,10 @@ fn the_object_cache_keeps_its_total_as_objects_come_and_go() {
let two = Arc::new(Object::Array(vec![Object::Int(1); 10]));
let (a, b) = (held_bytes(&one, &data, 0), held_bytes(&two, &data, 0));
let mut cache = super::state::ObjectCache::default();
cache.insert(1, one.clone(), a);
cache.insert(2, two, b);
cache.insert(1, Ok(one.clone()), a);
cache.insert(2, Ok(two), b);
assert_eq!(cache.owned(), a + b);
cache.insert(2, one, a);
cache.insert(2, Ok(one), a);
assert_eq!(cache.owned(), a + a, "a replaced object no longer counts");
cache.retain(|n| *n == 1);
assert_eq!((cache.len(), cache.owned()), (1, a));
+133 -1
View File
@@ -516,6 +516,129 @@ fn decoded(name: &str, bytes: &[u8], format: image::ImageFormat) -> Result<Embed
Ok(rgba_image(rgba.as_raw(), rgba.dimensions(), (72.0, 72.0)))
}
fn le16(b: &[u8], at: usize) -> Option<u16> {
b.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]]))
}
/// How a PCX image holds its pixels: bits per plane and planes.
#[derive(Clone, Copy, PartialEq)]
enum PcxLayout {
/// One byte per pixel per colour: each scanline has a red, a green and a blue row.
Rgb,
/// One byte per pixel, an index into the palette after the image (grey without one).
Indexed,
/// One bit per pixel in each of 1 to 4 planes, an index into the header's palette.
Bits(usize),
}
impl PcxLayout {
fn of(bits: u8, planes: usize) -> Option<PcxLayout> {
match (bits, planes) {
(8, 3) => Some(PcxLayout::Rgb),
(8, 1) => Some(PcxLayout::Indexed),
(1, 1..=4) => Some(PcxLayout::Bits(planes)),
_ => None,
}
}
}
/// The palette of a PCX image, and where its run-length coded scanlines end. An 8-bit image ends
/// with a 0x0C byte and 256 colours; a one-plane bit image is black and white whatever its header
/// holds; other bit images use the 16 colours at byte 16.
fn pcx_palette(bytes: &[u8], layout: PcxLayout) -> (Vec<u8>, usize) {
match layout {
PcxLayout::Rgb => (Vec::new(), bytes.len()),
PcxLayout::Indexed => match bytes.len().checked_sub(769).filter(|at| *at >= 128 && bytes.get(*at) == Some(&0x0C)) {
Some(at) => (bytes.get(at + 1..).unwrap_or_default().to_vec(), at),
None => ((0..=255u8).flat_map(|v| [v, v, v]).collect(), bytes.len()),
},
PcxLayout::Bits(1) => (vec![0, 0, 0, 255, 255, 255], bytes.len()),
PcxLayout::Bits(_) => (bytes.get(16..64).unwrap_or_default().to_vec(), bytes.len()),
}
}
/// The `rows` scanlines of `line` bytes each, decoded. A run may cross from one plane's row into the
/// next, but not out of its scanline.
fn pcx_scanlines(mut body: &[u8], rows: usize, line: usize) -> Option<Vec<u8>> {
let mut out = Vec::new();
out.try_reserve_exact(rows.checked_mul(line)?).ok()?;
for row in 1..=rows {
let end = row * line;
while out.len() < end {
let (&c, rest) = body.split_first()?;
body = rest;
if c < 0xC0 {
out.push(c);
continue;
}
let (&value, rest) = body.split_first()?;
body = rest;
let count = usize::from(c & 0x3F);
if count > end - out.len() {
return None;
}
out.resize(out.len() + count, value);
}
}
Some(out)
}
/// The RGB samples of the `w` pixels of scanline `row` (planes `stride` bytes apart).
fn pcx_row(out: &mut Vec<u8>, row: &[u8], w: usize, stride: usize, layout: PcxLayout, palette: &[u8]) {
let at = |i: usize| row.get(i).copied().unwrap_or(0);
for x in 0..w {
let index = match layout {
PcxLayout::Rgb => {
out.extend([at(x), at(stride + x), at(2 * stride + x)]);
continue;
}
PcxLayout::Indexed => usize::from(at(x)),
PcxLayout::Bits(planes) => (0..planes).fold(0, |index, k| index | (usize::from(at(k * stride + x / 8) >> (7 - x % 8) & 1) << k)),
};
out.extend((0..3).map(|c| palette.get(index * 3 + c).copied().unwrap_or(0)));
}
}
/// A PCX image: a 128-byte header (size at 4-11, resolution at 12 and 14, plane count at 65, bytes
/// per plane row at 66), then run-length coded scanlines, each holding one row of every plane.
fn pcx(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {
let bad = |m: &str| CreateError::Image(name.into(), m.into());
let header = bytes.get(..128).ok_or_else(|| bad("a damaged PCX header"))?;
let word = |at: usize| le16(header, at).unwrap_or(0);
let byte = |at: usize| header.get(at).copied().unwrap_or(0);
let (bits, planes, stride) = (byte(3), usize::from(byte(65)), usize::from(word(66)));
let (Some(w), Some(h)) = (word(8).checked_sub(word(4)), word(10).checked_sub(word(6))) else {
return Err(bad("a damaged PCX header"));
};
let (w, h) = (usize::from(w) + 1, usize::from(h) + 1);
if planes == 0 || stride == 0 {
return Err(bad("a damaged PCX header"));
}
let layout = PcxLayout::of(bits, planes).ok_or_else(|| bad("this PCX plane layout is not supported"))?;
if stride < (w * usize::from(bits)).div_ceil(8) {
return Err(bad("a damaged PCX header"));
}
let line = planes * stride;
if line.saturating_mul(h) > MAX_DECODED_BYTES || w.saturating_mul(h).saturating_mul(3) > MAX_DECODED_BYTES {
return Err(bad("unusual PCX image size"));
}
let (palette, end) = pcx_palette(bytes, layout);
let body = bytes.get(128..end).unwrap_or_default();
let scanlines = pcx_scanlines(body, h, line).ok_or_else(|| bad("a damaged PCX body"))?;
let mut data = Vec::new();
data.try_reserve_exact(w * h * 3).map_err(|_| bad("not enough memory for this image"))?;
for row in scanlines.chunks_exact(line) {
pcx_row(&mut data, row, w, stride, layout, &palette);
}
let dpi = (f64::from(word(12)), f64::from(word(14)));
let dpi = if dpi.0 > 0.0 && dpi.1 > 0.0 { dpi } else { (72.0, 72.0) };
let mut d = Dict::new();
d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
let px = (u32::try_from(w).unwrap_or(0), u32::try_from(h).unwrap_or(0));
Ok(Embedded { dict: d, data, filtered: false, smask: None, icc: None, px, dpi })
}
/// Largest GIF logical screen, in pixels (4096×4096).
const MAX_GIF_PIXELS: u64 = 1 << 24;
@@ -623,7 +746,13 @@ pub enum SourceKind {
}
/// File extensions Create converts to PDF (images and plain text).
pub const CONVERTIBLE: [&str; 12] = ["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx", "txt", "text"];
pub const CONVERTIBLE: [&str; 13] = ["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx", "pcx", "txt", "text"];
/// A PCX file: its manufacturer byte, a version (1 was never used), run-length coding and 1 or 8
/// bits per plane. `pcx` says when the rest of the header isn't one it can read.
fn is_pcx(bytes: &[u8]) -> bool {
bytes.first() == Some(&0x0A) && matches!(bytes.get(1), Some(0 | 2..=5)) && bytes.get(2) == Some(&1) && matches!(bytes.get(3), Some(1 | 8))
}
/// A classic TIFF or a BigTIFF (version 43), in either byte order.
fn is_tiff(bytes: &[u8]) -> bool {
@@ -640,6 +769,7 @@ fn is_image(bytes: &[u8]) -> bool {
|| bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| is_tiff(bytes)
|| is_gif(bytes)
|| is_pcx(bytes)
// JPEG 2000: a JP2 file or a raw codestream.
|| bytes.starts_with(JP2_SIGNATURE)
|| bytes.starts_with(&[0xFF, 0x4F, 0xFF, 0x51])
@@ -675,6 +805,8 @@ fn embed(name: &str, bytes: &[u8], wanted: usize) -> Result<Vec<Embedded>, Creat
Ok(vec![decoded(name, &pdfcraft_xfa::image::bmp_with_pixel_offset(bytes), image::ImageFormat::Bmp)?])
} else if is_gif(bytes) {
Ok(vec![decoded(name, bytes, image::ImageFormat::Gif)?])
} else if is_pcx(bytes) {
Ok(vec![pcx(name, bytes)?])
} else if bytes.starts_with(JP2_SIGNATURE) || bytes.starts_with(&[0xFF, 0x4F, 0xFF, 0x51]) {
Ok(vec![jpx(name, bytes)?])
} else {
+76
View File
@@ -485,6 +485,82 @@ fn bigtiff_images_become_pages() {
assert_eq!(media(&pages(&doc)[0]), [0.0, 0.0, 2.0, 1.0], "4×2 px at 144 dpi");
}
/// A PCX header for a `w` by `h` image at 72 dpi.
fn pcx_header(version: u8, bits: u8, planes: u8, stride: u16, w: u16, h: u16) -> Vec<u8> {
let mut pcx = vec![0u8; 128];
pcx[..4].copy_from_slice(&[0x0A, version, 1, bits]);
pcx[8..10].copy_from_slice(&(w - 1).to_le_bytes());
pcx[10..12].copy_from_slice(&(h - 1).to_le_bytes());
pcx[12..14].copy_from_slice(&72u16.to_le_bytes());
pcx[14..16].copy_from_slice(&72u16.to_le_bytes());
pcx[65] = planes;
pcx[66..68].copy_from_slice(&stride.to_le_bytes());
pcx
}
/// A 24-bit PCX: each scanline holds a red, a green and a blue row.
#[test]
fn pcx_images_become_pages() {
let mut pcx = pcx_header(5, 8, 3, 2, 2, 2);
pcx.extend_from_slice(&[10, 11, 20, 21, 30, 31]);
pcx.extend_from_slice(&[40, 41, 50, 51, 60, 61]);
let embedded = super::pcx("a.pcx", &pcx).unwrap();
assert_eq!(embedded.data, [10, 20, 30, 11, 21, 31, 40, 50, 60, 41, 51, 61]);
let doc = reopen(&from_images(&[("a.pcx".into(), pcx)]).unwrap());
assert_eq!(pages(&doc).len(), 1);
assert_eq!(media(&pages(&doc)[0]), [0.0, 0.0, 2.0, 2.0]);
assert_eq!(image_of(&doc, 0).name(b"ColorSpace"), Some(&b"DeviceRGB"[..]));
}
#[test]
fn a_pcx_run_may_cross_planes_but_not_scanlines() {
// 0xC4 repeats 7 four times: the red row and half of the green one
let mut pcx = pcx_header(5, 8, 3, 2, 2, 1);
pcx.extend_from_slice(&[0xC4, 7, 8, 9]);
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [7, 7, 8, 7, 7, 9]);
let mut pcx = pcx_header(5, 8, 3, 2, 2, 2);
pcx.extend_from_slice(&[0xC8, 7, 1, 2, 3, 4]);
assert!(super::pcx("a.pcx", &pcx).is_err(), "eight bytes in a six-byte scanline");
}
#[test]
fn an_8_bit_pcx_uses_its_palette_and_is_grey_without_one() {
let mut pcx = pcx_header(5, 8, 1, 2, 2, 1);
pcx.extend_from_slice(&[1, 2]);
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [1, 1, 1, 2, 2, 2], "no palette: grey");
pcx.push(0x0C);
let mut palette = vec![0u8; 768];
palette[3..9].copy_from_slice(&[9, 8, 7, 6, 5, 4]);
pcx.extend_from_slice(&palette);
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [9, 8, 7, 6, 5, 4]);
}
#[test]
fn bit_plane_pcx_images_read_their_palette() {
// version 2, one plane: black and white
let mut pcx = pcx_header(2, 1, 1, 2, 2, 1);
pcx.extend_from_slice(&[0b1000_0000, 0]);
assert!(from_images(&[("a.pcx".into(), pcx.clone())]).is_ok(), "an old version is still a PCX");
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [255, 255, 255, 0, 0, 0]);
// two planes: colour 3 is at byte 16 + 9
let mut pcx = pcx_header(5, 1, 2, 1, 1, 1);
pcx[25..28].copy_from_slice(&[1, 2, 3]);
pcx.extend_from_slice(&[0x80, 0x80]);
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [1, 2, 3]);
}
#[test]
fn damaged_pcx_headers_and_bodies_are_refused() {
let no_planes = pcx_header(5, 8, 0, 2, 2, 1);
let no_stride = pcx_header(5, 8, 3, 0, 2, 1);
let short_stride = pcx_header(5, 8, 3, 1, 2, 1);
let short_body = pcx_header(5, 8, 3, 2, 2, 1);
for bytes in [no_planes, no_stride, short_stride, short_body] {
assert!(super::pcx("a.pcx", &bytes).is_err());
}
assert!(super::pcx("a.pcx", &[0x0A, 5, 1, 8]).is_err(), "no header");
}
/// A synthetic ICC profile: a 128-byte header (size, device class, colour space, `acsp`) and
/// some payload. Only the header is read.
fn icc_profile(space: &[u8; 4]) -> Vec<u8> {
+1 -1
View File
@@ -31,7 +31,7 @@ use layout::Piece;
pub(crate) use layout::WRAP_CALLS;
pub use layout::{PASTE_STEP, first_undrawable, lines, paste_place, paste_rect, text_rect, text_width};
pub use store::{add_content, delete_content, isolate_content, list_added, scan_markers, update_content};
pub use types::{Added, AddedImage, AddedText, Align, CHAR_SPACING_LIMIT, Family, MarkerScan};
pub use types::{Added, AddedImage, AddedText, Align, CHAR_SPACING_LIMIT, Family, Ink, MarkerScan};
#[derive(Clone, Debug, PartialEq)]
pub enum Content {
+9 -5
View File
@@ -1,7 +1,7 @@
use super::layout::{
Piece, arabic_error, hebrew_error, is_arabic, is_hebrew, is_thai, latin_width, norm, shaped_layout, text_rect, thai_error, wrapped,
};
use super::types::{AddedText, Align, Family};
use super::types::{AddedText, Align, Family, Ink};
use super::{
Content, Dict, Document, EditError, GlyphError, GlyphOutline, HashMap, HashSet, ObjRef, Object, PdfString, ShapedCluster, ShapedScript, Stream,
align_code, literal, matrix_number, n, shaped_glyph, win_ansi,
@@ -105,8 +105,7 @@ pub(super) fn draw_laid_shaped(
fonts.set(name.clone().into_bytes(), Object::Ref(font));
names.push(name);
}
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());
out.extend(format!("BT {}\n", t.fill_op()).bytes());
if t.char_spacing != 0.0 {
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
}
@@ -293,8 +292,7 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
}
res.set(b"Font".to_vec(), Object::Dict(fonts));
let r = text_rect(t);
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());
out.extend(format!("BT /{name} {} Tf {}\n", n(t.size), t.fill_op()).bytes());
if t.char_spacing != 0.0 {
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
}
@@ -355,6 +353,12 @@ pub(super) fn params(c: &Content) -> Dict {
d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));
d.set(b"Size".to_vec(), Object::Real(t.size));
d.set(b"Color".to_vec(), arr(&t.color));
// The ink beside its RGB look, which a reader that knows no ink keeps showing.
match t.painted_ink() {
Some(Ink::Gray(g)) => d.set(b"Gray".to_vec(), Object::Real(g)),
Some(Ink::Cmyk(c)) => d.set(b"CMYK".to_vec(), arr(&c)),
None => {}
}
d.set(b"Align".to_vec(), Object::Int(align_code(t.align)));
// Each paragraph's own alignment, or null where it follows /Align.
let aligns = crate::paragraph_align::tidy(t.aligns.clone(), t.align);
+39 -3
View File
@@ -1,8 +1,33 @@
use super::draw::{draw, params};
use super::layout::{first_undrawable, is_thai, nums, shaped_arabic, thai_error};
use super::types::{Added, AddedImage, AddedText, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};
use super::types::{Added, AddedImage, AddedText, CHAR_SPACING_LIMIT, Family, Ink, MarkerScan, TAG};
use super::{Content, Dict, Document, EditError, GlyphError, MarkKind, ObjRef, Object, Stream, align_from, check, contents, page_list, place_tagged};
/// A text item's gray or CMYK ink. Items written before inks, and an ink out of range or not
/// made only of numbers (a `/Gray` name, a `/CMYK` entry that isn't a number), have none: the
/// text paints in its RGB `/Color`.
fn ink(doc: &Document, d: &Dict) -> Option<Ink> {
let ink = if let Some(g) = d.get(b"Gray") {
Ink::Gray(read_value(doc, g, Object::as_f64)?)
} else {
// Four entries or none: a longer array is never copied or read through.
read_value(doc, d.get(b"CMYK")?, |cmyk| {
let [c, m, y, k] = cmyk.as_array()?.as_slice() else { return None };
Some(Ink::Cmyk([c.as_f64()?, m.as_f64()?, y.as_f64()?, k.as_f64()?]))
})?
};
Some(ink).filter(|i| i.valid())
}
/// `f` of `o`, a reference followed. A direct value is read where it is, never copied, so a
/// large one a file puts there costs nothing to look at.
fn read_value<T>(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> T) -> T {
match o {
Object::Ref(_) => f(&doc.resolve(o)),
direct => f(direct),
}
}
fn parse(doc: &Document, d: &Dict) -> Option<Content> {
let r = nums(doc, d.get(b"Rect"));
let rect: [f64; 4] = r.try_into().ok()?;
@@ -21,7 +46,7 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
.map(|a| a.iter().take(crate::paragraph_align::count(&text)).map(|v| v.as_int().map(|c| align_from(Some(c)))).collect())
})
.unwrap_or_default();
Some(Content::Text(AddedText {
let mut t = AddedText {
rect,
text,
family,
@@ -29,11 +54,19 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
italic,
size: d.get(b"Size").and_then(Object::as_f64).unwrap_or(12.0),
color: if c.len() == 3 { [c[0], c[1], c[2]] } else { [0.0; 3] },
ink: ink(doc, d),
align,
aligns: crate::paragraph_align::tidy(aligns, align),
// Items written before character spacing have none.
char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
}))
};
// An ink whose look isn't the stored colour (a file edited by hand) is none.
t.drop_stale_ink();
// One that stands is the ink as painted, finer digits dropped, and its look.
if let Some(i) = t.ink {
t.set_ink(Some(i));
}
Some(Content::Text(t))
}
b"Image" => {
let crop = nums(doc, d.get(b"Crop"));
@@ -138,6 +171,9 @@ fn validate(c: &Content) -> Result<(), EditError> {
"the character spacing must be between -{CHAR_SPACING_LIMIT} and {CHAR_SPACING_LIMIT} points"
)));
}
if t.ink.is_some_and(|i| !i.valid()) {
return Err(EditError::Invalid("a gray level and each CMYK value must be from 0 to 1".into()));
}
if (r[2] - r[0]).abs() < 1.0 {
return Err(EditError::Invalid("the text box is too narrow".into()));
}
+101 -1
View File
@@ -1,5 +1,5 @@
use super::layout::norm;
use super::{Content, MarkKind, ObjRef, Std14};
use super::{Content, MarkKind, ObjRef, Std14, n};
pub(super) const TAG: &str = "Added";
@@ -90,6 +90,60 @@ pub enum Align {
Justify,
}
/// A device colour added text is painted in instead of RGB, for print files: a text's black in
/// CMYK stays 100 K rather than a DeviceRGB black the printer separates into rich black.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Ink {
/// A DeviceGray level, from 0 (black) to 1 (white): painted with `g`.
Gray(f64),
/// DeviceCMYK `[c, m, y, k]`, each from 0 to 1 (`[0, 0, 0, 1]` is 100 K): painted with `k`.
Cmyk([f64; 4]),
}
impl Ink {
/// Whether every component is a number from 0 to 1.
pub fn valid(self) -> bool {
self.components().iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))
}
/// The ink as its operator paints it: each component to the thousandth that `g` and `k` are
/// written with (as RGB's `rg`), so the item, what it reads back as and the page agree.
pub fn painted(self) -> Ink {
let round = |v: f64| (v * 1000.0).round() / 1000.0;
match self {
Ink::Gray(g) => Ink::Gray(round(g)),
Ink::Cmyk(c) => Ink::Cmyk(c.map(round)),
}
}
fn components(&self) -> &[f64] {
match self {
Ink::Gray(g) => std::slice::from_ref(g),
Ink::Cmyk(c) => c,
}
}
/// How the ink looks on screen: gray is the same level in each of red, green and blue
/// (ISO 32000-2 §10.4.2.2), CMYK takes each colour plus black from 1 (§10.4.2.5).
pub fn rgb(self) -> [f64; 3] {
match self {
Ink::Gray(g) => [g.clamp(0.0, 1.0); 3],
Ink::Cmyk([c, m, y, k]) => [c, m, y].map(|v| 1.0 - (v + k).clamp(0.0, 1.0)),
}
}
/// The operator that makes this ink the fill colour, without a line end.
pub(super) fn fill_op(self) -> String {
match self {
Ink::Gray(g) => format!("{} g", n(g.clamp(0.0, 1.0))),
Ink::Cmyk(c) => {
let [c, m, y, k] = c.map(|v| v.clamp(0.0, 1.0));
format!("{} {} {} {} k", n(c), n(m), n(y), n(k))
}
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct AddedText {
/// The text box in display space; its width wraps the text and its top is the first line's
@@ -100,7 +154,14 @@ pub struct AddedText {
pub bold: bool,
pub italic: bool,
pub size: f64,
/// The RGB colour: what the text is painted in, unless it has an [`AddedText::ink`] this is
/// the look of.
pub color: [f64; 3],
/// A gray or CMYK ink the text is painted in, with `color` its look ([`Ink::rgb`]). Set it
/// with [`AddedText::set_ink`] and the colour with [`AddedText::set_color`], which drops an
/// ink the colour no longer shows; one left behind by setting `color` directly paints nothing
/// ([`AddedText::painted_ink`]) until [`AddedText::drop_stale_ink`] forgets it.
pub ink: Option<Ink>,
pub align: Align,
/// Extra space after every character, in points: the PDF's character spacing (`Tc`).
pub char_spacing: f64,
@@ -114,6 +175,44 @@ impl AddedText {
pub fn paragraph_align(&self, i: usize) -> Align {
crate::paragraph_align::align_of(&self.aligns, i, self.align)
}
/// Paint the text in `ink` (its look becomes [`AddedText::color`]), or in RGB with `None`. An
/// ink in range is kept as painted ([`Ink::painted`]); one out of range stays as given, for
/// saving to refuse.
pub fn set_ink(&mut self, ink: Option<Ink>) {
let ink = ink.map(|i| if i.valid() { i.painted() } else { i });
if let Some(i) = ink {
self.color = i.rgb();
}
self.ink = ink;
}
/// Paint the text in RGB `rgb`. Its ink stays only when `rgb` is the ink's own look; once
/// gone it stays gone, so picking that look again later paints in RGB.
pub fn set_color(&mut self, rgb: [f64; 3]) {
self.color = rgb;
self.drop_stale_ink();
}
/// Forget an ink `color` no longer shows, so two styles that paint the same compare equal.
pub fn drop_stale_ink(&mut self) {
self.ink = self.painted_ink();
}
/// The ink the text is painted in, or `None` for RGB: the one it has while `color` is still
/// its look.
pub fn painted_ink(&self) -> Option<Ink> {
// Within rounding: a look read back from a file, or from a colour picker, is the same.
self.ink.filter(|i| i.rgb().iter().zip(self.color).all(|(a, b)| (a - b).abs() < 1e-6))
}
/// The operator that sets the text's fill colour, without a line end.
pub(super) fn fill_op(&self) -> String {
match self.painted_ink() {
Some(ink) => ink.fill_op(),
None => crate::marks::rgb(self.color),
}
}
}
impl Default for AddedText {
@@ -126,6 +225,7 @@ impl Default for AddedText {
italic: false,
size: 12.0,
color: [0.0; 3],
ink: None,
align: Align::Left,
aligns: Vec::new(),
char_spacing: 0.0,
+2 -2
View File
@@ -61,8 +61,8 @@ pub use text::{
};
pub mod added;
pub use added::{
Added, AddedImage, AddedText, Align, Content, Family, MarkerScan, add_content, delete_content, first_undrawable, isolate_content, list_added,
scan_markers, update_content,
Added, AddedImage, AddedText, Align, Content, Family, Ink, MarkerScan, add_content, delete_content, first_undrawable, isolate_content,
list_added, scan_markers, update_content,
};
mod apply;
+158
View File
@@ -1048,6 +1048,164 @@ fn added_text_and_images_are_page_content_that_stays_editable() {
assert!(marks_present(&doc).is_empty());
}
/// #6440: added text in a print file can be gray or CMYK, painted with `g` / `k`, so its black
/// stays 100 K. The ink survives save and reopen; another colour drops it for good.
#[test]
fn gray_and_cmyk_added_text_writes_g_and_k_until_it_is_recoloured() {
use crate::added::Ink;
let item_stream = |doc: &Document, i: usize| {
let obj = list_added(doc)[i].obj;
let Object::Stream(s) = &*doc.get(obj) else { panic!("an item is a stream") };
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
};
let mut doc = fixture();
let base = AddedText { rect: [72.0, 600.0, 300.0, 700.0], text: "Proof".into(), size: 14.0, ..AddedText::default() };
let mut black = base.clone();
black.set_ink(Some(Ink::Cmyk([0.0, 0.0, 0.0, 1.0])));
assert_eq!(black.color, [0.0; 3], "100 K looks black on screen");
let mut gray = AddedText { rect: [72.0, 400.0, 300.0, 500.0], ..base.clone() };
gray.set_ink(Some(Ink::Gray(0.25)));
add_content(&mut doc, 0, &Content::Text(black)).unwrap();
add_content(&mut doc, 0, &Content::Text(gray)).unwrap();
add_content(&mut doc, 0, &Content::Text(AddedText { rect: [72.0, 200.0, 300.0, 300.0], ..base.clone() })).unwrap();
let doc = reopen(&doc);
let (k, g, rgb) = (item_stream(&doc, 0), item_stream(&doc, 1), item_stream(&doc, 2));
assert!(k.contains("/PCFHelvetica 14 Tf 0 0 0 1 k\n") && !k.contains("rg"), "{k}");
assert!(g.contains("/PCFHelvetica 14 Tf 0.25 g\n") && !g.contains("rg"), "{g}");
assert!(rgb.contains("/PCFHelvetica 14 Tf 0 0 0 rg\n"), "RGB text paints as before: {rgb}");
let inks: Vec<Option<Ink>> = list_added(&doc).iter().map(|a| if let Content::Text(t) = &a.content { t.painted_ink() } else { None }).collect();
assert_eq!(inks, [Some(Ink::Cmyk([0.0, 0.0, 0.0, 1.0])), Some(Ink::Gray(0.25)), None]);
// Another colour drops the ink, and picking the ink's look again later doesn't bring it back;
// picking that look while the ink is there keeps it.
let Content::Text(cmyk) = list_added(&doc)[0].content.clone() else { panic!() };
let mut same = cmyk.clone();
same.set_color([0.0; 3]);
assert_eq!(same, cmyk, "black on 100 K stays 100 K");
let mut recoloured = cmyk.clone();
recoloured.set_color([1.0, 0.0, 0.0]);
assert_eq!(recoloured.ink, None);
recoloured.set_color([0.0; 3]);
assert_eq!((recoloured.ink, recoloured.painted_ink()), (None, None), "the ink stays gone");
// Set directly, a colour paints in RGB too, and the item reads back without the ink: what a
// draft with its stale ink dropped compares equal to.
let mut doc = doc;
let red = AddedText { color: [1.0, 0.0, 0.0], ..cmyk };
update_content(&mut doc, 0, 0, &Content::Text(red.clone())).unwrap();
let stream = item_stream(&doc, 0);
assert!(stream.contains("1 0 0 rg") && !stream.contains(" k\n"), "{stream}");
let mut settled = red;
settled.drop_stale_ink();
for doc in [&doc, &reopen(&doc)] {
let Content::Text(back) = list_added(doc)[0].content.clone() else { panic!() };
// The stored box is the text's own height.
assert_eq!(back, AddedText { rect: back.rect, ..settled.clone() });
}
// CMYK looks as ISO 32000-2 §10.4.2.5 maps it to RGB; an ink out of range is refused.
assert_eq!(Ink::Cmyk([0.5, 0.0, 1.0, 0.25]).rgb(), [0.25, 0.75, 0.0]);
let mut wrong = base;
wrong.ink = Some(Ink::Gray(1.5));
assert!(add_content(&mut doc, 0, &Content::Text(wrong)).is_err());
}
/// #6440: a file edited by hand paints its added text in RGB unless the stored gray or CMYK is
/// in range, the right length and still the look of `/Color`; nothing in it panics.
#[test]
fn a_hand_edited_ink_reads_back_only_when_it_is_the_stored_colours_look() {
use crate::added::Ink;
let mut doc = fixture();
add_content(&mut doc, 0, &Content::Text(AddedText { rect: [72.0, 600.0, 300.0, 700.0], text: "Proof".into(), ..AddedText::default() })).unwrap();
let obj = list_added(&doc)[0].obj;
let real = |v: &[f64]| Object::Array(v.iter().map(|x| Object::Real(*x)).collect());
// A `/CMYK` far longer than four numbers, as a hostile file might store it: an ink first.
let long = real(&[0.0, 0.0, 0.0, 1.0].repeat(50_000));
let long_ref = Object::Ref(doc.add(long.clone()));
let ink_ref = Object::Ref(doc.add(real(&[0.0, 0.0, 0.0, 1.0])));
let read_text = |entries: &[(&[u8], Object)]| {
let mut edited = doc.clone();
let Object::Stream(mut s) = (*edited.get(obj)).clone() else { panic!("an item is a stream") };
let mut params = s.dict.get(b"PCAdded").and_then(|p| p.as_dict().cloned()).unwrap();
for (key, value) in entries {
params.set(key.to_vec(), value.clone());
}
s.dict.set(b"PCAdded".to_vec(), Object::Dict(params));
edited.set(obj, Object::Stream(s));
let Content::Text(t) = list_added(&edited)[0].content.clone() else { panic!() };
t
};
let read = |entries: &[(&[u8], Object)]| read_text(entries).ink;
// As PDFCraft writes it: the ink stands.
assert_eq!(read(&[(b"Color", real(&[0.5; 3])), (b"Gray", Object::Real(0.5))]), Some(Ink::Gray(0.5)));
assert_eq!(read(&[(b"Color", real(&[0.0; 3])), (b"CMYK", real(&[0.0, 0.0, 0.0, 1.0]))]), Some(Ink::Cmyk([0.0, 0.0, 0.0, 1.0])));
assert_eq!(read(&[(b"Color", real(&[0.0; 3])), (b"CMYK", ink_ref)]), Some(Ink::Cmyk([0.0, 0.0, 0.0, 1.0])), "by reference");
// Finer than it paints, it reads back as painted (`0.5 g`), its look with it.
let fine = read_text(&[(b"Color", real(&[0.50049; 3])), (b"Gray", Object::Real(0.50049))]);
assert_eq!((fine.ink, fine.color), (Some(Ink::Gray(0.5)), [0.5; 3]));
for (what, entries) in [
("a colour the ink isn't the look of", vec![(&b"Color"[..], real(&[1.0, 0.0, 0.0])), (b"CMYK", real(&[0.0, 0.0, 0.0, 1.0]))]),
("three CMYK numbers", vec![(b"Color", real(&[0.0; 3])), (b"CMYK", real(&[0.0, 0.0, 1.0]))]),
("five CMYK numbers", vec![(b"Color", real(&[0.0; 3])), (b"CMYK", real(&[0.0, 0.0, 0.0, 1.0, 0.0]))]),
("a long CMYK", vec![(b"Color", real(&[0.0; 3])), (b"CMYK", long.clone())]),
("a long CMYK by reference", vec![(b"Color", real(&[0.0; 3])), (b"CMYK", long_ref.clone())]),
("gray a long array", vec![(b"Color", real(&[0.0; 3])), (b"Gray", long.clone())]),
("CMYK not an array", vec![(b"Color", real(&[0.0; 3])), (b"CMYK", Object::Real(1.0))]),
("gray out of range", vec![(b"Color", real(&[1.0; 3])), (b"Gray", Object::Real(2.0))]),
("gray not a number", vec![(b"Color", real(&[0.0; 3])), (b"Gray", Object::name("Black"))]),
(
"a CMYK entry not a number",
vec![
(b"Color", real(&[0.0; 3])),
(b"CMYK", Object::Array(vec![Object::Real(0.0), Object::name("Bad"), Object::Real(0.0), Object::Real(1.0)])),
],
),
(
"gray not a number beside a CMYK",
vec![(b"Color", real(&[0.0; 3])), (b"Gray", Object::name("Black")), (b"CMYK", real(&[0.0, 0.0, 0.0, 1.0]))],
),
("gray NaN", vec![(b"Color", real(&[0.0; 3])), (b"Gray", Object::Real(f64::NAN))]),
("CMYK infinite", vec![(b"Color", real(&[0.0; 3])), (b"CMYK", real(&[0.0, 0.0, 0.0, f64::INFINITY]))]),
] {
assert_eq!(read(&entries), None, "{what}");
}
}
/// #6440: an ink finer than the thousandth `g` and `k` are written to is kept as painted, so the
/// item, its stored `/CMYK` and what it reads back as are what the page shows.
#[test]
fn an_ink_is_kept_as_it_is_painted() {
use crate::added::Ink;
let mut doc = fixture();
let mut t = AddedText { rect: [72.0, 600.0, 300.0, 700.0], text: "Proof".into(), size: 14.0, ..AddedText::default() };
t.set_ink(Some(Ink::Cmyk([0.12345, 0.00049, 0.0, 0.99951])));
let painted = Ink::Cmyk([0.123, 0.0, 0.0, 1.0]);
assert_eq!((t.ink, t.color), (Some(painted), painted.rgb()));
add_content(&mut doc, 0, &Content::Text(t)).unwrap();
let doc = reopen(&doc);
let item = &list_added(&doc)[0];
let Object::Stream(s) = &*doc.get(item.obj) else { panic!("an item is a stream") };
let stream = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned();
assert!(
stream.contains(
"/PCFHelvetica 14 Tf 0.123 0 0 1 k
"
),
"{stream}"
);
let stored = s
.dict
.get(b"PCAdded")
.and_then(|p| p.as_dict())
.and_then(|p| p.get(b"CMYK"))
.and_then(Object::as_array)
.map(|a| a.iter().filter_map(Object::as_f64).collect::<Vec<_>>());
assert_eq!(stored, Some(vec![0.123, 0.0, 0.0, 1.0]));
let Content::Text(back) = &item.content else { panic!() };
assert_eq!(back.painted_ink(), Some(painted));
}
/// #4464: a page left with one added item draws that item and nothing else.
#[test]
fn an_isolated_item_is_all_that_is_left_on_its_page() {
+18 -6
View File
@@ -206,6 +206,20 @@ pub struct OfficeExport {
/// `Err(false)`: it can't be encoded).
type PreparedImage = Result<(&'static str, Arc<[u8]>), bool>;
/// Displayed points per user-space unit on `info`'s page (`/UserUnit`), 1 when the page has no
/// usable size.
pub(crate) fn display_unit(info: &pdfcraft_render::PageInfo) -> f64 {
let crop_width = f64::from(info.crop[2] - info.crop[0]);
let display_width = f64::from(if info.rotation.is_multiple_of(180) { info.width } else { info.height });
if crop_width > 0.0 && crop_width.is_finite() && display_width.is_finite() { display_width / crop_width } else { 1.0 }
}
/// Bold and italic as a font's name says them (`Arial-BoldItalicMT`).
pub(crate) fn weight_and_slant(base_font: &str) -> (bool, bool) {
let f = base_font.to_ascii_lowercase();
(f.contains("bold") || f.contains("black") || f.contains("heavy"), f.contains("italic") || f.contains("oblique"))
}
impl crate::Document {
/// The pages as paragraphs and images (for Word, HTML and RTF export), including what
/// form XObjects draw.
@@ -247,9 +261,7 @@ impl crate::Document {
let b = info.user_to_view(r[2] as f32, r[3] as f32);
[a[0].min(b[0]) as f64, (info.height - a[1].max(b[1])) as f64, a[0].max(b[0]) as f64, (info.height - a[1].min(b[1])) as f64]
};
let crop_width = f64::from(info.crop[2] - info.crop[0]);
let display_width = f64::from(if info.rotation % 180 == 0 { info.width } else { info.height });
let unit = if crop_width > 0.0 && crop_width.is_finite() && display_width.is_finite() { display_width / crop_width } else { 1.0 };
let unit = display_unit(info);
let reading = pdfcraft_edit::reading_blocks_checked(cos, i).unwrap_or_default();
let forms_unread = reading.truncated;
let blocks = reading
@@ -257,7 +269,7 @@ impl crate::Document {
.into_iter()
.filter(|b| !b.text.trim().is_empty())
.map(|b| {
let f = b.base_font.to_ascii_lowercase();
let (bold, italic) = weight_and_slant(&b.base_font);
// `text` is trimmed; the editor text keeps the source's own spaces.
let space_around = [b.editor_text.starts_with(char::is_whitespace), b.editor_text.ends_with(char::is_whitespace)];
pdfcraft_export::Block {
@@ -265,8 +277,8 @@ impl crate::Document {
text: b.text,
rect: visible_rect(b.rect),
size: b.size * unit,
bold: f.contains("bold") || f.contains("black") || f.contains("heavy"),
italic: f.contains("italic") || f.contains("oblique"),
bold,
italic,
color: b.color,
rotation: b.rotation - f64::from(info.rotation),
}
+4 -1
View File
@@ -44,6 +44,7 @@ mod pictures;
pub mod print_raster;
pub mod printcheck;
mod protection;
mod rich_copy;
pub mod scan_clean;
mod scan_colours;
mod scan_fields;
@@ -68,6 +69,7 @@ pub use links::{
MAX_REMOTE_DOCUMENT_BYTES, RemoteDocumentPathError, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path,
};
pub use pdfcraft_edit::strip_subset_tag;
pub use rich_copy::RichCopy;
pub use signature_image::{ImageSignaturePreview, SignatureImage};
pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};
pub use stamp_preview::{CommentLayer, StampPreview};
@@ -91,7 +93,8 @@ pub use pdfcraft_edit::added::{
};
pub use pdfcraft_edit::paragraph_align;
pub use pdfcraft_edit::{
Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,
Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, Ink as TextInk,
MarkKind, Watermark,
};
pub use pdfcraft_forms::{
BorderStyle, CalculatedField, CalculationIssue, CalculationOrder, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont,
+389
View File
@@ -0,0 +1,389 @@
//! Copy with formatting: the selected glyphs of a page as paragraphs of styled spans and an
//! HTML fragment ([`pdfcraft_export::clip_html`]) for the clipboard, next to the plain text.
//!
//! Glyphs come from the text layer (view space); style comes from the page's reading blocks,
//! which never mix styles, mapped into view space. A glyph takes the style of the block its
//! centre lies in; a glyph in no block is copied unstyled.
use pdfcraft_export::{ClipBuilder, ClipStyle, ClipText, clip_html};
use pdfcraft_render::{PageInfo, PageText};
use crate::EditError;
use crate::compare::{display_unit, weight_and_slant};
/// Block tests spent matching glyphs to blocks for one copy; past it the rest is unstyled.
const MAX_MATCH_STEPS: usize = 20_000_000;
/// How far outside a block's box (points) a glyph centre still belongs to it.
const SLACK: f32 = 0.5;
/// Selected text with its formatting.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RichCopy {
/// The paragraphs and spans.
pub text: ClipText,
/// The HTML fragment for the clipboard (empty when nothing was selected).
pub html: String,
/// Styles were left out: the document has no editor to read them, reading stopped at its
/// limits on this page, or matching glyphs to blocks ran out of steps.
pub styles_incomplete: bool,
/// A cap left part of the selection out of `text` and `html`; the plain text has all of it.
pub truncated: bool,
}
struct StyledBlock {
rect: [f32; 4],
style: ClipStyle,
}
impl crate::Document {
/// Selected `glyphs` of `page` (indices into `text`, in copy order) with their formatting.
/// Refused when the document does not allow copying.
pub fn rich_copy(&self, page: usize, text: &PageText, glyphs: &[usize]) -> Result<RichCopy, EditError> {
self.rich_copy_within(page, text, glyphs, MAX_MATCH_STEPS)
}
/// [`Self::rich_copy`] with `steps` block tests to match glyphs to blocks.
fn rich_copy_within(&self, page: usize, text: &PageText, glyphs: &[usize], mut steps: usize) -> Result<RichCopy, EditError> {
self.check_copying()?;
let (blocks, mut incomplete) = self.styled_blocks(page);
let mut nested = vec![None; blocks.len()];
let mut b = ClipBuilder::new();
// The previous glyph's line, block and box, and whether it was a hyphen.
let mut prev: Option<(usize, Option<usize>, [f32; 4], bool)> = None;
for &i in glyphs {
let (Some(g), Some(&line)) = (text.glyphs.get(i), text.line_of.get(i)) else { continue };
let hint = prev.and_then(|(_, b, _, _)| b).filter(|&k| !holds_smaller(&blocks, &mut nested, k, &mut steps));
let found = block_at(&blocks, g.rect, hint, &mut steps).unwrap_or_else(|| {
incomplete = true;
None
});
let line = usize::try_from(line).unwrap_or(usize::MAX);
if let Some((prev_line, prev_block, prev_rect, hyphen)) = prev {
if line != prev_line {
let style = |k: Option<usize>| k.and_then(|k| blocks.get(k)).map(|s| &s.style);
if found.is_none() && prev_block.is_none() {
b.line_break();
} else if found == prev_block || wraps(style(prev_block), style(found), prev_rect, g.rect) {
// A paragraph wrapping: one space, none after a hyphen.
if !hyphen {
b.space();
}
} else {
b.paragraph();
}
} else if text.space_before.get(i).copied().unwrap_or(false) {
b.space();
}
}
let style = found.and_then(|k| blocks.get(k)).map(|s| &s.style);
if !b.push(&g.text, style.unwrap_or(&ClipStyle::default())) {
break;
}
prev = Some((line, found, g.rect, g.text.ends_with('-')));
}
Ok(finish(b, incomplete))
}
/// `page`'s reading blocks in view space with their style, and whether reading stopped at
/// its limits.
fn styled_blocks(&self, page: usize) -> (Vec<StyledBlock>, bool) {
let Some(info) = self.info.pages.get(page) else { return (Vec::new(), false) };
let Some(editor) = self.editor.as_ref() else { return (Vec::new(), true) };
let Ok(reading) = pdfcraft_edit::reading_blocks_checked(&editor.cos, page) else { return (Vec::new(), true) };
let unit = display_unit(info);
let blocks = reading
.blocks
.into_iter()
.filter(|b| !b.text.trim().is_empty())
.map(|b| {
let (bold, italic) = weight_and_slant(&b.base_font);
let style = ClipStyle {
families: pdfcraft_export::font_family(&b.base_font),
size: b.size * unit,
bold: b.bold || bold,
italic: b.italic || italic,
color: b.color,
};
StyledBlock { rect: view_rect(info, b.rect), style }
})
.collect();
(blocks, reading.truncated)
}
}
/// A user-space box as a view-space box (points from the displayed page's top-left, y down).
fn view_rect(info: &PageInfo, r: [f64; 4]) -> [f32; 4] {
let a = info.user_to_view(r[0] as f32, r[1] as f32);
let b = info.user_to_view(r[2] as f32, r[3] as f32);
[a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
}
/// The copy `b` collected, with its HTML; `truncated` when a cap cut the text or the HTML.
fn finish(b: ClipBuilder, styles_incomplete: bool) -> RichCopy {
let text = b.finish();
let (html, cut) = clip_html(&text);
RichCopy { html, truncated: text.truncated || cut, text, styles_incomplete }
}
/// Whether the next line starts inside the same paragraph although its first glyph is in another
/// block: blocks split where the style changes, so a style change at a line's end is still a
/// wrap when the size stays and the lines sit no further apart than their own height allows.
/// Two blocks of the same style, a change of size, or a gap of over half a line are paragraphs.
fn wraps(prev: Option<&ClipStyle>, next: Option<&ClipStyle>, prev_rect: [f32; 4], rect: [f32; 4]) -> bool {
let (Some(prev), Some(next)) = (prev, next) else { return false };
let diff = (prev.size - next.size).abs();
if prev == next || diff.is_nan() || diff > 0.01 {
return false;
}
let height = (prev_rect[3] - prev_rect[1]).max(rect[3] - rect[1]);
// The next line starts just below the last one; a line far above it is another column.
let gap = rect[1] - prev_rect[3];
height > 0.0 && gap.is_finite() && gap >= -height / 2.0 && gap <= height / 2.0
}
/// Whether a block smaller than block `k` overlaps it, so a glyph inside `k` may belong to that
/// one instead. Worked out once per block (`nested` keeps it), at a step per block tested; when
/// the steps run out the answer is yes, so the full search decides.
fn holds_smaller(blocks: &[StyledBlock], nested: &mut [Option<bool>], k: usize, steps: &mut usize) -> bool {
if let Some(Some(known)) = nested.get(k) {
return *known;
}
let Some(outer) = blocks.get(k) else { return true };
let area = |r: &[f32; 4]| (r[2] - r[0]) * (r[3] - r[1]);
let overlaps = |r: &[f32; 4]| r[0] < outer.rect[2] && r[2] > outer.rect[0] && r[1] < outer.rect[3] && r[3] > outer.rect[1];
let mut found = false;
for (j, b) in blocks.iter().enumerate() {
if *steps == 0 {
return true;
}
*steps -= 1;
if j != k && overlaps(&b.rect) && area(&b.rect) < area(&outer.rect) {
found = true;
break;
}
}
if let Some(slot) = nested.get_mut(k) {
*slot = Some(found);
}
found
}
/// The block whose box holds the centre of `glyph` (view space): `hint` first (a block no
/// smaller one overlaps), then the smallest that holds it. Each block tested costs a step;
/// `None` when the steps ran out first.
fn block_at(blocks: &[StyledBlock], glyph: [f32; 4], hint: Option<usize>, steps: &mut usize) -> Option<Option<usize>> {
let (x, y) = ((glyph[0] + glyph[2]) / 2.0, (glyph[1] + glyph[3]) / 2.0);
let holds = |r: &[f32; 4]| x >= r[0] - SLACK && x <= r[2] + SLACK && y >= r[1] - SLACK && y <= r[3] + SLACK;
let area = |r: &[f32; 4]| (r[2] - r[0]) * (r[3] - r[1]);
if let Some(k) = hint
&& *steps > 0
{
*steps -= 1;
if blocks.get(k).is_some_and(|b| holds(&b.rect)) {
return Some(Some(k));
}
}
let mut best: Option<(usize, f32)> = None;
for (k, b) in blocks.iter().enumerate() {
if *steps == 0 {
return None;
}
*steps -= 1;
if holds(&b.rect) && best.is_none_or(|(_, a)| area(&b.rect) < a) {
best = Some((k, area(&b.rect)));
}
}
Some(best.map(|(k, _)| k))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use pdfcraft_export::{ClipBuilder, ClipStyle};
use crate::Session;
/// A heading in bold, a body paragraph of two lines with HTML-special characters, and a red
/// word on the body's first line.
fn styled_page() -> Vec<u8> {
let content = b"BT /F1 24 Tf 20 250 Td (Title) Tj ET \
BT /F2 12 Tf 20 200 Td (Body text) Tj ET \
BT 1 0 0 rg /F2 12 Tf 90 200 Td (red) Tj ET \
BT /F2 12 Tf 20 186 Td (a<b & c) Tj ET";
page_with(content)
}
/// A one-page PDF drawing `content` with `/F1` Helvetica-Bold and `/F2` Helvetica.
fn page_with(content: &[u8]) -> Vec<u8> {
pdfcraft_testkit::Pdf::new()
.obj("<< /Type /Catalog /Pages 2 0 R >>")
.obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>")
.obj("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>")
.stream("", content)
.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>")
.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
.build()
}
fn page_text(s: &Session, id: crate::DocId) -> Arc<pdfcraft_render::PageText> {
let doc = s.get(id).unwrap();
let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), Default::default());
let request = pdfcraft_render::RenderRequest { page: 0, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() };
r.render(request).text.unwrap()
}
#[test]
fn copy_keeps_headings_body_and_colour_as_html() {
let mut s = Session::new();
let id = s.open("styled.pdf", None, Arc::new(styled_page()), None).unwrap();
let text = page_text(&s, id);
let all: Vec<usize> = (0..text.glyphs.len()).collect();
let copy = s.get(id).unwrap().rich_copy(0, &text, &all).unwrap();
let html = &copy.html;
assert!(!copy.styles_incomplete);
assert!(
html.starts_with("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:24pt\"><strong>Title</strong></span></p>\n"),
"{html}"
);
assert!(html.contains("font-size:12pt\">Body text "), "{html}");
assert!(html.contains("font-size:12pt;color:#FF0000\">red</span>"), "{html}");
assert!(html.contains("a&lt;b &amp; c"), "{html}");
assert!(!html.contains("<b &"), "{html}");
assert_eq!(copy.text.paragraphs.len(), html.matches("<p ").count());
assert!(copy.text.paragraphs.len() >= 2, "{html}");
// The heading and the body are separate paragraphs; the red word shares the body's.
let body = copy.text.paragraphs.iter().find(|p| p.iter().any(|s| s.text.contains("Body"))).unwrap();
assert!(body.iter().any(|s| s.text == "red" && s.style.color == [1.0, 0.0, 0.0]), "{body:?}");
// A part of the selection: only those glyphs.
let part = s.get(id).unwrap().rich_copy(0, &text, &all[..5]).unwrap();
assert_eq!(part.text.paragraphs.len(), 1);
assert!(part.html.contains("<strong>Title</strong>"), "{}", part.html);
// Nothing selected, and indices past the text: an empty copy, not a panic.
let none = s.get(id).unwrap().rich_copy(0, &text, &[]).unwrap();
assert!(none.html.is_empty() && none.text.paragraphs.is_empty());
let past = s.get(id).unwrap().rich_copy(7, &text, &[usize::MAX, text.glyphs.len()]).unwrap();
assert!(past.html.is_empty());
}
#[test]
fn running_out_of_match_steps_copies_the_rest_unstyled() {
let mut s = Session::new();
let id = s.open("styled.pdf", None, Arc::new(styled_page()), None).unwrap();
let text = page_text(&s, id);
let all: Vec<usize> = (0..text.glyphs.len()).collect();
let doc = s.get(id).unwrap();
let full = doc.rich_copy(0, &text, &all).unwrap();
// Enough for the first glyphs only: the text is all there, the rest has no style.
let short = doc.rich_copy_within(0, &text, &all, 8).unwrap();
assert!(short.styles_incomplete);
let plain = |c: &super::RichCopy| c.text.paragraphs.iter().flatten().map(|s| s.text.clone()).collect::<String>();
assert_eq!(plain(&short).replace([' ', '\n'], ""), plain(&full).replace([' ', '\n'], ""));
let last = short.text.paragraphs.last().and_then(|p| p.last()).unwrap();
assert_eq!(last.style, pdfcraft_export::ClipStyle::default(), "{last:?}");
assert!(short.html.starts_with("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:24pt\"><strong>T"), "{}", short.html);
// No steps at all: nothing styled, still no panic.
let none = doc.rich_copy_within(0, &text, &all, 0).unwrap();
assert!(none.styles_incomplete && !none.html.contains("font-size"), "{}", none.html);
// A page without blocks to match needs no steps.
let page_less = doc.rich_copy_within(5, &text, &all, 0).unwrap();
assert!(!page_less.styles_incomplete);
}
fn copy_all(s: &Session, id: crate::DocId) -> super::RichCopy {
let text = page_text(s, id);
let all: Vec<usize> = (0..text.glyphs.len()).collect();
s.get(id).unwrap().rich_copy(0, &text, &all).unwrap()
}
#[test]
fn a_style_change_at_a_line_end_stays_in_its_paragraph() {
let content = b"BT /F2 12 Tf 20 200 Td (plain then) Tj ET \
BT /F1 12 Tf 85 200 Td (bold) Tj ET \
BT /F2 12 Tf 20 186 Td (continues here) Tj ET \
BT /F2 12 Tf 20 120 Td (Another paragraph) Tj ET";
let mut s = Session::new();
let id = s.open("wrap.pdf", None, Arc::new(page_with(content)), None).unwrap();
let copy = copy_all(&s, id);
let text = |p: &Vec<pdfcraft_export::ClipSpan>| p.iter().map(|s| s.text.as_str()).collect::<String>();
let paragraphs: Vec<String> = copy.text.paragraphs.iter().map(text).collect();
assert!(paragraphs.iter().any(|p| p.contains("bold") && p.contains("continues")), "{paragraphs:?}");
assert!(paragraphs.iter().any(|p| p.contains("Another") && !p.contains("continues")), "a wide gap is still a paragraph: {paragraphs:?}");
}
#[test]
fn a_style_change_into_the_next_column_starts_a_paragraph() {
let content = b"BT /F2 12 Tf 20 200 Td (left top) Tj ET \
BT /F2 12 Tf 20 186 Td (left end) Tj ET \
BT /F1 12 Tf 170 200 Td (Right head) Tj ET \
BT /F2 12 Tf 170 186 Td (right body) Tj ET";
let mut s = Session::new();
let id = s.open("columns.pdf", None, Arc::new(page_with(content)), None).unwrap();
let copy = copy_all(&s, id);
let text = |p: &Vec<pdfcraft_export::ClipSpan>| p.iter().map(|s| s.text.as_str()).collect::<String>();
let paragraphs: Vec<String> = copy.text.paragraphs.iter().map(text).collect();
assert!(paragraphs.iter().any(|p| p.contains("Right")), "{paragraphs:?}");
assert!(!paragraphs.iter().any(|p| p.contains("left end") && p.contains("Right")), "{paragraphs:?}");
}
#[test]
fn a_styled_word_inside_a_paragraph_keeps_its_style() {
let content = b"BT /F2 12 Tf 20 200 Td (first row of the text) Tj ET \
BT /F2 12 Tf 20 186 Td (second) Tj ET \
BT /F1 12 Tf 62 186 Td (bold) Tj ET \
BT /F2 12 Tf 92 186 Td (row) Tj ET";
let mut s = Session::new();
let id = s.open("nested.pdf", None, Arc::new(page_with(content)), None).unwrap();
let copy = copy_all(&s, id);
let spans: Vec<_> = copy.text.paragraphs.iter().flatten().collect();
assert!(spans.iter().any(|s| s.text.contains("bold") && s.style.bold), "{spans:?}");
assert!(spans.iter().any(|s| s.text.contains("second") && !s.style.bold), "{spans:?}");
}
#[test]
fn a_capped_copy_is_marked_truncated() {
let (plain, bold) = (ClipStyle::default(), ClipStyle { bold: true, ..ClipStyle::default() });
let mut b = ClipBuilder::new();
for k in 0..=pdfcraft_export::MAX_CLIP_SPANS {
b.push("x", if k % 2 == 0 { &plain } else { &bold });
}
let copy = super::finish(b, false);
assert!(copy.truncated && copy.text.truncated);
let mut b = ClipBuilder::new();
b.push("x", &plain);
assert!(!super::finish(b, false).truncated);
}
#[test]
fn without_an_editor_the_styles_are_incomplete() {
let mut s = Session::new();
let id = s.open("styled.pdf", None, Arc::new(styled_page()), None).unwrap();
let text = page_text(&s, id);
let all: Vec<usize> = (0..text.glyphs.len()).collect();
s.doc_mut(id).unwrap().editor = None;
let copy = s.get(id).unwrap().rich_copy(0, &text, &all).unwrap();
assert!(copy.styles_incomplete && !copy.html.contains("font-size"), "{}", copy.html);
assert!(!copy.truncated);
}
#[test]
fn copy_with_formatting_is_refused_when_copying_is_withheld() {
let mut cos = pdfcraft_cos::Document::open(Arc::new(styled_page())).unwrap();
cos.set_encryption(&pdfcraft_cos::NewEncryption {
algorithm: pdfcraft_cos::Algorithm::Aes256,
user_password: "",
owner_password: "owner",
permissions: 0b0100, // print only
encrypt_metadata: true,
seed: [7; 32],
})
.unwrap();
let bytes = Arc::new(pdfcraft_cos::write_full(&cos, &Default::default()).unwrap());
let mut s = Session::new();
let id = s.open("locked.pdf", None, bytes, None).unwrap();
let text = pdfcraft_render::PageText { glyphs: Vec::new(), line_of: Vec::new(), space_before: Vec::new() };
let err = s.get(id).unwrap().rich_copy(0, &text, &[]).unwrap_err();
assert!(matches!(err, crate::EditError::NotPermitted(_)), "{err:?}");
}
}
+3
View File
@@ -4182,6 +4182,7 @@ fn pasted_added_content_keeps_its_style_and_picture() {
italic: true,
size: 12.0,
color: [0.8, 0.1, 0.2],
ink: None,
align: TextAlign::Center,
aligns: Vec::new(),
char_spacing: 0.0,
@@ -8112,6 +8113,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
italic: false,
size: 12.0,
color: [0.0, 0.0, 0.0],
ink: None,
align: TextAlign::Left,
aligns: Vec::new(),
char_spacing: 0.0,
@@ -8153,6 +8155,7 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {
italic: false,
size: 12.0,
color: [0.0, 0.0, 0.0],
ink: None,
align: TextAlign::Left,
aligns: Vec::new(),
char_spacing: 0.0,
+433
View File
@@ -0,0 +1,433 @@
//! Copy with formatting: selected text as paragraphs of styled spans, written as an HTML
//! fragment for the clipboard (inline styles, so a word processor keeps font, size, weight,
//! slant and colour when it pastes).
use crate::as_html::allowed;
use crate::{esc, hex};
/// Spans kept for one copy; text past it is left out and [`ClipText::truncated`] is set.
pub const MAX_CLIP_SPANS: usize = 20_000;
/// Text bytes kept for one copy (before escaping).
pub const MAX_CLIP_TEXT_BYTES: usize = 2 << 20;
/// The HTML written for one copy never passes this many bytes.
pub const MAX_CLIP_HTML_BYTES: usize = 16 << 20;
/// Font sizes are written within this range (points), so a hostile size stays a font size.
const CLIP_SIZE_PT: std::ops::RangeInclusive<f64> = 1.0..=1000.0;
/// A family name longer than this is not a family name.
const MAX_FAMILY_CHARS: usize = 64;
/// How a span looks.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ClipStyle {
/// Family names to try in order ([`font_family`]); empty keeps the target's own.
pub families: Vec<String>,
/// Size in points; zero or not finite leaves the target's size, and any other is written
/// within 1 to 1000.
pub size: f64,
pub bold: bool,
pub italic: bool,
/// Fill colour as RGB in 0..=1.
pub color: [f64; 3],
}
/// A run of text in one style.
#[derive(Clone, Debug, PartialEq)]
pub struct ClipSpan {
pub text: String,
pub style: ClipStyle,
}
/// The copied text: paragraphs of spans, and whether a cap left some out.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ClipText {
pub paragraphs: Vec<Vec<ClipSpan>>,
pub truncated: bool,
}
/// Builds a [`ClipText`] piece by piece, merging pieces of equal style into one span and
/// stopping at the caps.
#[derive(Debug)]
pub struct ClipBuilder {
out: ClipText,
/// The separator owed before the next piece in this paragraph (a space or a line break).
pending: Option<char>,
new_paragraph: bool,
spans: usize,
bytes: usize,
}
impl Default for ClipBuilder {
fn default() -> Self {
Self { out: ClipText::default(), pending: None, new_paragraph: true, spans: 0, bytes: 0 }
}
}
impl ClipBuilder {
pub fn new() -> Self {
Self::default()
}
/// A word space before the next piece (dropped at the start of a paragraph).
pub fn space(&mut self) {
self.pending.get_or_insert(' ');
}
/// A line break inside the paragraph before the next piece.
pub fn line_break(&mut self) {
self.pending = Some('\n');
}
/// The next piece starts a new paragraph.
pub fn paragraph(&mut self) {
self.new_paragraph = true;
self.pending = None;
}
/// Append `text` in `style`. Returns `false` once a cap is reached; nothing more is kept.
pub fn push(&mut self, text: &str, style: &ClipStyle) -> bool {
if self.out.truncated {
return false;
}
if text.is_empty() {
return true;
}
let sep = if self.new_paragraph { None } else { self.pending };
let need = text.len().saturating_add(sep.map_or(0, char::len_utf8));
let Some(bytes) = self.bytes.checked_add(need).filter(|b| *b <= MAX_CLIP_TEXT_BYTES) else {
self.out.truncated = true;
return false;
};
let new_span = self.new_paragraph || self.out.paragraphs.last().and_then(|p| p.last()).is_none_or(|last| last.style != *style);
if new_span && self.spans >= MAX_CLIP_SPANS {
self.out.truncated = true;
return false;
}
if self.new_paragraph {
self.out.paragraphs.push(Vec::new());
self.new_paragraph = false;
}
self.pending = None;
let Some(spans) = self.out.paragraphs.last_mut() else { return false };
match spans.last_mut() {
Some(last) if last.style == *style => {
last.text.extend(sep);
last.text.push_str(text);
}
last => {
// A separator belongs to the span before it, so a new style starts at its text.
if let (Some(last), Some(sep)) = (last, sep) {
last.text.push(sep);
}
spans.push(ClipSpan { text: text.to_owned(), style: style.clone() });
self.spans += 1;
}
}
self.bytes = bytes;
true
}
pub fn finish(self) -> ClipText {
self.out
}
}
/// The family names to try for a font's `/BaseFont`, best first: subset tag and style suffix
/// removed, `PSMT`/`MT`/`PS` dropped. The first has camel case and hyphens spaced
/// (`ABCDEF+TimesNewRomanPSMT` → `Times New Roman`, `MS-Gothic` → `MS Gothic`); the second,
/// when it differs, is the name as spelt (`SimSun`). A hyphen ends the family only before a
/// style word (`Arial-BoldMT`). Only letters, digits, spaces, `-`, `_` and `.` are kept, so a
/// name cannot leave its CSS string. Empty when nothing is left.
pub fn font_family(base_font: &str) -> Vec<String> {
let name = match base_font.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
_ => base_font,
};
let name = name.split_once(',').map_or(name, |(family, _)| family);
let family = match name.rsplit_once('-') {
Some((family, style)) if STYLE_WORDS.iter().any(|w| style.starts_with(w)) => family,
_ => name,
};
let family = family.strip_suffix("PSMT").or_else(|| family.strip_suffix("MT")).or_else(|| family.strip_suffix("PS")).unwrap_or(family);
let mut spaced = String::with_capacity(family.len().min(MAX_FAMILY_CHARS * 2));
let mut prev_lower = false;
for c in family.chars().take(MAX_FAMILY_CHARS) {
if prev_lower && c.is_ascii_uppercase() {
spaced.push(' ');
}
prev_lower = c.is_ascii_lowercase();
spaced.push(if c == '-' { ' ' } else { c });
}
let spelt: String = family.chars().take(MAX_FAMILY_CHARS).collect();
let mut out: Vec<String> = Vec::with_capacity(2);
for f in [safe_family(&spaced), safe_family(&spelt)].into_iter().flatten() {
if !out.contains(&f) {
out.push(f);
}
}
out
}
/// What may follow a hyphen in a `/BaseFont` when the rest names the style, not the family.
const STYLE_WORDS: &[&str] = &[
"Bold", "Italic", "Oblique", "Regular", "Roman", "Light", "Medium", "Semi", "Demi", "Black", "Heavy", "Thin", "Book", "Cond", "Extra", "Ultra",
"Narrow", "Plain", "Normal", "It", "Bd", "Lt", "Md", "Blk", "MT", "PS",
];
/// `family` with only letters, digits, spaces, `-`, `_` and `.`, so it cannot leave a CSS
/// string; `None` when nothing is left.
fn safe_family(family: &str) -> Option<String> {
let kept: String = family.chars().filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.')).take(MAX_FAMILY_CHARS * 2).collect();
let kept = kept.trim();
(!kept.is_empty()).then(|| kept.to_owned())
}
/// The copied text as an HTML fragment, and whether [`MAX_CLIP_HTML_BYTES`] cut it: one `<p>`
/// per paragraph, a `<span>` per run with its families, size and colour inline, bold as
/// `<strong>` and italic as `<em>` (so a target that drops style attributes still keeps them).
/// Text is escaped; a line break is `<br>`, and a space HTML would collapse (after another
/// space, at a paragraph's start or after a break, across runs too) is `&nbsp;`. Never longer
/// than the cap: a paragraph or run that would pass it ends the fragment.
pub fn clip_html(text: &ClipText) -> (String, bool) {
const OPEN: &str = "<p style=\"margin:0\">";
const CLOSE: &str = "</p>\n";
let fits = |len: usize, more: usize| len.saturating_add(more).saturating_add(CLOSE.len()) <= MAX_CLIP_HTML_BYTES;
let mut out = String::new();
for spans in &text.paragraphs {
if !fits(out.len(), OPEN.len()) {
return (out, true);
}
let mut p = String::from(OPEN);
// A paragraph's first space would collapse.
let mut space_before = true;
for span in spans {
let s = span_html(span, &mut space_before);
if !fits(out.len().saturating_add(p.len()), s.len()) {
if p.len() > OPEN.len() {
out.push_str(&p);
out.push_str(CLOSE);
}
return (out, true);
}
p.push_str(&s);
}
p.push_str(CLOSE);
out.push_str(&p);
}
(out, false)
}
/// One run as HTML. `space_before` says whether the text before it ended in a space or a break,
/// and is left saying so for the next run.
fn span_html(span: &ClipSpan, space_before: &mut bool) -> String {
let st = &span.style;
let mut css = Vec::new();
let families: Vec<String> = st.families.iter().filter_map(|f| safe_family(f)).map(|f| format!("'{f}'")).collect();
if !families.is_empty() {
css.push(format!("font-family:{}", families.join(",")));
}
if st.size.is_finite() && st.size != 0.0 {
css.push(format!("font-size:{}pt", num(st.size.clamp(*CLIP_SIZE_PT.start(), *CLIP_SIZE_PT.end()))));
}
if let Some(h) = hex(st.color) {
css.push(format!("color:#{h}"));
}
let mut body = text_html(&span.text, space_before);
if st.italic {
body = format!("<em>{body}</em>");
}
if st.bold {
body = format!("<strong>{body}</strong>");
}
if css.is_empty() { body } else { format!("<span style=\"{}\">{body}</span>", esc(&css.join(";"))) }
}
/// Escape for HTML text in one pass; `\n` becomes `<br>`, and a space after a space or a break
/// (`space_before` carries that in and out) is `&nbsp;`, so a run of spaces keeps its width.
/// Dropped: what [`esc`] drops (C0 controls), C1 controls, a carriage return
/// and the bidirectional overrides and isolates, which would reorder the pasted text.
fn text_html(text: &str, space_before: &mut bool) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars().filter(|c| clip_char(*c)) {
match c {
'\n' => out.push_str("<br>"),
' ' if *space_before => out.push_str("&nbsp;"),
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
c => out.push(c),
}
*space_before = matches!(c, ' ' | '\n');
}
out
}
/// Whether `c` may go into the clipboard HTML's text.
fn clip_char(c: char) -> bool {
allowed(c) && !matches!(c, '\r' | '\u{80}'..='\u{9F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
}
/// A size with at most one decimal and no trailing `.0`.
fn num(v: f64) -> String {
let r = (v * 10.0).round() / 10.0;
if r.fract() == 0.0 { format!("{r:.0}") } else { format!("{r:.1}") }
}
#[cfg(test)]
mod tests {
use super::*;
fn style(size: f64, bold: bool, italic: bool, color: [f64; 3]) -> ClipStyle {
ClipStyle { families: font_family("ABCDEF+Helvetica-Bold"), size, bold, italic, color }
}
#[test]
fn heading_body_and_coloured_span_keep_their_formatting() {
let mut b = ClipBuilder::new();
let heading = style(24.0, true, false, [0.0; 3]);
let body = style(11.5, false, false, [0.0; 3]);
let red = style(11.5, false, true, [1.0, 0.0, 0.0]);
b.push("Title", &heading);
b.paragraph();
b.push("Body", &body);
b.space();
b.push("text", &body);
b.space();
b.push("red", &red);
let clip = b.finish();
assert_eq!(clip.paragraphs.len(), 2);
assert_eq!(clip.paragraphs.get(1).map(Vec::len), Some(2), "{clip:?}");
let (html, cut) = clip_html(&clip);
assert!(!cut);
assert_eq!(
html,
"<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:24pt\"><strong>Title</strong></span></p>\n\
<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:11.5pt\">Body text </span>\
<span style=\"font-family:'Helvetica';font-size:11.5pt;color:#FF0000\"><em>red</em></span></p>\n"
);
}
#[test]
fn special_characters_are_escaped_and_cannot_leave_the_style() {
let st = ClipStyle { families: vec!["Evil';}</style><script>\\\n".into()], size: f64::NAN, ..ClipStyle::default() };
let mut b = ClipBuilder::new();
b.push("<a href=\"x\">&\u{0}\u{1b}</a> two\nline", &st);
let (html, _) = clip_html(&b.finish());
assert_eq!(
html,
"<p style=\"margin:0\"><span style=\"font-family:'Evilstylescript'\">&lt;a href=&quot;x&quot;&gt;&amp;&lt;/a&gt; &nbsp;two<br>line</span></p>\n"
);
}
#[test]
fn invisible_controls_and_bidi_overrides_are_dropped() {
let mut b = ClipBuilder::new();
b.push("a\u{85}b\u{9F}c\rd\u{202E}e\u{2066}f\u{2069}g\u{202A}h\u{2067}i\tj", &ClipStyle::default());
assert_eq!(clip_html(&b.finish()).0, "<p style=\"margin:0\">abcdefghi\tj</p>\n");
}
#[test]
fn font_sizes_stay_within_range() {
for (size, want) in [(1e300, "1000"), (f64::MAX, "1000"), (2e306, "1000"), (0.2, "1"), (9.96, "10"), (-12.0, "1"), (f64::MIN, "1")] {
let st = ClipStyle { size, ..ClipStyle::default() };
let mut b = ClipBuilder::new();
b.push("x", &st);
let (html, _) = clip_html(&b.finish());
assert_eq!(html, format!("<p style=\"margin:0\"><span style=\"font-size:{want}pt\">x</span></p>\n"), "{size}");
}
}
#[test]
fn families_read_like_a_word_processor_names_them() {
let f = |b: &str| font_family(b);
assert_eq!(f("ABCDEF+TimesNewRomanPSMT"), ["Times New Roman", "TimesNewRoman"]);
assert_eq!(f("Arial,BoldItalic"), ["Arial"]);
assert_eq!(f("Arial-BoldMT"), ["Arial"]);
assert_eq!(f("Helvetica-Oblique"), ["Helvetica"]);
assert_eq!(f("MS-Gothic"), ["MS Gothic", "MS-Gothic"], "a hyphen before a family word stays in the name");
assert_eq!(f("Segoe-UI-Bold"), ["Segoe UI", "Segoe-UI"], "the style is the last part");
assert_eq!(f("SimSun"), ["Sim Sun", "SimSun"], "the name as spelt is tried too");
assert_eq!(f("abcdef+Foo"), ["abcdefFoo"], "a lower-case prefix is not a subset tag");
assert!(f("").is_empty());
assert!(f("+'\"\\;").is_empty());
assert!(f(&"Ab".repeat(10_000)).iter().all(|f| f.chars().count() <= MAX_FAMILY_CHARS * 2));
let st = ClipStyle { families: f("SimSun"), ..ClipStyle::default() };
let mut b = ClipBuilder::new();
b.push("x", &st);
assert_eq!(clip_html(&b.finish()).0, "<p style=\"margin:0\"><span style=\"font-family:'Sim Sun','SimSun'\">x</span></p>\n");
}
#[test]
fn spaces_html_would_collapse_keep_their_width() {
let (a, c) = (ClipStyle::default(), ClipStyle { bold: true, ..ClipStyle::default() });
let mut b = ClipBuilder::new();
b.push(" lead a ", &a);
b.push(" b", &c);
b.line_break();
b.push(" c", &a);
assert_eq!(
clip_html(&b.finish()).0,
"<p style=\"margin:0\">&nbsp;lead a <strong>&nbsp;b<br></strong>&nbsp;c</p>\n",
"at a paragraph's start, across runs and after a break"
);
}
#[test]
fn a_default_builder_starts_a_paragraph() {
let mut b = ClipBuilder::default();
assert!(b.push("x", &ClipStyle::default()));
assert_eq!(b.finish().paragraphs.len(), 1);
}
#[test]
fn empty_and_huge_selections_are_bounded() {
let b = ClipBuilder::new();
assert_eq!(clip_html(&b.finish()), (String::new(), false));
let mut b = ClipBuilder::new();
b.space();
assert!(b.push("", &ClipStyle::default()));
assert!(b.finish().paragraphs.is_empty(), "nothing pushed, nothing kept");
// Alternating styles: the span cap stops it.
let (a, c) = (style(10.0, false, false, [0.0; 3]), style(10.0, true, false, [0.0; 3]));
let mut b = ClipBuilder::new();
let mut kept = 0usize;
for i in 0..MAX_CLIP_SPANS + 10 {
if b.push("x", if i % 2 == 0 { &a } else { &c }) {
kept += 1;
}
}
let clip = b.finish();
assert!(clip.truncated);
assert_eq!(kept, MAX_CLIP_SPANS);
// Exactly at the cap, a new paragraph is refused before it is opened.
let mut b = ClipBuilder::new();
for i in 0..MAX_CLIP_SPANS {
assert!(b.push("x", if i % 2 == 0 { &a } else { &c }));
}
b.paragraph();
assert!(!b.push("x", &a));
let clip = b.finish();
assert!(clip.truncated);
assert_eq!(clip.paragraphs.len(), 1, "no empty paragraph past the cap");
// One style: the text cap stops it.
let mut b = ClipBuilder::new();
let chunk = "y".repeat(1 << 16);
// Bounded, so the test fails rather than runs on when the cap is gone.
let pushes = (0..MAX_CLIP_TEXT_BYTES / chunk.len() + 2).take_while(|_| b.push(&chunk, &a)).count();
assert_eq!(pushes, MAX_CLIP_TEXT_BYTES / chunk.len(), "the cap stopped it");
let clip = b.finish();
assert!(clip.truncated);
assert!(clip.paragraphs.iter().flatten().map(|s| s.text.len()).sum::<usize>() <= MAX_CLIP_TEXT_BYTES);
// HTML: escaping grows text up to sixfold; the writer still stops at its cap.
let big = ClipText { paragraphs: vec![vec![ClipSpan { text: "<".repeat(1 << 20), style: a.clone() }]; 8], truncated: false };
let (html, cut) = clip_html(&big);
assert!(cut, "the cut is reported");
assert!(html.len() <= MAX_CLIP_HTML_BYTES && html.ends_with("</p>\n"), "{}", html.len());
assert!(html.len() > MAX_CLIP_HTML_BYTES / 2);
// Empty paragraphs count against the cap too.
let empty = ClipText { paragraphs: vec![Vec::new(); MAX_CLIP_HTML_BYTES / 20], truncated: false };
let (html, cut) = clip_html(&empty);
assert!(cut && html.len() <= MAX_CLIP_HTML_BYTES, "{}", html.len());
}
}
+2
View File
@@ -20,6 +20,7 @@ mod as_docx;
mod as_html;
mod as_markdown;
mod as_rtf;
mod clip;
mod layout;
pub use as_docx::docx;
@@ -34,6 +35,7 @@ pub use as_markdown::markdown;
#[cfg(test)]
use as_markdown::{emphasis, paragraph};
pub use as_rtf::rtf;
pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family};
pub use layout::{Block, Cell, Image, Page, Table};
#[cfg(test)]
use layout::{LOOKUP_STEPS, MAX_COLS, body_size};
+30 -1
View File
@@ -178,7 +178,27 @@ fn entries() -> Result<Entries, SignError> {
/// Whether the store's key is what the certificate needs (RSA; ECDSA on its curve).
fn matches_key(key: &NCryptKey, want: StoreKey) -> Result<(), String> {
let group = key.algorithm_group().map_err(|e| format!("its private key's algorithm couldn't be read: {}", describe(&e)))?;
// Some KSPs (Certisign's desktopID, for one) report NCRYPT_ALGORITHM_GROUP_PROPERTY
// as a character count instead of a byte count, so the group can't be read even though
// the key works. The certificate already names the key type, so an unreadable group is
// trusted: a working key is accepted instead of wrongly rejected. The key size, when it
// can be read, still has to agree with the certificate.
matches_key_from_group(key.algorithm_group().ok(), key, want)
}
/// Core check, decoupled from the NCryptKey handle so the algorithm group can be injected
/// (e.g. forced to `None` to simulate a KSP that reports the property as a character count
/// instead of a byte count, as Certisign's desktopID KSP does).
fn matches_key_from_group(group: Option<AlgorithmGroup>, key: &NCryptKey, want: StoreKey) -> Result<(), String> {
let Some(group) = group else {
return match want {
StoreKey::Rsa => Ok(()),
StoreKey::Ecdsa(bits) => match key.bits() {
Ok(actual) if actual != bits => Err(format!("its certificate holds a P-{bits} key but the store's private key has {actual} bits")),
_ => Ok(()),
},
};
};
let name = |g: &AlgorithmGroup| match g {
AlgorithmGroup::Rsa => "an RSA".to_string(),
AlgorithmGroup::Ecdsa => "an ECDSA".to_string(),
@@ -272,4 +292,13 @@ mod tests {
assert_eq!(describe(&CngError::WindowsError(0x57)), "Windows error 0x00000057");
assert_eq!(describe(&CngError::InvalidHashLength), "Invalid hash length");
}
#[test]
fn key_group_matches_trusts_when_group_unreadable() {
// Certisign's desktopID KSP reports the algorithm-group property as a character
// count (3 for "RSA") instead of a byte count (8), so `algorithm_group` fails. An
// unreadable group must not make a usable key look unusable.
let key = NCryptKey::new_owned(0);
assert_eq!(matches_key(&key, StoreKey::Rsa), Ok(()));
}
}
+3
View File
@@ -245,6 +245,9 @@ impl PdfCraftApp {
last_copied_image: None,
last_copied_file: None,
system_clipboard: true,
html_clipboard_override: None,
#[cfg(not(target_arch = "wasm32"))]
os_clipboard: None,
clipboard_override: None,
attach_override: None,
duplicate_draft: None,
+39 -1
View File
@@ -211,10 +211,48 @@ impl PdfCraftApp {
if !self.may_copy(id) {
return false;
}
ctx.copy_text(text);
// Built only when there is a clipboard to take it.
let html = if self.takes_html() {
self.views
.get(i)
.and_then(DocView::selected_glyphs)
.and_then(|(page, layer, glyphs)| self.session.get(id)?.rich_copy(page, &layer, &glyphs).ok())
// A capped copy would paste less than the plain text holds; paste that instead.
.filter(|copy| !copy.truncated)
.map(|copy| copy.html)
.filter(|html| !html.is_empty())
} else {
None
};
if !html.is_some_and(|html| self.put_rich_text(&html, &text)) {
ctx.copy_text(text);
}
true
}
/// Whether Copy with formatting has a clipboard to write: the system clipboard is on, and
/// this isn't the web build (or a test stands in for the clipboard).
fn takes_html(&self) -> bool {
self.system_clipboard && (self.html_clipboard_override.is_some() || cfg!(not(target_arch = "wasm32")))
}
/// Put `html` on the clipboard with `text` as its plain alternative, in one set (egui has no
/// HTML output, and its own text copy at the end of the frame would replace the HTML).
/// `false` when it wasn't, so the caller copies the plain text the usual way.
fn put_rich_text(&mut self, html: &str, text: &str) -> bool {
if let Some(set) = self.html_clipboard_override.as_mut() {
return set(html, text);
}
#[cfg(not(target_arch = "wasm32"))]
{
crate::os_clipboard::with_kept(&mut self.os_clipboard, |c| c.set().html(html, Some(text))).is_ok()
}
#[cfg(target_arch = "wasm32")]
{
false
}
}
/// The clipboard text of a whole-document copy, once its pages are read; dropped with the
/// document it was copied from, and by any later copy (a text field's, a comment's), which
/// it must not replace. Run at the end of the frame, so it sees this frame's copies.
+16
View File
@@ -93,6 +93,22 @@ impl DocView {
Some(s.text(t)).filter(|x| !x.is_empty())
}
/// The selection's page, its text layer and the selected glyphs in copy order, for Copy with
/// formatting. `None` after Select All of the document and for a column selection, which
/// copy plain text (a column's rows and tab-separated cells are not paragraphs).
pub(crate) fn selected_glyphs(&self) -> Option<(usize, Arc<PageText>, Vec<usize>)> {
if self.all_text {
return None;
}
let s = self.selection?;
let t = self.texts.get(&s.page)?;
let glyphs = match s.span {
Span::Run { anchor, head } => Selection::range(anchor, head).take(t.glyphs.len()).collect(),
Span::Column { .. } => return None,
};
Some((s.page, t.clone(), glyphs))
}
/// Select every page without navigating; shared by Organize and the Pages sidebar.
pub fn select_all_pages(&mut self) -> bool {
self.selected = (0..self.page_count).collect();
+63
View File
@@ -391,3 +391,66 @@ fn save_asks_where_to_keep_an_email_attachment_and_leaves_the_temporary_copy_alo
assert!(app.save_active(SaveTarget::InPlace));
let _ = std::fs::remove_dir_all(&dir);
}
/// #6440: recolouring gray or CMYK text in its open box drops the ink at once. Finishing the box
/// then adds no empty Undo step (the draft equals the item the page reads back), picking the
/// ink's own look again in the same box paints RGB rather than bringing the ink back, and new
/// boxes don't take the ink.
#[test]
fn recolouring_print_ink_text_in_its_box_drops_the_ink_without_an_empty_step() {
// 100 K text, open in its box.
let open = || {
let mut app = crate::PdfCraftApp::new();
app.set_option("language", "en").unwrap();
app.open_bytes("a.pdf", None, one_page_pdf()).unwrap();
let mut text = pdfcraft_engine::AddedText { rect: [20.0, 200.0, 180.0, 220.0], text: "Proof".into(), ..Default::default() };
text.set_ink(Some(pdfcraft_engine::TextInk::Cmyk([0.0, 0.0, 0.0, 1.0])));
assert!(app.apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));
let stored = item(&app);
assert!(stored.painted_ink().is_some());
app.views[0].content.draft = Some(crate::content_ui::TextDraft {
page: 0,
index: Some(0),
rect: stored.rect,
text: stored.text.clone(),
style: stored,
focus: true,
selection: None,
typing_from: None,
});
app
};
fn item(app: &crate::PdfCraftApp) -> pdfcraft_engine::AddedText {
match &app.session.get(app.views[0].id).unwrap().added()[0].content {
pdfcraft_engine::AddedContent::Text(t) => t.clone(),
other => panic!("{other:?}"),
}
}
// The box's style with another colour, set as the Format panel hands it over.
let recolour = |app: &mut crate::PdfCraftApp, color: [f64; 3]| {
let style = app.views[0].content.draft.as_ref().map(|d| d.style.clone()).unwrap();
app.restyle_draft(0, pdfcraft_engine::AddedText { color, ..style });
};
let finish = |app: &mut crate::PdfCraftApp| {
let added = app.session.get(app.views[0].id).unwrap().added().to_vec();
app.views[0].content.finish_draft(&added)
};
// Red, then Done.
let mut app = open();
recolour(&mut app, [1.0, 0.0, 0.0]);
assert_eq!(item(&app).ink, None, "the page paints red in RGB");
let finished = finish(&mut app);
assert!(finished.is_none(), "an empty Undo step: {finished:?}");
assert_eq!(app.text_style.ink, None, "new boxes don't take the ink");
// Red, then black in the same box: RGB black, not the 100 K back.
let mut app = open();
recolour(&mut app, [1.0, 0.0, 0.0]);
recolour(&mut app, [0.0; 3]);
let now = item(&app);
assert_eq!((now.ink, now.color), (None, [0.0; 3]));
assert_eq!(app.text_style.ink, None);
let finished = finish(&mut app);
assert!(finished.is_none(), "an empty Undo step: {finished:?}");
}
+11
View File
@@ -254,6 +254,10 @@ struct PendingOpen {
display_override: Option<(canvas::PageLayout, bool)>,
}
/// Puts `(html, plain_text)` on a clipboard; `false` when it couldn't, and plain-text Copy is
/// used instead.
pub type HtmlClipboard = Box<dyn FnMut(&str, &str) -> bool>;
pub struct PdfCraftApp {
/// Tools side and pane widths; which panes are open is `left_open` and `right`.
pub side_panels: side_panels::SidePanels,
@@ -592,6 +596,13 @@ pub struct PdfCraftApp {
/// system clipboard as a file when `system_clipboard` is on.
pub last_copied_file: Option<(String, Vec<u8>)>,
pub system_clipboard: bool,
/// Where Copy with formatting puts its HTML and the plain alternative instead of the system
/// clipboard, when `system_clipboard` is on (tests).
pub html_clipboard_override: Option<HtmlClipboard>,
/// The system clipboard Copy with formatting writes to, kept open so that X11 goes on
/// serving the copy after the frame.
#[cfg(not(target_arch = "wasm32"))]
os_clipboard: Option<arboard::Clipboard>,
/// What ⌘V reads instead of the system clipboard (tests).
pub clipboard_override: Option<create_ui::Clip>,
/// Attach file: the file to attach instead of asking (tests, automation).
+15
View File
@@ -17,6 +17,21 @@ pub(crate) fn with<T>(f: impl FnOnce(&mut arboard::Clipboard) -> Result<T, arboa
f(&mut clipboard)
}
/// [`with`] on the clipboard kept in `kept`, created on first use, instead of a fresh one. On
/// X11 the copied data is served only while its `Clipboard` lives, so a copy made through a
/// kept clipboard stays pasteable after the call returns.
pub(crate) fn with_kept<T>(
kept: &mut Option<arboard::Clipboard>,
f: impl FnOnce(&mut arboard::Clipboard) -> Result<T, arboard::Error>,
) -> Result<T, arboard::Error> {
let _turn = LOCK.lock().unwrap_or_else(PoisonError::into_inner);
let clipboard = match kept {
Some(clipboard) => clipboard,
None => kept.insert(arboard::Clipboard::new()?),
};
f(clipboard)
}
/// Nonempty text supersedes the app's cached image, even if another clipboard format also exists.
pub(crate) fn has_text() -> bool {
with(|cb| cb.get_text()).is_ok_and(|text| !text.is_empty())
+5 -1
View File
@@ -406,7 +406,11 @@ impl PdfCraftApp {
/// style at once and stays open. Text already on the page is updated with what has been typed,
/// as one undoable change; new text waits until it is finished. Text typed after this styling
/// starts from it too.
pub(crate) fn restyle_draft(&mut self, index: usize, style: pdfcraft_engine::AddedText) {
pub(crate) fn restyle_draft(&mut self, index: usize, mut style: pdfcraft_engine::AddedText) {
// A gray or CMYK ink the colour no longer shows goes now (#6440): kept, the draft would
// differ from the item the page reads back without it, and a later pick of the ink's
// look would bring it back.
style.drop_stale_ink();
let Some(view) = self.views.get_mut(index) else { return };
// Text the standard fonts can't draw stays in the box, unwritten, until it is corrected (#125).
let blocked = view.content.blocked().is_some();
+2 -1
View File
@@ -266,7 +266,8 @@ pub(crate) fn panel(
let swatch = colour_button(ui, t, look.color);
egui::Popup::menu(&swatch).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
if let Some(picked) = crate::comments::swatch_grid(ui, Some(look.color)) {
look.color = picked;
// Drops a gray or CMYK ink the new colour isn't the look of (#6440).
look.set_color(picked);
ui.close();
}
});
+22
View File
@@ -146,3 +146,25 @@ fn alt_drag_with_the_highlighter_marks_only_the_column() {
let marks: Vec<(&str, usize)> = doc.info.annotations.iter().map(|a| (a.subtype.as_str(), a.quads.len())).collect();
assert_eq!(marks, [("Highlight", 4)], "Name, Qty, Apple and 12, each its own quad");
}
/// A column's rows and tab-separated cells are not paragraphs, so Copy puts the plain text on
/// the clipboard and no HTML, even where the clipboard would take it.
#[test]
fn a_column_selection_copies_plain_text_only() {
let offered = std::sync::Arc::new(std::sync::Mutex::new(0usize));
let seen = offered.clone();
let mut h = harness(move |app| {
app.system_clipboard = true;
app.html_clipboard_override = Some(Box::new(move |_, _| {
*seen.lock().unwrap() += 1;
true
}));
});
let (from, to) = top_two_rows(&h);
drag(&mut h, from, to, Modifiers::ALT);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert_eq!(*offered.lock().unwrap(), 0, "no HTML for a column selection");
let copied = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == "Name\tQty\nApple\t12"));
assert!(copied, "the plain text goes out the usual way");
}
+101 -2
View File
@@ -193,7 +193,7 @@ fn copied(h: &Harness<'static, PdfCraftApp>, want: &str) -> bool {
#[test]
fn selected_text_copy_edit_and_context_menus() {
use egui_kittest::kittest::Queryable;
let (mut h, at) = harness(|_| {});
let (mut h, at) = harness(|app| app.system_clipboard = false);
click(&mut h, at);
click(&mut h, at);
h.state_mut().quick_tool = pdfcraft_ui_egui::QuickTool::Hand;
@@ -245,7 +245,7 @@ fn escape_closes_an_open_menu_before_it_clears_the_selection() {
#[test]
fn selected_text_copy_command_requires_selection() {
let (mut h, at) = harness(|_| {});
let (mut h, at) = harness(|app| app.system_clipboard = false);
assert!(!h.state_mut().execute("edit.copy"));
click(&mut h, at);
click(&mut h, at);
@@ -277,6 +277,7 @@ fn selected_text_copy_floating_button_honours_permissions() {
app.open_bytes("no-copy.pdf", None, bytes).unwrap();
app.submit_password(Some(password.into()));
app.set_option("left", "closed").unwrap();
app.system_clipboard = false;
app
});
let mut loaded = false;
@@ -301,6 +302,104 @@ fn selected_text_copy_floating_button_honours_permissions() {
}
}
/// What the stand-in for the system clipboard was given: `(html, plain text)` per copy.
type HtmlSets = std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>>;
/// The system clipboard on, through a stand-in that takes or refuses Copy with formatting.
fn html_clipboard(app: &mut PdfCraftApp, takes: bool) -> HtmlSets {
let sets = HtmlSets::default();
let seen = sets.clone();
app.system_clipboard = true;
app.html_clipboard_override = Some(Box::new(move |html, text| {
seen.lock().unwrap().push((html.to_owned(), text.to_owned()));
takes
}));
sets
}
fn any_copy_text(h: &Harness<'static, PdfCraftApp>) -> bool {
h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(_)))
}
/// Copy with formatting: Copy puts the selection as HTML (font, size) and its plain text on the
/// system clipboard in one set, and doesn't also copy the text through egui, which would
/// replace the HTML. A new copy replaces it.
#[test]
fn selected_text_copy_keeps_the_formatting_as_html() {
let (mut h, at) = harness(|_| {});
let sets = html_clipboard(h.state_mut(), true);
click(&mut h, at);
click(&mut h, at);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert_eq!(
sets.lock().unwrap().as_slice(),
[("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:14pt\">quick</span></p>\n".to_owned(), "quick".to_owned())]
);
assert!(!any_copy_text(&h), "egui's own text copy would replace the HTML");
// Three clicks: the line, a new copy.
h.run_steps(60);
for _ in 0..3 {
click(&mut h, at);
}
assert!(h.state_mut().execute("edit.copy"));
let last = sets.lock().unwrap().last().cloned().unwrap_or_default();
assert!(last.0.contains(">The quick brown fox</span>"), "{last:?}");
assert_eq!(last.1, "The quick brown fox");
}
/// When the system clipboard refuses the HTML, Copy still copies the plain text.
#[test]
fn selected_text_copy_falls_back_to_plain_text_when_html_is_refused() {
let (mut h, at) = harness(|_| {});
let sets = html_clipboard(h.state_mut(), false);
click(&mut h, at);
click(&mut h, at);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert_eq!(sets.lock().unwrap().len(), 1, "the HTML was offered");
assert!(copied(&h, "quick"), "the plain text goes out the usual way");
}
/// With the system clipboard off, no HTML is built and the plain text goes out as before.
#[test]
fn selected_text_copy_without_system_clipboard_builds_no_html() {
let (mut h, at) = harness(|_| {});
let sets = html_clipboard(h.state_mut(), true);
h.state_mut().system_clipboard = false;
click(&mut h, at);
click(&mut h, at);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert!(sets.lock().unwrap().is_empty());
assert!(copied(&h, "quick"));
}
/// A document that withholds copying gives neither the text nor its HTML.
#[test]
fn selected_text_copy_with_formatting_honours_permissions() {
let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(two_lines())).unwrap();
doc.set_encryption(&pdfcraft_cos::NewEncryption {
algorithm: pdfcraft_cos::Algorithm::Aes256,
user_password: "pw",
owner_password: "owner",
permissions: -1 ^ 0b1_0000,
encrypt_metadata: true,
seed: [4; 32],
})
.unwrap();
let bytes = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
let (mut h, at) = harness_with(bytes, |app| app.submit_password(Some("pw".into())));
let sets = html_clipboard(h.state_mut(), true);
click(&mut h, at);
click(&mut h, at);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"));
assert!(!h.state_mut().execute("edit.copy"));
h.step();
assert!(!any_copy_text(&h));
assert!(sets.lock().unwrap().is_empty());
}
#[test]
fn selected_text_copy_preserves_unicode_and_page_clipboard() {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+12
View File
@@ -136,6 +136,18 @@ The messages and both transports are the shared contract of [`craft-web-host`](h
- **Files from the host are untrusted input.** An opened file goes through the same reading as one picked with File ▸ Open or dropped on the window, with the same format limits; before it is copied into the app's memory, its size is checked against the host open limit (512 MiB) and a larger file is refused, and a name is cut to 255 characters.
- **The event and message names are the interface.** `pdfcraft:ready`, `pdfcraft:open`, `pdfcraft:save`, `pdfcraft:dirty` and `pdfcraft:failed`, and the fields they carry (the same as the `?host=parent` messages), stay stable; changing one is a breaking change.
### Driving it from the page (`window.pdfcraft`)
`?control` on the page's URL puts `window.pdfcraft` on the page, from [`craft-web-api`](https://github.com/storytold/craft-libs/tree/main/crates/web-api) (storytold/craft-libs#413), the same shape in every Craft app (`index.html?control`, which can be combined with other flags). It is opt-in because the control channel keeps the accessibility tree of every frame. The browser already exposes PdfCraft's canvas (`id="pdfcraft"`) as `window.pdfcraft`, so the functions are added to that element. `pdfcraft.request(method, params)` calls any method of the UI control channel the desktop app serves with `--control` (`ui.state`, `ui.inspect`, `ui.click`, `ui.key`, `ui.set`…; `ui.open` needs a file system, so on the web it answers with an error and a file is dropped on the page instead), and `execute(command, params)` (`ui.command`: a registry command id), `commands()` (`ui.commands`), `docInspect(params)` (`ui.state`), `uiInspect(params)` (`ui.inspect`) and `screenshot(params)` are shortcuts for the common ones. Each returns a Promise that resolves with the method's result and rejects with an `Error`; a call the app does not answer within 30 seconds rejects, and the app may still reach it later and run it (or reject it), as it does for a desktop client that timed out, so a timed-out call is not guaranteed to have been skipped.
```js
const state = await pdfcraft.docInspect(); // open documents, page, zoom, panels, dialog
await pdfcraft.request("ui.set", { key: "show_page_edge_shadows", value: "false" });
const { data } = await pdfcraft.screenshot(); // the window as PNG (base64)
```
Opening a PDF, handing a saved or exported file to the page, the file name and the unsaved flag stay with the host messages above.
## Renderer selection and fallback flags
PdfCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls back to
+7 -7
View File
@@ -1571,11 +1571,11 @@ title = "Copy text keeping layout"
area = "B"
tier = "P2"
milestone = "M3"
status = "planned"
commands = []
tools = []
evidence = []
notes = ""
status = "partial"
commands = ["edit.copy"]
tools = ["text_extract"]
evidence = ["crates/export/src/clip.rs::heading_body_and_coloured_span_keep_their_formatting", "crates/export/src/clip.rs::special_characters_are_escaped_and_cannot_leave_the_style", "crates/export/src/clip.rs::empty_and_huge_selections_are_bounded", "crates/export/src/clip.rs::invisible_controls_and_bidi_overrides_are_dropped", "crates/export/src/clip.rs::font_sizes_stay_within_range", "crates/engine/src/rich_copy.rs::copy_keeps_headings_body_and_colour_as_html", "crates/engine/src/rich_copy.rs::copy_with_formatting_is_refused_when_copying_is_withheld", "crates/engine/src/rich_copy.rs::running_out_of_match_steps_copies_the_rest_unstyled", "crates/engine/src/rich_copy.rs::a_style_change_at_a_line_end_stays_in_its_paragraph", "crates/engine/src/rich_copy.rs::a_style_change_into_the_next_column_starts_a_paragraph", "crates/engine/src/rich_copy.rs::a_styled_word_inside_a_paragraph_keeps_its_style", "crates/engine/src/rich_copy.rs::a_capped_copy_is_marked_truncated", "crates/engine/src/rich_copy.rs::without_an_editor_the_styles_are_incomplete", "crates/ui-egui/tests/it/column_select.rs::a_column_selection_copies_plain_text_only", "crates/automation/tests/it/automation.rs::text_extract_as_html_keeps_the_formatting", "crates/automation/src/tests.rs::text_extract_html_has_one_budget_across_pages", "crates/ui-egui/tests/it/text_select.rs::selected_text_copy_keeps_the_formatting_as_html", "crates/ui-egui/tests/it/text_select.rs::selected_text_copy_falls_back_to_plain_text_when_html_is_refused", "crates/ui-egui/tests/it/text_select.rs::selected_text_copy_with_formatting_honours_permissions"]
notes = "Copy of a page-text selection also puts HTML on the system clipboard (paragraphs, bold, italic, size, colour, font family; plain text as the alternative), and text_extract format html returns the same. Missing: RTF, underline and strike-through, tables, Select All of the whole document (plain text only), the web build (plain text only), styles for glyphs outside the page's reading blocks (copied unstyled), and HTML for a column selection (plain text only; text_extract with rect gives its HTML in line order, not as the column's rows)"
[[feature]]
id = "view.snapshot"
@@ -2047,8 +2047,8 @@ milestone = "M7"
status = "shipped"
commands = ["edit.text"]
tools = ["page_add_text", "content_update"]
evidence = ["crates/ui-egui/tests/it/content.rs::typing_moving_styling_and_deleting_added_content", "crates/ui-egui/tests/it/content.rs::clicking_elsewhere_keeps_the_text_and_starts_a_new_box", "crates/automation/tests/it/automation.rs::adding_content_through_tools", "crates/edit/src/tests.rs::added_text_and_images_are_page_content_that_stays_editable", "crates/engine/src/tests.rs::added_text_and_images_render_and_stay_editable", "crates/edit/src/tests.rs::added_arabic_text_is_shaped_in_display_order_and_stays_searchable", "crates/automation/tests/it/automation.rs::thai_text_through_tools_saves_reopens_extracts_and_renders", "crates/ui-egui/tests/it/content.rs::typing_thai_text_keeps_marks_and_commits_to_page", "crates/automation/tests/it/automation.rs::added_arabic_text_keeps_copy_search_and_editor_order_after_retyping_and_reopen", "crates/edit/src/tests.rs::added_hebrew_text_is_drawn_right_to_left_and_stays_searchable", "crates/automation/tests/it/automation.rs::hebrew_text_through_tools_saves_reopens_extracts_and_renders"]
notes = "page content, editable later (retype, move, restyle); standard fonts, Windows-1252 text. Arabic text is shaped with the craft-fonts Arab face (Type 3 outlines with ToUnicode) and laid out in bidirectional display order; per-line ActualText keeps copy, search and editor text in typing order through retyping and save/reopen; it is drawn regular whatever the bold/italic setting, and typing in the box is still left to right (misc.rtl-ui). Hebrew (#128) takes the same path with the craft-fonts Hebr face (Noto Sans Hebrew): right-to-left display order, points and cantillation kept on their letter as one glyph, ToUnicode and per-line ActualText; regular style only, and right-to-left scripts other than Arabic and Hebrew are not covered. Thai Add Text uses the craft-fonts Thai face, with shaped clusters and ToUnicode; Thai is regular style, wrapping preserves clusters but is not dictionary-based, and forms/Fill and Sign are not covered by this change. Each click on the page keeps the box being typed and starts a new one; Done and Discard beside the box"
evidence = ["crates/ui-egui/tests/it/content.rs::typing_moving_styling_and_deleting_added_content", "crates/ui-egui/tests/it/content.rs::clicking_elsewhere_keeps_the_text_and_starts_a_new_box", "crates/automation/tests/it/automation.rs::adding_content_through_tools", "crates/edit/src/tests.rs::added_text_and_images_are_page_content_that_stays_editable", "crates/engine/src/tests.rs::added_text_and_images_render_and_stay_editable", "crates/edit/src/tests.rs::added_arabic_text_is_shaped_in_display_order_and_stays_searchable", "crates/automation/tests/it/automation.rs::thai_text_through_tools_saves_reopens_extracts_and_renders", "crates/ui-egui/tests/it/content.rs::typing_thai_text_keeps_marks_and_commits_to_page", "crates/automation/tests/it/automation.rs::added_arabic_text_keeps_copy_search_and_editor_order_after_retyping_and_reopen", "crates/edit/src/tests.rs::added_hebrew_text_is_drawn_right_to_left_and_stays_searchable", "crates/automation/tests/it/automation.rs::hebrew_text_through_tools_saves_reopens_extracts_and_renders", "crates/edit/src/tests.rs::gray_and_cmyk_added_text_writes_g_and_k_until_it_is_recoloured", "crates/automation/tests/it/automation.rs::added_text_takes_a_cmyk_or_gray_ink_through_tools", "crates/ui-egui/src/editing/tests.rs::recolouring_print_ink_text_in_its_box_drops_the_ink_without_an_empty_step"]
notes = "page content, editable later (retype, move, restyle); standard fonts, Windows-1252 text. The colour is RGB, or for print files gray or CMYK (#6440: page_add_text / content_update gray or cmyk, painted with g / k so black can be 100 K, kept through save and reopen; choosing another colour later, also from the Format panel, drops the ink for good and paints in RGB, while choosing the colour the ink already shows (black on 100 K) keeps it; content_update color always paints in RGB). Arabic text is shaped with the craft-fonts Arab face (Type 3 outlines with ToUnicode) and laid out in bidirectional display order; per-line ActualText keeps copy, search and editor text in typing order through retyping and save/reopen; it is drawn regular whatever the bold/italic setting, and typing in the box is still left to right (misc.rtl-ui). Hebrew (#128) takes the same path with the craft-fonts Hebr face (Noto Sans Hebrew): right-to-left display order, points and cantillation kept on their letter as one glyph, ToUnicode and per-line ActualText; regular style only, and right-to-left scripts other than Arabic and Hebrew are not covered. Thai Add Text uses the craft-fonts Thai face, with shaped clusters and ToUnicode; Thai is regular style, wrapping preserves clusters but is not dictionary-based, and forms/Fill and Sign are not covered by this change. Each click on the page keeps the box being typed and starts a new one; Done and Discard beside the box"
[[feature]]
id = "edit.find-replace"