diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 0000000000..acbdeff607 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,188 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/ai-core.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/atomic.yml': + - 'actions/checkout@v4.4.0' + - 'actions/checkout@v7.0.1' + - 'dtolnay/rust-toolchain@stable' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/audio.yml': + - 'actions/cache@v6.1.0' + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/cms.yml': + - 'actions/checkout@v4.4.0' + - 'dtolnay/rust-toolchain@stable' + '.github/workflows/crw.yml': + - 'actions/cache@v6.1.0' + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/dialogs.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/doc.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/docpath.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/ecproj-format.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/font-store.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/formats.yml': + - 'actions/checkout@v7.0.1' + - 'dtolnay/rust-toolchain@stable' + - 'step-security/harden-runner@v2.22.4' + - 'swatinem/rust-cache@v2.9.3' + '.github/workflows/house-rules.yml': [] + '.github/workflows/i18n.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/jpeg.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/keymap.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/lockfile.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/media.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/menu.yml': + - 'actions/checkout@v7.0.1' + - 'dtolnay/rust-toolchain@stable' + - 'swatinem/rust-cache@v2.9.3' + '.github/workflows/pcraft-format.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/pdf.yml': + - 'actions/checkout@v7.0.1' + - 'actions/setup-python@v7.1.0' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + - 'step-security/taiki-e-install-action@v2.87.32' + '.github/workflows/print.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/proof.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/sonarcloud.yml': [] + '.github/workflows/ui.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/update.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/vectorcraft-format.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/video.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + '.github/workflows/web-api.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/taiki-e-install-action@v2.87.32' + '.github/workflows/web-host.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + - 'step-security/rust-cache@v2.9.2' + - 'step-security/taiki-e-install-action@v2.87.32' + '.github/workflows/window.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/dtolnay-rust-toolchain@v1.0.0' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/workspace.yml': [] +dependencies: + 'actions/cache@v6.1.0': + ref: 'v6.1.0' + commit: 'sha1-55cc8345863c7cc4c66a329aec7e433d2d1c52a9' + owner_id: 44036562 + repo_id: 215566462 + 'actions/checkout@v4.4.0': + ref: 'v4.4.0' + commit: 'sha1-11d5960a326750d5838078e36cf38b85af677262' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'actions/setup-python@v7.1.0': + ref: 'v7.1.0' + commit: 'sha1-6d4fd22b20465ccc0f7354476588e8df7c9ca0e0' + owner_id: 44036562 + repo_id: 192625525 + 'dtolnay/rust-toolchain@stable': + ref: 'stable' + commit: 'sha1-b725eda525362e7cf34af9a7243cac1e3f01a7ec' + owner_id: 1940490 + repo_id: 260749683 + 'step-security/dtolnay-rust-toolchain@v1.0.0': + ref: 'v1.0.0' + commit: 'sha1-8dd607977d06adf4ed49b190381e74c17a9dd25f' + owner_id: 88700172 + repo_id: 1249865941 + 'step-security/harden-runner@v2.22.4': + ref: 'v2.22.4' + commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' + owner_id: 88700172 + repo_id: 422287306 + 'step-security/rust-cache@v2.9.2': + ref: 'v2.9.2' + commit: 'sha1-8871c8ba063416da7c32246932ea6ae08700453e' + owner_id: 88700172 + repo_id: 822636713 + 'step-security/taiki-e-install-action@v2.87.32': + ref: 'v2.87.32' + commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8' + owner_id: 88700172 + repo_id: 1382753260 + 'swatinem/rust-cache@v2.9.3': + ref: 'v2.9.3' + commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' + owner_id: 580492 + repo_id: 298565987 diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index cc8d738ac9..5471bf1ec0 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index 1a20fa6791..f72a64f1e1 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy @@ -50,7 +50,7 @@ jobs: name: Atomic WASM runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - uses: dtolnay/rust-toolchain@stable with: targets: wasm32-unknown-unknown diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 0517efe6f2..d6a7ff5e25 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -25,18 +25,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-lint save-if: ${{ github.ref == 'refs/heads/main' }} @@ -69,15 +69,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false # The workspace's rust-version. - run: rustup toolchain install 1.95.0 --profile minimal - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-msrv save-if: ${{ github.ref == 'refs/heads/main' }} @@ -88,16 +88,16 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-features save-if: ${{ github.ref == 'refs/heads/main' }} @@ -113,20 +113,20 @@ jobs: runs-on: ubuntu-26.04 steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-audio-test save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + - uses: actions/cache@v6.1.0 with: path: ${{ runner.temp }}/media-fixtures/opus/vectors # The archive's SHA-256 (scripts/fetch-opus-vectors.sh checks it). diff --git a/.github/workflows/cms.yml b/.github/workflows/cms.yml index a15a48c9d3..74ce0815fa 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -16,7 +16,7 @@ jobs: timeout-minutes: 20 runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - uses: dtolnay/rust-toolchain@stable with: components: clippy diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 8fec986612..54be7ba3ba 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -29,17 +29,17 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-crw-${{ matrix.os }} save-if: ${{ github.ref == 'refs/heads/main' }} @@ -53,17 +53,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-crw-wasm save-if: ${{ github.ref == 'refs/heads/main' }} @@ -75,21 +75,21 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-crw-samples save-if: ${{ github.ref == 'refs/heads/main' }} - name: Cache the CC0 sample files - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: actions/cache@v6.1.0 with: path: ${{ runner.temp }}/crw-samples key: crw-samples-${{ hashFiles('crates/crw/tests/samples.json') }} diff --git a/.github/workflows/dialogs.yml b/.github/workflows/dialogs.yml index 97a931aec6..c8d43d725e 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -23,15 +23,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: # The token isn't needed after checkout; cargo runs build scripts and proc macros from # dependencies, so don't leave it in .git/config for that third-party code to read. persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: clippy diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index a0c619c1e6..6caa4f0eea 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/docpath.yml b/.github/workflows/docpath.yml index 571b65eca6..e0115f6f58 100644 --- a/.github/workflows/docpath.yml +++ b/.github/workflows/docpath.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index 16bab05c76..24a3350af8 100644 --- a/.github/workflows/ecproj-format.yml +++ b/.github/workflows/ecproj-format.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/font-store.yml b/.github/workflows/font-store.yml index f246f621ab..0578f18ec4 100644 --- a/.github/workflows/font-store.yml +++ b/.github/workflows/font-store.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index e19902e8cf..84d2c0d7e9 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -72,17 +72,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: Swatinem/rust-cache@v2.9.3 with: key: ${{ matrix.crate }} save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index 5f717aeff6..7e69031884 100644 --- a/.github/workflows/i18n.yml +++ b/.github/workflows/i18n.yml @@ -28,11 +28,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index 900baf6787..21db0ab794 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -25,18 +25,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-jpeg save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index aba5352655..41fcc0502d 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -27,24 +27,24 @@ jobs: CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Checkout test fonts - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v7.0.1 with: repository: storytold/craft-fonts ref: b076417b5880bd4154bd22f00695b1d28c6bea83 path: .test-inputs/craft-fonts persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-keymap-linux save-if: ${{ github.ref == 'refs/heads/main' }} @@ -71,23 +71,23 @@ jobs: CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Checkout test fonts - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v7.0.1 with: repository: storytold/craft-fonts ref: b076417b5880bd4154bd22f00695b1d28c6bea83 path: .test-inputs/craft-fonts persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-keymap-${{ matrix.os }} save-if: ${{ github.ref == 'refs/heads/main' }} @@ -98,17 +98,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-keymap-wasm save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml new file mode 100644 index 0000000000..e630c9a8f3 --- /dev/null +++ b/.github/workflows/lockfile.yml @@ -0,0 +1,34 @@ +name: Lockfile + +# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin +# no longer verifies upstream, so a moved tag cannot slip a different commit into a run. +# Docs: https://gh.io/actions-lockfile +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + GH_TOKEN: ${{ github.token }} + +jobs: + lockfile: + name: Lockfile is in sync + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install gh-actions-lock + run: gh extension install github/gh-actions-lock --pin v0.4.1 + - name: Verify the lockfile + run: gh actions-lock --verify diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index cb3912d54e..4814e35ca8 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -25,18 +25,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-media-lint save-if: ${{ github.ref == 'refs/heads/main' }} @@ -56,16 +56,16 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-media-test save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index 6d0e082cb1..8d10587313 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -21,14 +21,14 @@ jobs: name: Menu (Linux) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy targets: aarch64-apple-darwin, wasm32-unknown-unknown - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: Swatinem/rust-cache@v2.9.3 with: key: craft-menu-linux - run: cargo fmt -p craft-menu --check diff --git a/.github/workflows/pcraft-format.yml b/.github/workflows/pcraft-format.yml index 177bb45938..9c66b5a10d 100644 --- a/.github/workflows/pcraft-format.yml +++ b/.github/workflows/pcraft-format.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" components: rustfmt, clippy diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index a494d085cf..09ddfabcab 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -31,19 +31,19 @@ jobs: RUSTFLAGS: --cfg craft_pdf_unicode_fixtures steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-pdf save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" - name: Provision licensed PDF test fonts @@ -61,14 +61,14 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-pdf-backends save-if: ${{ github.ref == 'refs/heads/main' }} @@ -81,19 +81,19 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-pdf-wasm save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" - name: Provision licensed PDF test fonts @@ -111,7 +111,7 @@ jobs: - name: Install the matching WASM test runner # A prebuilt, checksum-verified binary instead of building it from source on every run. # A version the pinned action does not list yet falls back to `cargo install --locked`. - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 + uses: step-security/taiki-e-install-action@v2.87.32 with: tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }} fallback: cargo-install @@ -122,19 +122,19 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-plate-test save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" - name: Provision licensed PDF test fonts diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 3838e6c429..8e2108e096 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -24,11 +24,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index 0035b1c04a..10365a2306 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -25,27 +25,27 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false # The Language data (craft-i18n `language-data/`), embedded by crates/proof/build.rs. # Pinned to storytold/craft-i18n#114's head (#109's SCOWL dictionaries + judgment/judgement, # CP2.1); TODO(CP2.1): move to #114's merge commit once it merges. - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: repository: storytold/craft-i18n ref: c239f934ace90b7939afaceb23b472ceeafd6b8a path: craft-i18n persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-proof save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 0892f5a2c8..f15ef6ddc8 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -30,21 +30,21 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 - name: Install software Vulkan renderer if: runner.os == 'Linux' run: | sudo apt-get update sudo apt-get install -y mesa-vulkan-drivers libvulkan1 echo 'WGPU_BACKEND=vulkan' >> "$GITHUB_ENV" - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-ui save-if: ${{ github.ref == 'refs/heads/main' }} @@ -59,15 +59,15 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: actions/checkout@v7.0.1 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-ui-wasm save-if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index f9c8e1498c..9a7139026d 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -28,15 +28,15 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: # The token isn't needed after checkout; cargo runs build scripts and proc macros from # dependencies, so don't leave it in .git/config for that third-party code to read. persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index b2b20463a0..74144f30f4 100644 --- a/.github/workflows/vectorcraft-format.yml +++ b/.github/workflows/vectorcraft-format.yml @@ -28,13 +28,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" components: rustfmt, clippy diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index ec1c16eda3..fa667bdfca 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -22,18 +22,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-video-lint - run: cargo fmt -p craft-video --check @@ -60,16 +60,16 @@ jobs: name: Video tests (${{ matrix.os }}) steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-video-${{ matrix.os }} - name: Install ffmpeg (Linux) diff --git a/.github/workflows/web-api.yml b/.github/workflows/web-api.yml index 2460fb5695..4bf1a30fe8 100644 --- a/.github/workflows/web-api.yml +++ b/.github/workflows/web-api.yml @@ -26,13 +26,13 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy @@ -46,7 +46,7 @@ jobs: - name: Install the matching WASM test runner # A prebuilt, checksum-verified binary instead of building it from source on every run. # A version the pinned action does not list yet falls back to `cargo install --locked`. - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 + uses: step-security/taiki-e-install-action@v2.87.32 with: tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }} fallback: cargo-install diff --git a/.github/workflows/web-host.yml b/.github/workflows/web-host.yml index b780ee76b0..76e6701e53 100644 --- a/.github/workflows/web-host.yml +++ b/.github/workflows/web-host.yml @@ -27,18 +27,18 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 + - uses: step-security/rust-cache@v2.9.2 with: key: craft-web-host save-if: ${{ github.ref == 'refs/heads/main' }} @@ -55,7 +55,7 @@ jobs: - name: Install the matching WASM test runner # A prebuilt, checksum-verified binary instead of building it from source on every run. # A version the pinned action does not list yet falls back to `cargo install --locked`. - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 + uses: step-security/taiki-e-install-action@v2.87.32 with: tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }} fallback: cargo-install diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml index f570ef5ceb..fdd28e2030 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -28,15 +28,15 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.1 with: # The token isn't needed after checkout; cargo runs build scripts and proc macros from # dependencies, so don't leave it in .git/config for that third-party code to read. persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable components: rustfmt, clippy diff --git a/Cargo.lock b/Cargo.lock index 7b965e3f73..c11a134ae5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1846,17 +1846,22 @@ dependencies = [ name = "craft-image-codecs" version = "0.1.0" dependencies = [ + "avif-serialize", "craft-heif", "craft-jpeg", + "craft-metadata", "exr", "flate2", "half", + "hayro-jpeg2000", "image", "image-webp", "jpeg-encoder 0.6.1", "jxl-oxide", "png 0.18.1", "proptest", + "rav1e", + "ravif", "rayon", "serde_json", "thiserror 2.0.21", @@ -1885,7 +1890,9 @@ dependencies = [ name = "craft-jpeg" version = "0.1.0" dependencies = [ + "jpeg-decoder", "jpeg-encoder 0.6.1", + "rayon", "thiserror 2.0.21", "zune-jpeg", ] @@ -2178,6 +2185,7 @@ dependencies = [ "bytemuck", "chrono", "craft-stream-codecs", + "craft-svg", "flate2", "hayro", "hayro-cmap", @@ -2185,6 +2193,7 @@ dependencies = [ "hayro-syntax", "js-sys", "krilla", + "krilla-svg", "kurbo 0.13.1", "md-5 0.11.0", "proptest", @@ -2194,6 +2203,7 @@ dependencies = [ "stringprep", "thiserror 2.0.21", "ttf-parser", + "usvg 0.47.0", "wasm-bindgen", "wasm-bindgen-test", "zeroize", @@ -2359,6 +2369,18 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-ps" +version = "0.1.0" +dependencies = [ + "craft-eps", + "kurbo 0.13.1", + "miniz_oxide 0.8.9", + "pdf-writer", + "skrifa 0.47.0", + "weezl 0.1.12", +] + [[package]] name = "craft-psd" version = "0.1.0" @@ -2565,6 +2587,14 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "craft-texture" +version = "0.1.0" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-tga" version = "0.1.0" @@ -2805,6 +2835,7 @@ name = "craft-xml" version = "0.1.0" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] @@ -4038,6 +4069,20 @@ dependencies = [ "roxmltree 0.20.0", ] +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + [[package]] name = "fontdb" version = "0.24.0" @@ -5326,6 +5371,15 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" +dependencies = [ + "rayon", +] + [[package]] name = "jpeg-encoder" version = "0.6.1" @@ -5624,6 +5678,22 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "krilla-svg" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1237d7c37b16ca9fbc2e72dde13a10d321f9a44aceee35c062bc0a43bfc7ce16" +dependencies = [ + "flate2", + "fontdb 0.23.0", + "krilla", + "resvg 0.47.0", + "skrifa 0.42.1", + "smallvec", + "tiny-skia 0.12.0", + "usvg 0.47.0", +] + [[package]] name = "kurbo" version = "0.11.3" @@ -7831,6 +7901,23 @@ dependencies = [ "usvg 0.45.1", ] +[[package]] +name = "resvg" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be183ad6a216aa96f33e4c8033b0988b8b3ea6fd2359d19af5bac4643fd8e81" +dependencies = [ + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes 0.16.2", + "tiny-skia 0.12.0", + "usvg 0.47.0", + "zune-jpeg", +] + [[package]] name = "resvg" version = "0.48.1" @@ -9877,6 +9964,34 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "usvg" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d46cf96c5f498d36b7a9693bc6a7075c0bb9303189d61b2249b0dc3d309c07de" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "fontdb 0.23.0", + "imagesize 0.14.0", + "kurbo 0.13.1", + "log", + "pico-args", + "roxmltree 0.21.2", + "rustybuzz", + "simplecss", + "siphasher", + "strict-num", + "svgtypes 0.16.2", + "tiny-skia-path 0.12.0", + "ttf-parser", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + [[package]] name = "usvg" version = "0.48.1" @@ -9885,7 +10000,7 @@ checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" dependencies = [ "base64 0.23.1", "data-url", - "fontdb", + "fontdb 0.24.0", "harfrust 0.12.0", "imagesize 0.15.0", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 57b7d3ef7c..576efca6f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,8 +20,13 @@ craft-affinity = { path = "crates/affinity" } craft-ai-core = { path = "crates/ai-core" } craft-anicraft-format = { path = "crates/anicraft-format" } craft-pdf = { path = "crates/pdf", version = "=0.1.0" } +craft-ps = { path = "crates/ps", version = "=0.1.0" } craft-pdn = { path = "crates/pdn" } craft-plate-test = { path = "crates/plate-test" } +pdf-writer = "0.15" +miniz_oxide = "0.8" +weezl = "0.1" +skrifa = "0.47" krilla = { version = "=0.8.2", default-features = false, features = ["raster-images"] } hayro = { version = "=0.7.1", default-features = false } hayro-interpret = { version = "=0.7.0", default-features = false, features = ["embed-fonts", "embed-cmaps"] } @@ -86,10 +91,10 @@ craft-keymap = { path = "crates/keymap" } craft-assuan = { path = "crates/assuan" } craft-kra = { path = "crates/kra" } craft-audio = { path = "crates/audio" } -# No default features, so craft-audio's `encode` builds craft-media without `isobmff`. craft-latex = { path = "crates/latex" } craft-markdown = { path = "crates/markdown" } craft-math = { path = "crates/math" } +# No default features: craft-audio turns on the craft-media modules each of its features needs. craft-media = { path = "crates/media", default-features = false } craft-materialx = { path = "crates/materialx" } craft-media-testkit = { path = "crates/media-testkit" } @@ -134,6 +139,7 @@ craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } craft-text = { path = "crates/text" } +craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } diff --git a/NOTICE b/NOTICE index e1cffb26ce..4fa5e4754e 100644 --- a/NOTICE +++ b/NOTICE @@ -254,9 +254,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and one local patch. Its manifest names Joe Neeman -as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See -vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local patch +vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs and +docs/sweep.typ. Its manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 +Raph Levien". See vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for +provenance, the local patches and the files left out. Platform lifecycle source provenance diff --git a/README.md b/README.md index aa47358da3..c6e95bd4f9 100644 --- a/README.md +++ b/README.md @@ -231,9 +231,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit sockets: session, requests of method calls with back-references, responses, ids, address templates, credentials and the judgement of HTTP answers, over any HTTP implementation. Bounded on hostile answers; what a program asks and makes of the answers stays in it. -- [`craft-jpeg`](crates/jpeg/README.md): clean-room decoder for 12-bit and arithmetic-coded - JPEG (T.81 SOF0/SOF1 at 12 bits, SOF9, SOF10), from PhotoCraft, and a frame probe for routing. - Metadata stays in each app. +- [`craft-jpeg`](crates/jpeg/README.md): clean-room JPEG decoder for 12-bit and arithmetic-coded + frames (T.81 SOF0/SOF1 at 12 bits, SOF9, SOF10), band decoding, and an optimized 8-bit baseline + encoder, from PhotoCraft; includes a frame probe for routing. Metadata interpretation stays in + each app. - [`craft-raster-codecs`](crates/raster-codecs/README.md): small raster formats, one module each, from PhotoCraft: DDS (BC1 to BC3, read and write), DICOM, FITS (read and write), IFF/ILBM (read and write), PCX, PNM/PAM/PFM (read and write) and XPM, into one flat image type. Bounded and @@ -347,6 +348,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). +- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with + nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are + bounded by `Limits`. From MaterialCraft. - [`craft-ui`](crates/ui/README.md): SVG catalogs, icon buttons, tabs, pane controls, transactional docking, print settings and theme helpers for egui frontends; assets, themes, localization and command handling stay in each app. Requires Rust 1.95 or later. - [`craft-vcard`](crates/vcard/README.md): vCard contacts, from MailCraft: vCard 2.1, 3.0 and 4.0 read diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 9b6200198e..d132f23da2 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -23,6 +23,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa- # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. +# All but Opus are also file formats of `encode` and `FileEncoder`. encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] @@ -32,16 +33,18 @@ pcm-encode = [] flac-encode = ["craft-media/bitstream"] # Codec modules on their own, for packet-level use. aac-decode = ["craft-media/bitstream"] -aac-encode = ["craft-media/bitstream"] +# The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. +aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] opus-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) decoder (`mp3::Decoder`). mp3-decode = ["mpa-decode"] -# ALAC packet decoder and encoder (`alac`), ported from Apple's reference implementation. +# ALAC packet decoder and encoder (`alac`), ported from Apple's reference implementation. The +# encoder also writes ALAC in M4A through `encode` and `FileEncoder`. alac-decode = [] -alac-encode = [] +alac-encode = ["craft-media/isobmff"] ac3-encode = ["craft-media/bitstream"] eac3-encode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) encoder (`mp3`). diff --git a/crates/audio/README.md b/crates/audio/README.md index 518dbeb4cc..5a5df4f2f5 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -29,19 +29,19 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `decode` | `decode`, `probe`, `Decoder`, `tracks`, `TrackDecoder`; every format in [Format support](#format-support) | `decode-native`, `symphonia` | | `decode-native` | the same, native formats only (others are `Unsupported`); `wav_pcm`, `aiff_pcm` (a file's integer PCM bit for bit, as `RawPcm`) | the six decoders below, craft-media `isobmff`/`matroska`/`ogg`, `log` | | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | -| `encode` | every encoder: the WAV, AIFF and FLAC file writers, and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode` | +| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | | `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | -| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams) | craft-media `bitstream` | +| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | | `alac-decode` | `alac::Decoder` | none | -| `alac-encode` | `alac::Encoder` | none | +| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | | `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | -| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder` | craft-media `bitstream` | +| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | -| `mp3-encode` | `mp3::Encoder` | craft-media `bitstream` | +| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | @@ -230,17 +230,86 @@ let wav = encode(&surround, &EncodeOptions::default().with_layout(ChannelLayout: let mut enc = FileEncoder::new(std::fs::File::create("take.wav")?, &EncodeOptions::default(), 48_000, 2)?; enc.write(&buf.channels, buf.frames())?; // one slice (or Vec) per channel enc.finish()?; + +// The coded formats go the same way: AAC in M4A at 192 kbit/s, 5.1 as E-AC-3, 16-bit ALAC. +let m4a = encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(192_000))?; +let eac3 = encode(&surround, &EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_5_1_SIDE))?; +let alac = encode(&buf, &EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16))?; ``` `EncodeOptions::default()` is 24-bit WAV. `with_bwf` adds a BWF `bext` chunk and `with_force_rf64` writes RF64 below 4 GiB; both apply to WAV only. `encode_format_for("aiff")` -maps an extension to an `EncodeFormat`, and `ENCODE_EXTENSIONS` lists the extensions the enabled -features can write. `EncodeFormat::ALL` lists the formats; `extension()` is the extension a new -file gets and `mime_type()` its media type. `write` refuses a block without one slice per channel, or with a slice -shorter than `frames`, and writes nothing. After a write fails for another reason, every later +maps an extension to an `EncodeFormat` (`"m4a"` to AAC; `"alac"` names ALAC), and `ENCODE_EXTENSIONS` lists the extensions the enabled +features can write. `EncodeFormat::ALL` lists the formats and `is_built()` says whether this build +writes one; `extension()` is the extension a new file gets and `mime_type()` its media type. +`write` refuses a block without one slice per channel, or with a slice shorter than `frames`, and +writes nothing. After a write fails for another reason, every later `write` and `finish` returns an error. -### Encode AAC +| `EncodeFormat` | File | Audio | Options used | +|---|---|---|---| +| `Wav`, `Aiff`, `Flac` | WAV / BWF / RF64, AIFF / AIFF-C, FLAC | any rate; FLAC up to 8 channels | `bit_depth`, `dither`, `layout` (WAV, FLAC), `bwf`, `force_rf64` (WAV) | +| `Alac` | M4A | 1–8 channels, any rate | `bit_depth` (16, 24, 32), `dither`, `layout` | +| `Aac` | M4A | AAC-LC, 1–8 channels, the 13 AAC rates (7350–96000 Hz) | `rate_control`, `layout` | +| `Mp3` | `.mp3` stream | mono or stereo; 32, 44.1, 48 kHz or 16, 22.05, 24 kHz | `rate_control` (bit rate), `layout` | +| `Ac3`, `Eac3` | `.ac3` / `.eac3` stream | up to 5.1 (E-AC-3: 7.1); 32, 44.1, 48 kHz | `rate_control` (bit rate), `layout` | + +`with_bitrate(bits_per_second)` sets a constant bit rate for all channels together. A rate the +stream cannot carry is moved to the nearest one it can: MP3 and AC-3 use the highest rate of their +tables not above it, AAC and E-AC-3 keep it inside their range (AAC from 6 kbit/s or a quarter of +the sample rate per channel, whichever is more: from about half of that down the encoder codes +silence). `with_quality(0.0..=1.0)` is AAC's +constant quality (VBR); the other lossy formats return `Unsupported` for it. Without either, AAC +is written at 64 kbit/s per channel, MP3 at 96 kbit/s per channel, and AC-3 and E-AC-3 at +96 kbit/s per full-bandwidth channel (the LFE not counted). + +The audio is in WAV channel order for every format; `layout` (the usual layout for the channel +count when unset) names the speakers, and the channels are reordered into the codec's own order. +Each coded format has a fixed set of layouts, and audio with other speakers is `Unsupported` +rather than written to the wrong ones: + +- AAC: C; L R; L R C; L R C Cb; L R C Ls Rs; 5.1; 6.1; and for 8 channels L R C LFE Lb Rb Lc Rc + (a front pair left and right of centre, mask `0xFF`). ALAC: the same, with 6.1's back centre last. + WAV 7.1 (backs and sides) is not that 7.1, and quad (the usual 4-channel layout) has no centre: + both need another format. +- AC-3 and E-AC-3: the layout picks the coding mode (1/0 to 3/2, with or without LFE; E-AC-3 also + 7.1 with backs and sides). +- A surround pair is a surround pair: side and back surrounds are interchangeable where the format + has one pair. + +Before a file is created, the options and the format say what will happen: + +```rust +let opts = EncodeOptions::new(EncodeFormat::Ac3).with_layout(info.layout).with_bitrate(200_000); +opts.check(info.sample_rate, info.channels)?; // the error FileEncoder::new would return, nothing written +let bps = opts.bitrate(info.sample_rate, info.channels)?; // Some(192_000): the rate actually used; None when lossless or by quality + +EncodeFormat::Ac3.sample_rates(); // Some(&[32_000, 44_100, 48_000]); None when any rate will do +EncodeFormat::Ac3.max_channels(); // 6 +EncodeFormat::Ac3.fixed_layouts(3); // L R C, L R Cb, L R LFE; None for WAV, AIFF and FLAC (any layout) +EncodeFormat::Ac3.supports_layout(&info.layout); // one of those, sides and backs standing for each other +EncodeFormat::Ac3.supports_quality(); // false: AAC only +``` + +`FileEncoder::bitrate()` gives the rate of a file being written. The `EncodeFormat` queries answer +for a format whose feature is off too; `check` and `EncodeOptions::bitrate` (there with any +encoder feature) return `Unsupported` for it. + +The layout `decode` reports (`AudioInfo::layout`) can be passed to `with_layout` as it is. When a +coded format refuses it (2.1 or quad into AAC, a single channel tagged as left, channels with no +speaker assignment), the choices are another format, or audio rearranged into one of the layouts +above with that layout set; leaving `layout` unset declares the usual layout for the count. This +crate's decoder returns 7- and 8-channel AAC without a speaker assignment, in AAC order, so such a +file needs that step before it is written again. + +An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame +written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no +place for that (see [Limits](#limits)). For a container of your own, use the codec modules below. + +### Encode AAC packets + +For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it, +for muxing into a container of your own: ```rust use craft_audio::AudioError; @@ -343,14 +412,14 @@ match craft_audio::decode(&bytes, None) { | WAV, BWF, RF64/BW64 | native | native | | AIFF, AIFF-C | native | native | | FLAC | symphonia | native | -| AAC-LC | native | native | +| AAC-LC | native | native; M4A through `encode` / `FileEncoder`, packets through `aac::Encoder` | | HE-AAC v1 | native (SBR) | — | | HE-AAC v2 | native, without parametric stereo (see [Limits](#limits)) | — | -| ALAC | native | native, packets (`alac::Encoder`; no file writer) | +| ALAC | native | native; M4A through `encode` / `FileEncoder`, packets through `alac::Encoder` | | MP1, MP2 (MPEG audio Layer I/II) | native | — | -| MP3 (Layer III) | native | native, frames (`mp3::Encoder`; the frames in a row are an `.mp3` file) | -| Opus | native | native | -| AC-3, E-AC-3 | native | native packet encoder | +| MP3 (Layer III) | native | native; `.mp3` through `encode` / `FileEncoder`, frames through `mp3::Encoder` | +| Opus | native | native, packets (`opus::Encoder`; no file writer) | +| AC-3, E-AC-3 | native | native; `.ac3` / `.eac3` through `encode` / `FileEncoder`, packets through `ac3::encoder::Encoder` | | Vorbis, ADPCM, A-law, µ-law | symphonia | — | | Container | Demuxer | Timing | @@ -410,10 +479,26 @@ match craft_audio::decode(&bytes, None) { - `TrackDecoder` returns `Unsupported` for FLAC and Vorbis; `decode` and `Decoder` read those through symphonia. ALAC in CAF still goes through symphonia (craft-media has no CAF demuxer). -- ALAC: `EncodeFormat` has no ALAC entry; `alac::Encoder` writes packets and the configuration, - and the caller muxes them (MP4 `alac` box, Matroska `A_ALAC`). craft-media's MP4 muxer writes no - `chan` box, so an MP4 of more than two channels carries no explicit layout; decoders then use the - standard ALAC layout for the count. +- ALAC: craft-media's MP4 muxer writes no `chan` box, so an M4A of more than two channels (from + `EncodeFormat::Alac` or muxed from `alac::Encoder` packets) carries no explicit layout; decoders + then use the standard ALAC layout for the count, which is the one written. +- `EncodeFormat::Mp3`, `Ac3` and `Eac3` write raw streams, which cannot signal the codec's delay or + the length: the file decodes with 1057 (MP3) or 256 (AC-3, E-AC-3) frames of delay in front and + padded to whole frames at the end. MP3 gets no Xing / Info frame. `EncodeFormat::Aac` and `Alac` + (M4A) decode to the length written. +- An AAC M4A's length is in the edit list and the last packet's duration. This crate, Apple's + decoders and ffmpeg 9 end the audio there; ffmpeg 8 skips the priming but plays the last + packet's padding (under 1024 frames of near silence). +- `EncodeFormat::Aac` and `Alac` write the `moov` box after the audio (no fast start), and no + metadata. Raw ADTS AAC is not a file format of `encode`; `aac::EncoderConfig::with_adts` gives + the frames. +- This crate's file reader plays a raw E-AC-3 7.1 stream as its 5.1 independent substream. +- `EncodeFormat::Aac` with 8 channels is AAC channel configuration 7 (C, Lc Rc, L R, Ls Rs, LFE), + which Apple's decoders read as written. ffmpeg assumes such a stream is a mislabelled 7.1 with + backs and sides and moves the channels accordingly, unless run with `-strict 1`. +- A file with no audio: MP3, AC-3 and E-AC-3 are then zero bytes, which nothing can probe. An + empty AAC M4A (a track with no samples) is read by ffmpeg; this crate's native reader passes it + on, so `decode-native` alone refuses it and symphonia reads only some as zero frames. - ALAC 32-bit streams: ffmpeg does not decode their uncompressed (escaped) stereo frames, which Apple's encoder and this one write for audio that does not compress; Apple's decoder and this one do. @@ -481,7 +566,7 @@ finite count as silence and the rest are clamped to ±4, so no input makes an in decoder's 7680-bit input buffer. - Not yet: block switching (short blocks; transients pre-echo), `scfsi` and `preflag`, intensity stereo, a tonality-aware model, VBR/ABR, the Xing/Info and LAME gapless tags (the delay is not - signalled), CRC, free format, and an `EncodeFormat` entry for `encode`/`FileEncoder`. + signalled), CRC and free format. ### AC-3 and E-AC-3 encoding diff --git a/crates/audio/examples/encode.rs b/crates/audio/examples/encode.rs index 28de0f5adb..51cdecc840 100644 --- a/crates/audio/examples/encode.rs +++ b/crates/audio/examples/encode.rs @@ -1,4 +1,4 @@ -//! Write a tone as WAV and FLAC, whole and streamed, and as AAC packets. +//! Write a tone as WAV, FLAC and AAC in M4A, whole and streamed, and as AAC packets. //! //! `cargo run -p craft-audio --example encode --features lossless-encode,aac-encode -- out` @@ -28,7 +28,11 @@ fn main() -> Result<(), Box> { } enc.finish()?; - // AAC packets for an MP4 or Matroska muxer, with the configuration its sample entry needs. + // AAC in M4A at 160 kbit/s: the same call, with a bit rate in place of a bit depth. + let m4a = encode(&stereo, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(160_000))?; + std::fs::write(dir.join("tone.m4a"), m4a)?; + + // AAC packets for a muxer of your own, with the configuration its sample entry needs. let mut aac = craft_audio::aac::Encoder::new(craft_audio::aac::EncoderConfig::cbr(rate as u32, 2, 128_000))?; let mut units = aac.encode(&[&tone, &tone]); units.extend(aac.flush()); diff --git a/crates/audio/src/aac/encoder/mod.rs b/crates/audio/src/aac/encoder/mod.rs index 5a0ea5ac84..c641b790b8 100644 --- a/crates/audio/src/aac/encoder/mod.rs +++ b/crates/audio/src/aac/encoder/mod.rs @@ -162,6 +162,16 @@ const HISTORY: usize = 2048; /// Bits per channel in a silent frame, rounded up: the smallest frame the encoder writes. const MIN_FRAME_BITS_PER_CHANNEL: u64 = 48; +/// The lowest and highest constant bit rate (bits per second) [`Encoder::new`] accepts for a +/// stream without ADTS headers: at least 1 kbit/s per channel and a silent frame, at most the +/// 6144 bits per channel and frame of the decoder buffer. +pub(crate) fn cbr_range(sample_rate: u32, channels: usize) -> (u32, u32) { + let (rate, channels) = (u64::from(sample_rate), channels as u64); + let silent = (MIN_FRAME_BITS_PER_CHANNEL * channels * rate).div_ceil(FRAME_LEN as u64); + let most = 6144 * channels * rate / FRAME_LEN as u64; + (u32::try_from(silent.max(1000 * channels)).unwrap_or(u32::MAX), u32::try_from(most).unwrap_or(u32::MAX)) +} + /// AAC-LC encoder. pub struct Encoder { cfg: EncoderConfig, diff --git a/crates/audio/src/aac/mod.rs b/crates/audio/src/aac/mod.rs index 297aa79728..f423a4e22c 100644 --- a/crates/audio/src/aac/mod.rs +++ b/crates/audio/src/aac/mod.rs @@ -64,6 +64,8 @@ pub use config::{AdtsHeader, AudioSpecificConfig, ElementType, ProgramConfig, co #[cfg(feature = "aac-decode")] pub use decoder::Decoder; #[cfg(feature = "aac-encode")] +pub(crate) use encoder::cbr_range; +#[cfg(feature = "aac-encode")] pub use encoder::{BitrateMode, Encoder, EncoderConfig, EncoderStats}; #[cfg(feature = "aac-decode")] pub use latm::{LatmConfig, latm_config, latm_split}; diff --git a/crates/audio/src/ac3/mod.rs b/crates/audio/src/ac3/mod.rs index a8e8920d2f..6bb19df8d5 100644 --- a/crates/audio/src/ac3/mod.rs +++ b/crates/audio/src/ac3/mod.rs @@ -61,7 +61,7 @@ pub enum Error { pub type Result = std::result::Result; /// Data rate in kb/s by frmsizecod / 2 (Table 5.18). -const BITRATES: [u32; 19] = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640]; +pub(crate) const BITRATES: [u32; 19] = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640]; /// Full-bandwidth channels per acmod (Table 5.8). const NFCHANS: [usize; 8] = [2, 1, 2, 3, 3, 4, 4, 5]; diff --git a/crates/audio/src/layout.rs b/crates/audio/src/layout.rs index f3cab1b7fa..d0c5ae39e6 100644 --- a/crates/audio/src/layout.rs +++ b/crates/audio/src/layout.rs @@ -283,6 +283,40 @@ pub(crate) fn flac_assumed_mask(channels: usize) -> u32 { } } +/// The surround speaker a layout may name in place of `speaker`: formats with one surround pair +/// do not tell side from back, so a pair of either kind feeds it. +fn surround_twin(speaker: Speaker) -> Option { + Some(match speaker { + Speaker::SideLeft => Speaker::BackLeft, + Speaker::SideRight => Speaker::BackRight, + Speaker::BackLeft => Speaker::SideLeft, + Speaker::BackRight => Speaker::SideRight, + _ => return None, + }) +} + +/// How audio with `layout` feeds a format whose layout for the channel count is `mask`: for each +/// channel the format takes, the channel of the audio that feeds it. `order` is the format's +/// channel order over `mask` (for each of its channels, the WAV-order channel of `mask`; `None` +/// when it takes WAV order). `None` when `layout` is not the format's layout: it is unordered, or +/// has a speaker the format has not. +pub(crate) fn channel_map(mask: u32, order: Option<&[usize]>, layout: &ChannelLayout) -> Option> { + let speakers = ChannelLayout::from_mask(mask).speakers(); + if speakers.len() != usize::from(layout.channels()) { + return None; + } + let mut map = Vec::with_capacity(speakers.len()); + for j in 0..speakers.len() { + let speaker = *speakers.get(order.and_then(|o| o.get(j).copied()).unwrap_or(j))?; + let at = layout.index_of(speaker).or_else(|| surround_twin(speaker).and_then(|t| layout.index_of(t)))?; + if map.contains(&at) { + return None; + } + map.push(at); + } + Some(map) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index f8441a51d9..1c6c73dcfe 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -16,9 +16,10 @@ //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also -//! gives [`wav_float_header`]) and FLAC (feature `flac-encode`), whole-buffer or incremental into -//! any `Write + Seek`. Feature `lossless-encode` turns on both; feature `encode` turns on -//! `lossless-encode` and every codec's encoder. +//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A +//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, +//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature +//! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. //! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`], //! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF //! file bit for bit, and minimal files around such PCM, for essence embedded in other containers. @@ -54,7 +55,15 @@ mod read; mod track; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] mod wav; -#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] mod write; /// The FLAC packet encoder (RFC 9639), for a caller that muxes FLAC itself (into MP4, Matroska or @@ -100,7 +109,15 @@ pub use read::{RawPcm, aiff_pcm, wav_pcm}; pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; #[cfg(feature = "pcm-encode")] pub use write::wav_float_header; -#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; @@ -215,7 +232,8 @@ impl From for AudioError { } /// The file formats [`encode`] writes. Each needs its feature: WAV and AIFF `pcm-encode`, FLAC -/// `flac-encode`; asking for one that is not built returns [`AudioError::Unsupported`]. +/// `flac-encode`, AAC `aac-encode`, ALAC `alac-encode`, MP3 `mp3-encode`, AC-3 `ac3-encode` and +/// E-AC-3 `eac3-encode`; asking for one that is not built returns [`AudioError::Unsupported`]. #[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -226,20 +244,46 @@ pub enum EncodeFormat { Aiff, /// FLAC (integer depths). Flac, + /// AAC-LC in an M4A (MP4) file, 1–8 channels at one of the 13 AAC sample rates. The edit list + /// skips the encoder's priming and ends at the last frame, so the file decodes to the length + /// that was written. + Aac, + /// Apple Lossless in an M4A (MP4) file (integer depths), 1–8 channels. + Alac, + /// An MP3 stream: mono or stereo at 32, 44.1 or 48 kHz, or 16, 22.05 or 24 kHz. + Mp3, + /// An AC-3 stream: up to 5.1 at 32, 44.1 or 48 kHz. + Ac3, + /// An E-AC-3 stream: up to 7.1 at 32, 44.1 or 48 kHz. + Eac3, } impl EncodeFormat { /// Every format, in the order menus list them. Whether [`encode`] writes one depends on its - /// feature. - pub const ALL: &[EncodeFormat] = &[EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac]; + /// feature ([`EncodeFormat::is_built`]). + pub const ALL: &[EncodeFormat] = &[ + EncodeFormat::Wav, + EncodeFormat::Aiff, + EncodeFormat::Flac, + EncodeFormat::Alac, + EncodeFormat::Aac, + EncodeFormat::Mp3, + EncodeFormat::Ac3, + EncodeFormat::Eac3, + ]; /// The extension a new file of this format gets, lower case and without the dot: `"wav"`, - /// `"aif"`, `"flac"`. [`encode_format_for`] maps it back. + /// `"aif"`, `"flac"`, `"m4a"` (AAC and ALAC), `"mp3"`, `"ac3"`, `"eac3"`. + /// [`encode_format_for`] maps it back, `"m4a"` to AAC. pub fn extension(self) -> &'static str { match self { EncodeFormat::Wav => "wav", EncodeFormat::Aiff => "aif", EncodeFormat::Flac => "flac", + EncodeFormat::Aac | EncodeFormat::Alac => "m4a", + EncodeFormat::Mp3 => "mp3", + EncodeFormat::Ac3 => "ac3", + EncodeFormat::Eac3 => "eac3", } } @@ -249,6 +293,10 @@ impl EncodeFormat { EncodeFormat::Wav => "audio/wav", EncodeFormat::Aiff => "audio/aiff", EncodeFormat::Flac => "audio/flac", + EncodeFormat::Aac | EncodeFormat::Alac => "audio/mp4", + EncodeFormat::Mp3 => "audio/mpeg", + EncodeFormat::Ac3 => "audio/ac3", + EncodeFormat::Eac3 => "audio/eac3", } } @@ -258,8 +306,154 @@ impl EncodeFormat { EncodeFormat::Wav => Container::Wav, EncodeFormat::Aiff => Container::Aiff, EncodeFormat::Flac => Container::Flac, + EncodeFormat::Aac | EncodeFormat::Alac => Container::Mp4, + EncodeFormat::Mp3 => Container::MpegAudio, + EncodeFormat::Ac3 | EncodeFormat::Eac3 => Container::Ac3, } } + + /// The codec of the audio this format writes. + pub fn codec(self) -> CodecId { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => CodecId::Pcm, + EncodeFormat::Flac => CodecId::Flac, + EncodeFormat::Aac => CodecId::Aac, + EncodeFormat::Alac => CodecId::Alac, + EncodeFormat::Mp3 => CodecId::Mp3, + EncodeFormat::Ac3 => CodecId::Ac3, + EncodeFormat::Eac3 => CodecId::Eac3, + } + } + + /// The feature that builds this format's writer. + pub fn feature(self) -> &'static str { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => "pcm-encode", + EncodeFormat::Flac => "flac-encode", + EncodeFormat::Aac => "aac-encode", + EncodeFormat::Alac => "alac-encode", + EncodeFormat::Mp3 => "mp3-encode", + EncodeFormat::Ac3 => "ac3-encode", + EncodeFormat::Eac3 => "eac3-encode", + } + } + + /// Whether [`encode`] and [`FileEncoder`] write this format in this build (its + /// [`feature`](Self::feature) is on): what to filter [`EncodeFormat::ALL`] by for a menu. + pub fn is_built(self) -> bool { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => cfg!(feature = "pcm-encode"), + EncodeFormat::Flac => cfg!(feature = "flac-encode"), + EncodeFormat::Aac => cfg!(feature = "aac-encode"), + EncodeFormat::Alac => cfg!(feature = "alac-encode"), + EncodeFormat::Mp3 => cfg!(feature = "mp3-encode"), + EncodeFormat::Ac3 => cfg!(feature = "ac3-encode"), + EncodeFormat::Eac3 => cfg!(feature = "eac3-encode"), + } + } + + /// The sample rates the format takes, ascending, or `None` when it has no fixed list (WAV, + /// AIFF, FLAC and ALAC take any rate their headers can hold). + pub fn sample_rates(self) -> Option<&'static [u32]> { + match self { + EncodeFormat::Aac => Some(&[7350, 8000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 64_000, 88_200, 96_000]), + EncodeFormat::Mp3 => Some(&[16_000, 22_050, 24_000, 32_000, 44_100, 48_000]), + EncodeFormat::Ac3 | EncodeFormat::Eac3 => Some(&[32_000, 44_100, 48_000]), + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac => None, + } + } + + /// The most channels a file of this format holds. A WAV's frame size is a 16-bit field, so it + /// holds 65535 / bytes per sample: 32767 at 16 bits (the count given here), 21845 at 24 and + /// 16383 at 32; [`EncodeOptions::check`] answers for the depth chosen. + pub fn max_channels(self) -> u16 { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff => 32_767, + EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 => 8, + EncodeFormat::Ac3 => 6, + EncodeFormat::Mp3 => 2, + } + } + + /// The speaker layouts of a format that has a fixed set of them, as WAV masks, for a channel + /// count: one each for AAC, ALAC and MP3, one per coding mode for AC-3 and E-AC-3. Empty for a + /// count the format has not, and for WAV, AIFF and FLAC, which have no such set. + pub(crate) fn layout_masks(self, channels: u16) -> &'static [u32] { + let per_count: &[&[u32]] = match self { + // Channel configurations 1–6, the 6.1 program config element, and configuration 7 + // (7.1 with a front pair left and right of centre). + EncodeFormat::Aac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x607], &[0x60F], &[0x70F], &[0xFF]], + // Apple's layout tags for 1–8 channels, surrounds as back speakers. + EncodeFormat::Alac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x37], &[0x3F], &[0x13F], &[0xFF]], + EncodeFormat::Mp3 => &[&[0x4], &[0x3]], + // The coding modes 1/0 to 3/2 with and without an LFE, by channel count. + EncodeFormat::Ac3 => &[&[0x4], &[0x3, 0xC], &[0x7, 0x103, 0xB], &[0x107, 0x603, 0xF, 0x10B], &[0x607, 0x10F, 0x60B], &[0x60F]], + // The same, and 7.1 with backs and sides. + EncodeFormat::Eac3 => { + &[&[0x4], &[0x3, 0xC], &[0x7, 0x103, 0xB], &[0x107, 0x603, 0xF, 0x10B], &[0x607, 0x10F, 0x60B], &[0x60F], &[], &[0x63F]] + } + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac => &[], + }; + usize::from(channels).checked_sub(1).and_then(|i| per_count.get(i)).copied().unwrap_or_default() + } + + /// The speaker layouts a format with a fixed set of them has for `channels` channels: one for + /// AAC, ALAC and MP3, one per coding mode for AC-3 and E-AC-3; empty when the format cannot + /// hold that many channels. `None` for WAV, AIFF and FLAC, which take any layout. Audio in + /// another layout has to be rearranged into one of these before it is written. + /// + /// ``` + /// use craft_audio::{ChannelLayout, EncodeFormat}; + /// + /// assert_eq!(EncodeFormat::Aac.fixed_layouts(6), Some(vec![ChannelLayout::SURROUND_5_1_SIDE])); + /// assert_eq!(EncodeFormat::Mp3.fixed_layouts(6), Some(vec![])); + /// assert_eq!(EncodeFormat::Wav.fixed_layouts(6), None); + /// ``` + pub fn fixed_layouts(self, channels: u16) -> Option> { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac => None, + _ => Some(self.layout_masks(channels).iter().map(|&mask| ChannelLayout::from_mask(mask)).collect()), + } + } + + /// Whether the format holds audio with `layout`: for WAV, AIFF and FLAC any layout of up to + /// [`max_channels`](Self::max_channels) channels, for the others one of + /// [`fixed_layouts`](Self::fixed_layouts), where side and back surrounds stand for each other + /// in a layout with one surround pair. + pub fn supports_layout(self, layout: &ChannelLayout) -> bool { + match self { + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac => (1..=self.max_channels()).contains(&layout.channels()), + _ => self.layout_masks(layout.channels()).iter().any(|&mask| layout::channel_map(mask, None, layout).is_some()), + } + } + + /// Whether the format takes [`RateControl::Quality`]: AAC. The other lossy formats are + /// written at a constant bit rate only. + pub fn supports_quality(self) -> bool { + self == EncodeFormat::Aac + } + + /// Whether the format loses audio: AAC, MP3, AC-3 and E-AC-3. These take + /// [`EncodeOptions::rate_control`] and ignore the bit depth and dither. + pub fn is_lossy(self) -> bool { + matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3) + } +} + +/// How a lossy format spends bits ([`EncodeOptions::rate_control`]). +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum RateControl { + /// A constant bit rate in bits per second, for all channels together. A format with a fixed + /// set of rates (MP3, AC-3) uses the highest one not above it; a rate outside what the + /// stream can carry is moved to the nearest one inside. AAC is written at 6 kbit/s or a + /// quarter of the sample rate per channel at least: from about half of that down its encoder + /// codes silence. + Bitrate(u32), + /// A constant quality from 0.0 (smallest) to 1.0 (best), at whatever bit rate each frame + /// needs. AAC only; values outside the range are clamped, and NaN is an error. + Quality(f32), } /// Stored sample representation. @@ -418,9 +612,9 @@ pub enum BitDepth { pub struct EncodeOptions { /// Output file format. pub format: EncodeFormat, - /// Sample depth to write. + /// Sample depth to write (ignored by the lossy formats). pub bit_depth: BitDepth, - /// Add TPDF dither when quantizing to an integer depth. + /// Add TPDF dither when quantizing to an integer depth (ignored by the lossy formats). pub dither: bool, /// Write a BWF `bext` chunk (WAV only; ignored for other formats). pub bwf: Option, @@ -431,15 +625,27 @@ pub struct EncodeOptions { /// the count (they read 5 and 6 channels with side surrounds and 7 as 6.1 with sides, so the /// usual layouts for those counts get one; see the README's limits); AIFF has a fixed channel /// order and ignores it. It must have as many channels as the audio. + /// + /// AAC, ALAC, MP3, AC-3 and E-AC-3 store channels in their own order, so here the layout says + /// which speaker each channel of the audio (in WAV order) is, and the channels are reordered + /// to match. Each of these formats has a fixed set of layouts (AAC and ALAC one per channel + /// count, AC-3 one per coding mode); a layout outside it is [`AudioError::Unsupported`]. Side + /// and back surrounds are taken as the same pair where the format has only one. pub layout: Option, /// Write WAV in the RF64 layout even below 4 GiB (WAV only; ignored for other formats). pub force_rf64: bool, + /// The bit rate or quality of a lossy format (ignored by the others). `None` is a constant + /// 64 kbit/s per channel for AAC, 96 kbit/s per channel for MP3, and 96 kbit/s per + /// full-bandwidth channel (the LFE not counted) for AC-3 and E-AC-3, moved to the nearest rate + /// the stream can carry. + pub rate_control: Option, } impl EncodeOptions { - /// Options for `format`: 24-bit, no dither, no BWF chunk, the usual layout. + /// Options for `format`: 24-bit, no dither, no BWF chunk, the usual layout, the format's + /// default bit rate. pub fn new(format: EncodeFormat) -> Self { - Self { format, bit_depth: BitDepth::Int24, dither: false, bwf: None, layout: None, force_rf64: false } + Self { format, bit_depth: BitDepth::Int24, dither: false, bwf: None, layout: None, force_rf64: false, rate_control: None } } /// Sets `format`. @@ -477,6 +683,18 @@ impl EncodeOptions { self.force_rf64 = force_rf64; self } + + /// Sets `rate_control` to a constant bit rate in bits per second ([`RateControl::Bitrate`]). + pub fn with_bitrate(mut self, bits_per_second: u32) -> Self { + self.rate_control = Some(RateControl::Bitrate(bits_per_second)); + self + } + + /// Sets `rate_control` to a constant quality from 0.0 to 1.0 ([`RateControl::Quality`]). + pub fn with_quality(mut self, quality: f32) -> Self { + self.rate_control = Some(RateControl::Quality(quality)); + self + } } impl Default for EncodeOptions { diff --git a/crates/audio/src/write/coded.rs b/crates/audio/src/write/coded.rs new file mode 100644 index 0000000000..0d0dd626f4 --- /dev/null +++ b/crates/audio/src/write/coded.rs @@ -0,0 +1,506 @@ +//! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through +//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's +//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the +//! encoder's priming and the exact length in the edit list. + +// Each codec is its own feature, and so are the two sinks: with only some of them built, the +// other halves of the shared code are unused. +#![cfg_attr( + not(all(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode")), + allow(dead_code, unused_imports, unused_variables) +)] + +use super::failed_write_error; +use super::pcm::validate_layout; +use crate::layout::channel_map; +use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result}; +use std::io::{Cursor, Seek, Write}; + +/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written +/// stay small however long a block is. Also the frames of an ALAC packet. +const CHUNK: usize = 4096; + +/// Bits per second per channel when no rate is asked for: AAC. +const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per +/// full-bandwidth channel). +const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; + +/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. +fn labels(mask: u32) -> String { + ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") +} + +/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]), +/// or why the audio does not fit. +fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result> { + let Some(&mask) = format.layout_masks(layout.channels()).first() else { + return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); + }; + channel_map(mask, order, layout).ok_or_else(|| { + AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) + }) +} + +/// The speakers of the caller's layout, for an error message. +fn given(layout: &ChannelLayout) -> String { + layout.mask().map_or_else(|| "without speaker assignment".into(), labels) +} + +/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels +/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. +#[cfg(feature = "aac-encode")] +fn aac_order(channels: usize) -> Option<&'static [usize]> { + if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } +} + +/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample +/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes +/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s). +#[cfg(feature = "aac-encode")] +fn aac_floor_per_channel(sample_rate: u32) -> u32 { + (sample_rate / 4).max(6000) +} + +/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a +/// quality of 0–1 spans the encoder's VBR range. +#[cfg(feature = "aac-encode")] +fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { + use crate::aac::BitrateMode; + let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); + let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); + // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. + let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; + match rate { + None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), + Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), + // NaN stays NaN, which the encoder refuses. + Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), + } +} + +/// The bit rate in kbit/s for a codec with constant bit rates only. +fn constant_kbps(name: &str, rate: Option, default: u32) -> Result { + match rate { + None => Ok(default), + Some(RateControl::Bitrate(bps)) => Ok(bps / 1000), + Some(RateControl::Quality(_)) => { + Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) + } + } +} + +/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding +/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. +#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] +fn ac3_config( + codec: crate::ac3::encoder::Codec, + sample_rate: u32, + layout: &ChannelLayout, + rate: Option, +) -> Result<(crate::ac3::encoder::Config, Vec)> { + use crate::ac3::encoder::{Codec, CodingMode, Config}; + use CodingMode::*; + let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; + let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; + let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { + // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. + if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { + return None; + } + let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; + let map = channel_map(config.channel_layout().mask()?, None, layout)?; + Some((config, map)) + }); + let Some((mut config, map)) = found else { + return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); + }; + let full = config.mode.channels() as u32; + let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?; + // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of + // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. + let least = if config.mode == Surround71 { 384 } else { 32 * full }; + config.bitrate_kbps = match codec { + Codec::Ac3 => { + let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); + crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) + } + Codec::Eac3 => { + let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; + want.clamp(least, most.max(least)) + } + }; + Ok((config, map)) +} + +/// One encoded packet and the frames it decodes to. +struct Packet { + data: Vec, + frames: u32, +} + +/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order. +enum Codec { + #[cfg(feature = "aac-encode")] + Aac(Box), + #[cfg(feature = "alac-encode")] + Alac { + enc: Box, + quantizers: Vec, + /// Quantized samples of the packet being filled, per channel. + pending: Vec>, + }, + #[cfg(feature = "mp3-encode")] + Mp3(Box), + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Ac3 { + enc: Box, + /// The block with every sample finite and within ±1, as the encoder requires. + planes: Vec>, + }, +} + +impl Codec { + /// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames) + /// and appends the packets completed. + fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { + match self { + #[cfg(feature = "aac-encode")] + Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), + #[cfg(feature = "alac-encode")] + Codec::Alac { enc, quantizers, pending } => { + let frames = planes.first().map_or(0, |p| p.len()); + let mut at = 0; + while at < frames { + let filled = pending.first().map_or(0, Vec::len); + let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); + for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { + dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); + } + at = end; + if pending.first().is_some_and(|p| p.len() >= CHUNK) { + alac_packet(enc, pending, out)?; + } + } + } + #[cfg(feature = "mp3-encode")] + Codec::Mp3(enc) => { + let data = enc.encode(planes); + if !data.is_empty() { + out.push(Packet { data, frames: 0 }); + } + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Codec::Ac3 { enc, planes: clean } => { + for (dst, src) in clean.iter_mut().zip(planes) { + dst.clear(); + dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); + } + let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); + out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples })); + } + } + Ok(()) + } + + /// Encodes what the encoder still holds and appends the last packets. + fn finish(&mut self, out: &mut Vec) -> Result<()> { + match self { + #[cfg(feature = "aac-encode")] + Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), + #[cfg(feature = "alac-encode")] + Codec::Alac { enc, pending, .. } => { + if pending.first().is_some_and(|p| !p.is_empty()) { + alac_packet(enc, pending, out)?; + } + } + #[cfg(feature = "mp3-encode")] + Codec::Mp3(enc) => { + let data = enc.flush(); + if !data.is_empty() { + out.push(Packet { data, frames: 0 }); + } + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })), + } + Ok(()) + } + + /// Decoded frames before the first frame of the audio. + fn priming(&self) -> u32 { + match self { + #[cfg(feature = "aac-encode")] + Codec::Aac(enc) => enc.priming_samples(), + #[allow(unreachable_patterns)] + _ => 0, + } + } + + /// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` + /// frames in all): the configuration a decoder needs, with the average bit rate. + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option { + use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; + match self { + #[cfg(feature = "aac-encode")] + Codec::Aac(enc) => { + let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate); + if let CodecConfig::Aac(config) = &mut entry.codec + && frames > 0 + { + let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames); + config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); + } + Some(entry) + } + #[cfg(feature = "alac-encode")] + Codec::Alac { enc, .. } => { + let bits = u16::from(enc.encoder_config().bit_depth); + Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits)) + } + #[allow(unreachable_patterns)] + _ => None, + } + } +} + +/// Encodes the pending samples as one ALAC packet and empties them. +#[cfg(feature = "alac-encode")] +fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], out: &mut Vec) -> Result<()> { + let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); + let frames = refs.first().map_or(0, |p| p.len()) as u32; + let data = enc.encode(&refs)?; + pending.iter_mut().for_each(Vec::clear); + out.push(Packet { data, frames }); + Ok(()) +} + +/// A muxer's error as this crate's: a failed write stays an I/O error. +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +fn mux_error(e: craft_media::isobmff::Error) -> AudioError { + match e { + craft_media::isobmff::Error::Io(e) => AudioError::Io(e), + e => AudioError::Encode(format!("M4A: {e}")), + } +} + +/// An M4A file being written: one audio track whose samples are the packets. +/// +/// The last packet is held back until the length is known: its duration is cut to the audio's +/// last frame, so the sample durations add up to the priming plus the audio, and the edit that +/// skips the priming ends where the audio does. The movie timescale is the sample rate, which +/// keeps that edit exact. +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +struct M4a { + mux: craft_media::isobmff::Mp4Writer, + /// The track, added with the first packet: a file with no audio gets a track without an edit. + track: Option, + entry: craft_media::isobmff::SampleEntry, + sample_rate: u32, + channels: u32, + priming: u32, + held: Option, + /// Frames and bytes of the packets written, the held one not counted. + frames: u64, + bytes: u64, +} + +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +impl M4a { + fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result { + use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions}; + let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let mut options = WriterOptions::new(Brand::Mp4); + options.movie_timescale = sample_rate; + let mux = Mp4Writer::new(out, options).map_err(mux_error)?; + Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 }) + } + + fn track(&mut self, has_audio: bool) -> Result { + if let Some(track) = self.track { + return Ok(track); + } + let mut config = craft_media::isobmff::TrackConfig::new(self.entry.clone(), self.sample_rate); + if has_audio && self.priming > 0 { + config.media_start = Some(i64::from(self.priming)); + // AAC's overlap: a packet decodes right only after the one before it. Apple's + // decoders take the priming from the edit only when the track says so. + config.roll_distance = Some(-1); + } + let track = self.mux.add_track(config).map_err(mux_error)?; + self.track = Some(track); + Ok(track) + } + + fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> { + let track = self.track(true)?; + let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true }; + self.mux.write_sample(track, sample).map_err(mux_error)?; + self.frames += u64::from(duration); + self.bytes += packet.data.len() as u64; + Ok(()) + } + + fn write(&mut self, packet: Packet) -> Result<()> { + if let Some(held) = self.held.replace(packet) { + self.sample(&held, held.frames)?; + } + Ok(()) + } + + /// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`. + fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result { + if let Some(held) = self.held.take() { + let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames); + self.sample(&held, rest.min(u64::from(held.frames)) as u32)?; + } + let track = self.track(false)?; + // The configuration is complete only now: the bit rate, and ALAC's largest packet. + if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) { + self.mux.set_sample_entry(track, entry).map_err(mux_error)?; + } + self.mux.finish().map_err(mux_error) + } +} + +/// Where the packets go. +enum Sink { + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + M4a(Box>), + /// The packets in a row are the file. + Raw(W), +} + +/// A file of one of the coded formats written block by block. +pub(crate) struct Writer { + codec: Codec, + sink: Sink, + /// For each encoder channel, the caller's channel that feeds it. + map: Vec, + /// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for + /// AAC at a constant quality. + bitrate: Option, + frames: u64, + packets: Vec, + /// Set when a write has failed: the encoder and the sink no longer agree, so the writer + /// refuses every later call. + failed: bool, +} + +impl Writer { + pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result { + validate_layout(channels, sample_rate)?; + let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16)); + let (codec, map, bitrate) = match opts.format { + #[cfg(feature = "aac-encode")] + EncodeFormat::Aac => { + let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?; + let mode = aac_mode(opts.rate_control, sample_rate, channels); + let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) }; + let bitrate = match mode { + crate::aac::BitrateMode::Cbr(bps) => Some(bps), + crate::aac::BitrateMode::Vbr(_) => None, + }; + (Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate) + } + #[cfg(feature = "alac-encode")] + EncodeFormat::Alac => { + let count = u8::try_from(channels).unwrap_or(u8::MAX); + let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?; + let bits = match opts.bit_depth { + crate::BitDepth::Int16 => 16, + crate::BitDepth::Int24 => 24, + crate::BitDepth::Int32 => 32, + crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), + }; + let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?; + let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels); + (Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None) + } + #[cfg(feature = "mp3-encode")] + EncodeFormat::Mp3 => { + let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?; + let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?; + // A sample rate MP3 has not is the encoder's to refuse. + let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); + let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?; + (Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000))) + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + EncodeFormat::Ac3 | EncodeFormat::Eac3 => { + let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; + let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?; + let enc = crate::ac3::encoder::Encoder::new(config)?; + (Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000))) + } + #[allow(unreachable_patterns)] + f => return Err(AudioError::Unsupported(format!("writing {f:?}"))), + }; + let sink = match opts.format { + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)), + _ => Sink::Raw(out), + }; + Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false }) + } + + pub(crate) fn bitrate(&self) -> Option { + self.bitrate + } + + /// Hands the packets waiting to the sink. + fn drain(&mut self) -> Result<()> { + for packet in self.packets.drain(..) { + match &mut self.sink { + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + Sink::M4a(m4a) => m4a.write(packet)?, + Sink::Raw(out) => out.write_all(&packet.data)?, + } + } + Ok(()) + } + + /// Appends `frames` frames of `block`, which holds every channel at least that long. + pub(crate) fn write>(&mut self, block: &[C], frames: usize) -> Result<()> { + if self.failed { + return Err(failed_write_error()); + } + for at in (0..frames).step_by(CHUNK) { + let end = frames.min(at + CHUNK); + let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); + let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain()); + if let Err(e) = written { + self.failed = true; + return Err(e); + } + } + self.frames = self.frames.saturating_add(frames as u64); + Ok(()) + } + + pub(crate) fn finish(mut self) -> Result { + if self.failed { + return Err(failed_write_error()); + } + self.codec.finish(&mut self.packets)?; + self.drain()?; + match self.sink { + #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] + Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames), + Sink::Raw(mut out) => { + out.flush()?; + Ok(out) + } + } + } +} + +pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { + let mut w = Writer::new(Cursor::new(Vec::new()), opts, buf.sample_rate, buf.channels.len())?; + w.write(&buf.channels, buf.frames())?; + Ok(w.finish()?.into_inner()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/write/coded/tests.rs b/crates/audio/src/write/coded/tests.rs new file mode 100644 index 0000000000..cbdbd3375b --- /dev/null +++ b/crates/audio/src/write/coded/tests.rs @@ -0,0 +1,167 @@ +use super::*; + +use crate::Speaker; + +fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option> { + channel_map(mask, order, &ChannelLayout::from_mask(layout)) +} + +/// Channels are matched by speaker, not by position: a layout that lists the same speakers in +/// another WAV order is reordered, and one with other speakers is refused. +#[test] +fn channels_are_mapped_by_speaker() { + // L R C LFE Ls Rs onto itself, and onto an encoder order C L R Ls Rs LFE. + assert_eq!(map(0x60F, None, 0x60F), Some(vec![0, 1, 2, 3, 4, 5])); + assert_eq!(map(0x60F, Some(&[2, 0, 1, 4, 5, 3]), 0x60F), Some(vec![2, 0, 1, 4, 5, 3])); + // Back surrounds feed a format that has one surround pair, and the other way round. + assert_eq!(map(0x60F, None, 0x3F), Some(vec![0, 1, 2, 3, 4, 5])); + assert_eq!(map(0x3F, None, 0x60F), Some(vec![0, 1, 2, 3, 4, 5])); + // 6.1 with the back centre after the pair (L R C LFE Lb Rb Cb) onto L R C LFE Cb Ls Rs. + assert_eq!(map(0x70F, None, 0x13F), Some(vec![0, 1, 2, 3, 6, 4, 5])); + // Quad has no centre; 7.1 with sides and backs has no front pair left and right of centre. + assert_eq!(map(0x107, None, 0x33), None); + assert_eq!(map(0xFF, None, 0x63F), None); + // With both pairs in the format, one pair cannot feed both. + assert_eq!(map(0x63F, None, 0xFF), None); + assert_eq!(channel_map(0x3, None, &ChannelLayout::unordered(2)), None); + assert_eq!(map(0x3, None, 0x7), None); +} + +#[cfg(feature = "aac-encode")] +#[test] +fn every_aac_channel_count_has_a_layout_and_an_order() { + for channels in 1..=8 { + let mask = EncodeFormat::Aac.layout_masks(channels as u16)[0]; + assert_eq!(mask.count_ones() as usize, channels); + let mut order = map(mask, aac_order(channels), mask).unwrap(); + order.sort_unstable(); + assert_eq!(order, (0..channels).collect::>()); + } + assert!(EncodeFormat::Aac.layout_masks(9).is_empty() && EncodeFormat::Aac.layout_masks(0).is_empty()); + // The layouts this crate's decoder reports for what the encoder writes (`track::aac_layout`), + // and configuration 7's speakers for 8 channels. + let masks: Vec = (1..=8).map(|channels| EncodeFormat::Aac.layout_masks(channels)[0]).collect(); + assert_eq!(masks, [0x4, 0x3, 0x7, 0x107, 0x607, 0x60F, 0x70F, 0xFF]); + assert_eq!( + (EncodeFormat::Mp3.layout_masks(1), EncodeFormat::Mp3.layout_masks(2), EncodeFormat::Mp3.layout_masks(3)), + (&[0x4][..], &[0x3][..], &[][..]) + ); + // Configuration 7: C, Lc Rc, L R, Ls Rs, LFE. + let wide: Vec = ChannelLayout::from_mask(0xFF).speakers(); + let named: Vec = aac_order(8).unwrap().iter().map(|&c| wide[c]).collect(); + use Speaker::*; + assert_eq!(named, [FrontCenter, FrontLeftOfCenter, FrontRightOfCenter, FrontLeft, FrontRight, BackLeft, BackRight, Lfe]); +} + +/// The range the writer keeps a bit rate in is the one the encoder accepts. +#[cfg(feature = "aac-encode")] +#[test] +fn the_aac_bit_rate_range_is_the_encoders() { + use crate::aac::{Encoder, EncoderConfig, SAMPLE_RATES}; + for &rate in &SAMPLE_RATES { + for channels in 1..=8 { + let (lo, hi) = crate::aac::cbr_range(rate, channels); + assert!(lo <= hi, "{rate} Hz, {channels} channels"); + let accepts = |bps| Encoder::new(EncoderConfig::cbr(rate, channels, bps)).is_ok(); + assert!(accepts(lo) && accepts(hi), "{rate} Hz, {channels} channels: {lo}..={hi}"); + assert!(!accepts(lo - 1) && !accepts(hi + 1), "{rate} Hz, {channels} channels: {lo}..={hi}"); + for want in [None, Some(RateControl::Bitrate(0)), Some(RateControl::Bitrate(u32::MAX))] { + let mode = aac_mode(want, rate, channels); + assert!( + Encoder::new(EncoderConfig { mode, ..EncoderConfig::cbr(rate, channels, 0) }).is_ok(), + "{rate} Hz, {channels} channels, {want:?}" + ); + } + } + } +} + +/// Every layout the AC-3 encoders have is found from its speakers, at a bit rate the encoder +/// accepts whatever rate was asked for. +#[cfg(all(feature = "ac3-encode", feature = "eac3-encode"))] +#[test] +fn ac3_settings_follow_the_layout_and_validate() { + use crate::ac3::encoder::{Codec, CodingMode}; + let layouts = [ + (0x4, CodingMode::Mono, false), + (0x3, CodingMode::Stereo, false), + (0xB, CodingMode::Stereo, true), + (0x7, CodingMode::ThreeFront, false), + (0x103, CodingMode::StereoSurround, false), + (0x107, CodingMode::ThreeFrontSurround, false), + (0x33, CodingMode::StereoTwoSurround, false), + (0x603, CodingMode::StereoTwoSurround, false), + (0x37, CodingMode::ThreeFrontTwoSurround, false), + (0x3F, CodingMode::ThreeFrontTwoSurround, true), + (0x60F, CodingMode::ThreeFrontTwoSurround, true), + ]; + for codec in [Codec::Ac3, Codec::Eac3] { + for sample_rate in [32_000, 44_100, 48_000] { + for (mask, mode, lfe) in layouts { + for want in [None, Some(RateControl::Bitrate(0)), Some(RateControl::Bitrate(200_000)), Some(RateControl::Bitrate(u32::MAX))] { + let layout = ChannelLayout::from_mask(mask); + let (config, map) = ac3_config(codec, sample_rate, &layout, want).unwrap(); + assert_eq!((config.mode, config.lfe), (mode, lfe), "{mask:#x}"); + assert_eq!(map, (0..usize::from(layout.channels())).collect::>()); + assert_eq!(config.validate(), Ok(()), "{codec:?} {sample_rate} {mask:#x} {want:?}: {} kbit/s", config.bitrate_kbps); + } + } + let seven_one = ac3_config(codec, sample_rate, &ChannelLayout::SURROUND_7_1, Some(RateControl::Bitrate(u32::MAX))); + match codec { + Codec::Ac3 => assert!(matches!(seven_one, Err(AudioError::Unsupported(_)))), + Codec::Eac3 => assert_eq!(seven_one.unwrap().0.validate(), Ok(())), + } + } + } + // The highest table rate not above the one asked for; the default is 96 kbit/s per channel. + let rate = |codec, mask, want| ac3_config(codec, 48_000, &ChannelLayout::from_mask(mask), want).unwrap().0.bitrate_kbps; + assert_eq!(rate(Codec::Ac3, 0x3, Some(RateControl::Bitrate(200_000))), 192); + assert_eq!(rate(Codec::Ac3, 0x3, None), 192); + assert_eq!(rate(Codec::Ac3, 0x60F, None), 448); + assert_eq!(rate(Codec::Ac3, 0x60F, Some(RateControl::Bitrate(1))), 160); + assert_eq!(rate(Codec::Eac3, 0x3, Some(RateControl::Bitrate(200_500))), 200); + assert!(matches!(ac3_config(Codec::Ac3, 48_000, &ChannelLayout::STEREO, Some(RateControl::Quality(0.5))), Err(AudioError::Unsupported(_)))); + assert!(matches!(ac3_config(Codec::Ac3, 48_000, &ChannelLayout::unordered(2), None), Err(AudioError::Unsupported(_)))); +} + +/// The layouts `EncodeFormat` lists are the encoders' own: ALAC's layout per channel count, and +/// the speakers of every AC-3 and E-AC-3 coding mode the encoder has. +#[cfg(all(feature = "alac-encode", feature = "ac3-encode", feature = "eac3-encode"))] +#[test] +fn the_listed_layouts_are_the_encoders() { + use crate::ac3::encoder::{Codec, CodingMode::*, Config}; + for channels in 0..=10u16 { + let alac = crate::alac::channel_mask(channels as u8); + assert_eq!(EncodeFormat::Alac.layout_masks(channels), if alac == 0 { &[][..] } else { std::slice::from_ref(&alac) }, "ALAC, {channels}"); + for (format, codec) in [(EncodeFormat::Ac3, Codec::Ac3), (EncodeFormat::Eac3, Codec::Eac3)] { + let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; + let mut encoder: Vec = modes + .iter() + .flat_map(|&mode| [false, true].map(|lfe| Config { codec, sample_rate: 48_000, bitrate_kbps: 640, mode, lfe })) + .filter(|config| config.validate().is_ok() && config.channels() == usize::from(channels)) + .filter_map(|config| config.channel_layout().mask()) + .collect(); + let mut listed = format.layout_masks(channels).to_vec(); + encoder.sort_unstable(); + listed.sort_unstable(); + assert_eq!(listed, encoder, "{format:?}, {channels} channels"); + for &mask in &listed { + let layout = ChannelLayout::from_mask(mask); + assert_eq!(ac3_config(codec, 48_000, &layout, None).unwrap().0.channel_layout(), layout); + } + } + } +} + +/// The sample rates `EncodeFormat` lists are the encoders'. +#[cfg(all(feature = "aac-encode", feature = "mp3-encode"))] +#[test] +fn the_listed_sample_rates_are_the_encoders() { + let sorted = |rates: &[u32]| { + let mut rates = rates.to_vec(); + rates.sort_unstable(); + rates + }; + assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES)); + assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES)); +} diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 2355a7b055..0de55c394b 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -1,8 +1,11 @@ -//! Encoding: WAV/BWF/RF64 and AIFF/AIFF-C writers (`pcm-encode`) and the FLAC encoder -//! (`flac-encode`), whole-buffer and streaming. +//! Encoding: WAV/BWF/RF64 and AIFF/AIFF-C writers (`pcm-encode`), the FLAC encoder +//! (`flac-encode`) and the coded formats (AAC and ALAC in M4A, MP3, AC-3 and E-AC-3 streams, each +//! with its codec's feature), whole-buffer and streaming. #[cfg(feature = "pcm-encode")] mod aiff; +#[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] +mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; mod pcm; @@ -16,9 +19,14 @@ use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, pub use raw::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; use std::io::{Seek, Write}; -/// Encode `buf` as WAV/BWF, AIFF/AIFF-C or FLAC. Integer depths clamp samples to [-1, 1]; float +/// Encode `buf` as the file `opts.format` names. Integer depths clamp samples to [-1, 1]; float /// keeps values above full scale. `opts.layout`, when set, must have `buf`'s channel count. /// +/// The lossy formats take `opts.rate_control`. AAC and ALAC are written as M4A, which records the +/// encoder's priming and the exact length, so the file decodes to `buf`'s frames. MP3, AC-3 and +/// E-AC-3 are raw streams, which have no place for that: they decode with the codec's delay in +/// front and padded to whole frames. +/// /// ``` /// # #[cfg(feature = "pcm-encode")] { /// use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, encode}; @@ -32,6 +40,7 @@ use std::io::{Seek, Write}; pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { check_built(opts.format)?; // Checked for every format; WAV and FLAC record it. + #[cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(unused_variables))] let mask = opts.layout.map(|l| wav_mask(&l, buf.channels.len())).transpose()?; match opts.format { #[cfg(feature = "pcm-encode")] @@ -40,6 +49,8 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { EncodeFormat::Aiff => aiff::encode(buf, opts.bit_depth, opts.dither), #[cfg(feature = "flac-encode")] EncodeFormat::Flac => flac::encode(buf, opts.bit_depth, opts.dither, mask), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 => coded::encode(buf, opts), #[allow(unreachable_patterns)] f => Err(AudioError::Unsupported(format!("writing {f:?}"))), } @@ -47,31 +58,48 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { /// Refuses a format whose writer is not built, before anything else about the request is checked. fn check_built(format: EncodeFormat) -> Result<()> { - let (built, feature) = - if format == EncodeFormat::Flac { (cfg!(feature = "flac-encode"), "flac-encode") } else { (cfg!(feature = "pcm-encode"), "pcm-encode") }; - if built { Ok(()) } else { Err(AudioError::Unsupported(format!("writing {format:?} needs the `{feature}` feature"))) } + if format.is_built() { Ok(()) } else { Err(AudioError::Unsupported(format!("writing {format:?} needs the `{}` feature", format.feature()))) } } -/// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "pcm-encode", feature = "flac-encode"))] -pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc", "flac"]; -/// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "pcm-encode", not(feature = "flac-encode")))] -pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc"]; -/// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "flac-encode", not(feature = "pcm-encode")))] -pub const ENCODE_EXTENSIONS: &[&str] = &["flac"]; +/// Every extension [`ENCODE_EXTENSIONS`] can list, and how many of them the features built give. +const fn extensions() -> ([&'static str; 12], usize) { + let mut all = [""; 12]; + let mut n = 0; + macro_rules! add { + ($built:expr, $($extension:literal),+) => { + if $built { + $( + all[n] = $extension; + n += 1; + )+ + } + }; + } + add!(cfg!(feature = "pcm-encode"), "wav", "wave", "bwf", "aif", "aiff", "aifc"); + add!(cfg!(feature = "flac-encode"), "flac"); + add!(cfg!(any(feature = "aac-encode", feature = "alac-encode")), "m4a"); + add!(cfg!(feature = "mp3-encode"), "mp3"); + add!(cfg!(feature = "ac3-encode"), "ac3"); + add!(cfg!(feature = "eac3-encode"), "eac3", "ec3"); + (all, n) +} -/// The format [`encode`] writes for a file extension or format name (`wav`, `aiff`, `flac`, -/// case-insensitive, with or without the dot), or `None` when it cannot write it. `aifc` is -/// AIFF: float AIFF is written as AIFF-C. +const EXTENSIONS: ([&str; 12], usize) = extensions(); + +/// The file extensions of the formats [`encode`] can write (those whose features are on). +pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; + +/// The format [`encode`] writes for a file extension or format name (`wav`, `aiff`, `flac`, `m4a`, +/// `mp3`, `ac3`, `eac3`, case-insensitive, with or without the dot), or `None` when it cannot +/// write it. `aifc` is AIFF: float AIFF is written as AIFF-C. `m4a` is AAC when the AAC encoder +/// is built and ALAC otherwise; `alac` always names ALAC. /// /// ``` /// # #[cfg(feature = "pcm-encode")] { /// use craft_audio::{EncodeFormat, encode_format_for}; /// /// assert_eq!(encode_format_for(".AIFF"), Some(EncodeFormat::Aiff)); -/// assert_eq!(encode_format_for("mp3"), None); +/// assert_eq!(encode_format_for("ogg"), None); /// # } /// ``` pub fn encode_format_for(name: &str) -> Option { @@ -82,6 +110,18 @@ pub fn encode_format_for(name: &str) -> Option { "aif" | "aiff" | "aifc" => Some(EncodeFormat::Aiff), #[cfg(feature = "flac-encode")] "flac" => Some(EncodeFormat::Flac), + #[cfg(feature = "aac-encode")] + "m4a" => Some(EncodeFormat::Aac), + #[cfg(all(feature = "alac-encode", not(feature = "aac-encode")))] + "m4a" => Some(EncodeFormat::Alac), + #[cfg(feature = "alac-encode")] + "alac" => Some(EncodeFormat::Alac), + #[cfg(feature = "mp3-encode")] + "mp3" => Some(EncodeFormat::Mp3), + #[cfg(feature = "ac3-encode")] + "ac3" => Some(EncodeFormat::Ac3), + #[cfg(feature = "eac3-encode")] + "eac3" | "ec3" => Some(EncodeFormat::Eac3), _ => None, } } @@ -102,11 +142,11 @@ fn failed_write_error() -> AudioError { AudioError::Encode("the stream encoder already failed on an earlier write; its output is incomplete".into()) } -/// Writes WAV/BWF (RF64 above 4 GiB), AIFF / AIFF-C `fl32` or FLAC block by block, producing -/// the same bytes [`encode`] would for the whole buffer: a file of any length never -/// has to fit in memory. The file starts at the sink's position, and nothing may follow that -/// position (a new file, or one truncated there): the encoder cannot truncate a `Write + Seek`, -/// so the bytes of a longer file already there would stay after the new one. +/// Writes a file of any [`EncodeFormat`] block by block, producing the same bytes [`encode`] +/// would for the whole buffer: a file of any length never has to fit in memory. The file starts +/// at the sink's position, and nothing may follow that position (a new file, or one truncated +/// there): the encoder cannot truncate a `Write + Seek`, so the bytes of a longer file already +/// there would stay after the new one. /// /// ``` /// # #[cfg(feature = "flac-encode")] { @@ -125,30 +165,27 @@ fn failed_write_error() -> AudioError { /// ``` pub struct FileEncoder { writer: Writer, + format: EncodeFormat, channels: usize, } impl std::fmt::Debug for FileEncoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let format = match &self.writer { - #[cfg(feature = "pcm-encode")] - Writer::Wav(_) => EncodeFormat::Wav, - #[cfg(feature = "pcm-encode")] - Writer::Aiff(_) => EncodeFormat::Aiff, - #[cfg(feature = "flac-encode")] - Writer::Flac(_) => EncodeFormat::Flac, - }; - f.debug_struct("FileEncoder").field("format", &format).finish_non_exhaustive() + f.debug_struct("FileEncoder").field("format", &self.format).finish_non_exhaustive() } } -enum Writer { +// The writers differ in size with the features built; the coded one is boxed for its encoder. +#[allow(clippy::large_enum_variant)] +enum Writer { #[cfg(feature = "pcm-encode")] Wav(wav::Writer), #[cfg(feature = "pcm-encode")] Aiff(aiff::Writer), #[cfg(feature = "flac-encode")] Flac(flac::Writer), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Coded(Box>), } impl FileEncoder { @@ -156,7 +193,10 @@ impl FileEncoder { /// `opts.layout`, when set, must have `channels` channels. pub fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result { check_built(opts.format)?; - let (depth, dither, channels) = (opts.bit_depth, opts.dither, usize::from(channels)); + let channels = usize::from(channels); + #[cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(unused_variables))] + let (depth, dither) = (opts.bit_depth, opts.dither); + #[cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(unused_variables))] let mask = opts.layout.map(|l| wav_mask(&l, channels)).transpose()?; let writer = match opts.format { #[cfg(feature = "pcm-encode")] @@ -172,24 +212,45 @@ impl FileEncoder { EncodeFormat::Aiff => Writer::Aiff(aiff::Writer::new(out, channels, sample_rate, depth, dither)?), #[cfg(feature = "flac-encode")] EncodeFormat::Flac => Writer::Flac(flac::Writer::new(out, channels, sample_rate, depth, dither, mask)?), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 => { + Writer::Coded(Box::new(coded::Writer::new(out, opts, sample_rate, channels)?)) + } #[allow(unreachable_patterns)] f => return Err(AudioError::Unsupported(format!("writing {f:?}"))), }; - Ok(FileEncoder { writer, channels }) + Ok(FileEncoder { writer, format: opts.format, channels }) + } + + /// The constant bit rate the file is written at, in bits per second for all channels + /// together: the rate asked for or the format's default, moved to one the stream + /// can carry as [`RateControl::Bitrate`](crate::RateControl::Bitrate) describes. `None` for the lossless + /// formats and for AAC at a constant quality. + pub fn bitrate(&self) -> Option { + match &self.writer { + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(w) => w.bitrate(), + #[allow(unreachable_patterns)] + _ => None, + } } /// Fails, without writing anything, when `frames` more frames would not fit the format (an - /// AIFF holds 4 GiB, a FLAC 2^36 - 1 frames). + /// AIFF holds 4 GiB, a FLAC 2^36 - 1 frames). The coded formats have no limit a file reaches. pub fn check_room(&self, frames: u64) -> Result<()> { match &self.writer { #[cfg(feature = "pcm-encode")] - Writer::Wav(w) => w.check_room(frames), + Writer::Wav(w) => w.check_room(frames).map(drop), #[cfg(feature = "pcm-encode")] - Writer::Aiff(w) => w.check_room(frames), + Writer::Aiff(w) => w.check_room(frames).map(drop), #[cfg(feature = "flac-encode")] - Writer::Flac(w) => w.check_room(frames), + Writer::Flac(w) => w.check_room(frames).map(drop), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(_) => { + let _ = frames; + Ok(()) + } } - .map(drop) } /// Appends the first `frames` frames of `block`, one slice per channel (`&[Vec]`, @@ -212,10 +273,13 @@ impl FileEncoder { Writer::Aiff(w) => w.write(block, frames), #[cfg(feature = "flac-encode")] Writer::Flac(w) => w.write(block, frames), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(w) => w.write(block, frames), } } - /// Completes the headers and hands back `out`, positioned at the end of the file. + /// Encodes what is still buffered, completes the headers and hands back `out`, positioned at + /// the end of the file. pub fn finish(self) -> Result { match self.writer { #[cfg(feature = "pcm-encode")] @@ -224,10 +288,41 @@ impl FileEncoder { Writer::Aiff(w) => w.finish(), #[cfg(feature = "flac-encode")] Writer::Flac(w) => w.finish(), + #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] + Writer::Coded(w) => w.finish(), } } } +impl EncodeOptions { + /// Whether a file of `channels` channels at `sample_rate` can be written with these options: + /// `Ok`, or the error [`FileEncoder::new`] and [`encode`] would return, with nothing written. + /// For choosing a format before a file is created; [`EncodeFormat::sample_rates`], + /// [`EncodeFormat::max_channels`] and [`EncodeFormat::supports_layout`] say what a format takes. + /// + /// ``` + /// # #[cfg(feature = "mp3-encode")] { + /// use craft_audio::{EncodeFormat, EncodeOptions}; + /// + /// let mp3 = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(200_000); + /// assert!(mp3.check(48_000, 2).is_ok()); + /// assert!(mp3.check(96_000, 2).is_err()); // not an MP3 sample rate + /// assert_eq!(mp3.bitrate(48_000, 2).unwrap(), Some(192_000)); // the table rate below 200 kbit/s + /// # } + /// ``` + pub fn check(&self, sample_rate: u32, channels: u16) -> Result<()> { + self.bitrate(sample_rate, channels).map(drop) + } + + /// The constant bit rate such a file would be written at ([`FileEncoder::bitrate`]), or the + /// error [`EncodeOptions::check`] returns. + pub fn bitrate(&self, sample_rate: u32, channels: u16) -> Result> { + // The encoder a file would get, on a sink that is thrown away: what it accepts and the + // rate it settles on are then the writer's by construction. + Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + } +} + /// The header of a 32-bit float WAV holding `frames` frames (little-endian samples follow it). Its /// length doesn't depend on `frames`, so a recorder can rewrite it in place as the file grows; it /// switches to RF64 above 4 GiB. @@ -252,7 +347,7 @@ pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result< // With only one of `pcm-encode` and `flac-encode`, the other's formats are refused, not silently // written as something else. -#[cfg(all(test, not(all(feature = "pcm-encode", feature = "flac-encode"))))] +#[cfg(all(test, any(feature = "pcm-encode", feature = "flac-encode"), not(all(feature = "pcm-encode", feature = "flac-encode"))))] mod tests { use super::*; @@ -265,6 +360,7 @@ mod tests { let enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 1); assert!(matches!(enc, Err(AudioError::Unsupported(_)))); assert_eq!(encode_format_for(name), None); + assert!(!format.is_built() && EncodeFormat::ALL.iter().any(|f| f.is_built())); // Also with a layout it could not use. let opts = opts.with_layout(ChannelLayout::STEREO); assert!(matches!(encode(&buf, &opts), Err(AudioError::Unsupported(_)))); diff --git a/crates/audio/src/write/pcm.rs b/crates/audio/src/write/pcm.rs index 614d5a4a7a..402b9bebc1 100644 --- a/crates/audio/src/write/pcm.rs +++ b/crates/audio/src/write/pcm.rs @@ -1,6 +1,9 @@ //! PCM helpers shared by the WAV, AIFF and FLAC writers: quantization (with optional TPDF //! dither), interleaving and layout checks. +// The coded formats use the layout check, and of those only ALAC the quantizer. +#![cfg_attr(not(any(feature = "pcm-encode", feature = "flac-encode")), allow(dead_code))] + use crate::{AudioBuffer, AudioError, Result}; #[cfg(feature = "pcm-encode")] use {crate::BitDepth, std::io::Write}; diff --git a/crates/audio/tests/audio/decode_extensions.rs b/crates/audio/tests/audio/decode_extensions.rs index e8fe22d588..27a5573deb 100644 --- a/crates/audio/tests/audio/decode_extensions.rs +++ b/crates/audio/tests/audio/decode_extensions.rs @@ -62,11 +62,21 @@ fn every_decode_extension_probes_and_decodes() { fn every_encode_format_has_an_extension_it_is_written_and_read_under() { for &format in EncodeFormat::ALL { let ext = format.extension(); - assert_eq!(craft_audio::encode_format_for(ext), Some(format), "{ext}"); - assert!(craft_audio::ENCODE_EXTENSIONS.contains(&ext), "{ext}"); + // The extension names the format, or for `m4a`, which two formats share, AAC before ALAC. + // A format whose feature is off has no name. + match craft_audio::encode_format_for(ext) { + Some(named) => { + let shares_m4a = |f| matches!(f, EncodeFormat::Aac | EncodeFormat::Alac); + assert!(named == format || (shares_m4a(named) && shares_m4a(format)), "{ext}"); + assert!(named.is_built(), "{ext}"); + assert!(craft_audio::ENCODE_EXTENSIONS.contains(&ext), "{ext}"); + } + None => assert!(!matches!(format, EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac), "{ext}"), + } assert!(DECODE_EXTENSIONS.contains(&ext), "{ext}: what is written reads back"); assert!(format.mime_type().starts_with("audio/"), "{format:?}"); } - assert_eq!(EncodeFormat::ALL.iter().map(|f| f.extension()).collect::>(), ["wav", "aif", "flac"]); + let extensions: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.extension()).collect(); + assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3"]); assert_eq!(EncodeFormat::Aiff.mime_type(), "audio/aiff"); } diff --git a/crates/audio/tests/audio/encode_format.rs b/crates/audio/tests/audio/encode_format.rs index 30b992685f..7713f37a5a 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -14,7 +14,7 @@ fn only_formats_the_encoder_writes_are_named() { for name in craft_audio::ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - for other in ["mp3", "ogg", "m4a", "xyz", ""] { + for other in ["ogg", "opus", "aac", "mp4", "xyz", ""] { assert_eq!(encode_format_for(other), None, "{other}"); } } diff --git a/crates/audio/tests/codecs/file_formats.rs b/crates/audio/tests/codecs/file_formats.rs new file mode 100644 index 0000000000..53947df123 --- /dev/null +++ b/crates/audio/tests/codecs/file_formats.rs @@ -0,0 +1,571 @@ +//! The coded formats of `encode` and `FileEncoder` (AAC and ALAC in M4A; MP3, AC-3 and E-AC-3 +//! streams), read back with this crate's decoder and, where ffmpeg is installed, with ffmpeg. + +use std::io::{Cursor, Seek, SeekFrom, Write}; +use std::process::Command; + +use craft_audio::{ + AudioBuffer, AudioError, BitDepth, ChannelLayout, CodecId, Container, ENCODE_EXTENSIONS, EncodeFormat, EncodeOptions, FileEncoder, RateControl, + decode, encode, encode_format_for, +}; + +const CODED: [EncodeFormat; 5] = [EncodeFormat::Aac, EncodeFormat::Alac, EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3]; + +/// `channels` channels of `frames` frames, each channel a tone of its own frequency, on the +/// 16-bit grid (so a lossless 16-bit format returns it exactly). +fn tones(sample_rate: u32, channels: usize, frames: usize) -> AudioBuffer { + let channel = |c: usize| { + let step = (60.0 + 17.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32; + (0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect() + }; + AudioBuffer { sample_rate, channels: (0..channels).map(channel).collect() } +} + +/// Signal-to-noise ratio in dB of `got` against `want`, over the frames both have. +fn snr(want: &[f32], got: &[f32]) -> f64 { + let (signal, noise) = + want.iter().zip(got).fold((0f64, 0f64), |(s, n), (&w, &g)| (s + f64::from(w).powi(2), n + (f64::from(w) - f64::from(g)).powi(2))); + 10.0 * (signal / noise.max(1e-30)).log10() +} + +fn is_unsupported(r: Result) -> bool { + matches!(r, Err(AudioError::Unsupported(_))) +} + +/// An AAC file decodes to the frames that were written, in place: the edit list skips the +/// encoder's priming and cuts the padding of the last packet. +#[test] +fn aac_decodes_to_the_frames_written() { + for frames in [1, 1000, 1024, 1025, 5000, 48_017] { + let buf = tones(48_000, 2, frames); + let file = encode(&buf, &EncodeOptions::new(EncodeFormat::Aac)).unwrap(); + let (info, out) = decode(&file, Some("m4a")).unwrap(); + assert_eq!((info.container, info.codec, info.sample_rate, info.damaged), (Container::Mp4, CodecId::Aac, 48_000, 0)); + assert_eq!((info.frames, out.frames(), info.layout), (frames as u64, frames, ChannelLayout::STEREO), "{frames} frames"); + if frames >= 5000 { + for (want, got) in buf.channels.iter().zip(&out.channels) { + assert!(snr(want, got) > 30.0, "{frames} frames: {} dB", snr(want, got)); + } + } + } +} + +/// The M4A track's durations add up to the priming and the audio, and its one edit skips the +/// priming and lasts as long as the audio, in a movie timescale that is the sample rate. +#[test] +fn aac_timing_is_in_the_sample_table_and_the_edit_list() { + use craft_audio::craft_media::isobmff; + let file = encode(&tones(44_100, 1, 3000), &EncodeOptions::new(EncodeFormat::Aac)).unwrap(); + let mp4 = isobmff::open(file.as_slice()).unwrap(); + let track = &mp4.tracks[0]; + assert_eq!((mp4.timescale, track.timescale), (44_100, 44_100)); + assert_eq!(track.samples.iter().map(|s| u64::from(s.duration)).sum::(), 1024 + 3000); + assert_eq!(track.edits.len(), 1); + assert_eq!((track.edits[0].media_time, track.edits[0].segment_duration), (1024, 3000)); + // Every packet is in a `roll` group of distance -1, which Apple's decoders need to apply the edit. + let groups = &track.sample_groups; + assert_eq!((groups.len(), groups[0].grouping_type), (1, isobmff::FourCc(*b"roll"))); + assert_eq!((groups[0].runs.as_slice(), &groups[0].descriptions), ([(track.samples.len() as u32, 1)].as_slice(), &vec![vec![0xFF, 0xFF]])); +} + +/// The sample entry is completed when the file is: AAC's average bit rate, and the largest packet +/// and average bit rate in ALAC's cookie. +#[test] +fn the_sample_entry_describes_the_finished_stream() { + use craft_audio::craft_media::isobmff::{self, CodecConfig}; + let buf = tones(48_000, 2, 48_000); + let file = encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(96_000)).unwrap(); + let mp4 = isobmff::open(file.as_slice()).unwrap(); + let CodecConfig::Aac(aac) = &mp4.tracks[0].entries[0].codec else { panic!("not AAC") }; + assert!((90_000..100_000).contains(&aac.avg_bitrate), "{} bit/s", aac.avg_bitrate); + + let file = encode(&buf, &EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16)).unwrap(); + let mp4 = isobmff::open(file.as_slice()).unwrap(); + let CodecConfig::Alac { cookie } = &mp4.tracks[0].entries[0].codec else { panic!("not ALAC") }; + let config = craft_audio::alac::SpecificConfig::parse(cookie).unwrap(); + let largest = mp4.tracks[0].samples.iter().map(|s| s.size).max().unwrap(); + assert_eq!((config.max_frame_bytes, config.bit_depth, config.frame_length), (largest, 16, 4096)); + assert!(config.avg_bit_rate > 0); +} + +/// Dither reaches ALAC's quantizer: a level below one 16-bit step is silence without it. +#[test] +fn alac_dithers_when_asked() { + let buf = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.3 / 32768.0; 4096]] }; + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16); + let (_, plain) = decode(&encode(&buf, &opts).unwrap(), Some("m4a")).unwrap(); + let (_, dithered) = decode(&encode(&buf, &opts.with_dither(true)).unwrap(), Some("m4a")).unwrap(); + assert!(plain.channels[0].iter().all(|&s| s == 0.0)); + assert!(dithered.channels[0].iter().any(|&s| s != 0.0)); +} + +/// ALAC returns the quantized samples exactly, for every channel count, with each channel where +/// its speaker is. +#[test] +fn alac_is_lossless_in_every_layout() { + for channels in 1..=8u8 { + let layout = ChannelLayout::from_mask(craft_audio::alac::channel_mask(channels)); + let buf = tones(44_100, usize::from(channels), 10_000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(layout); + let file = encode(&buf, &opts).unwrap(); + let (info, out) = decode(&file, Some("m4a")).unwrap(); + assert_eq!((info.container, info.codec, info.frames, info.layout), (Container::Mp4, CodecId::Alac, 10_000, layout), "{channels} channels"); + assert_eq!(out, buf, "{channels} channels"); + } + // 24 bits, and a length that is no whole number of packets. + let buf = tones(96_000, 2, 4096 * 2 + 1); + let (_, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Alac)).unwrap(), Some("m4a")).unwrap(); + assert_eq!(out, buf); +} + +/// Channels go to the encoder by speaker. ALAC's 6.1 has the back centre last and AAC's has it +/// before the surround pair; 5.1 with side surrounds is the format's one 5.1. +#[test] +fn channels_reach_their_speakers() { + // WAV 6.1 with a back pair (L R C LFE Lb Rb Cb), the usual 7-channel layout, into ALAC: the same. + let buf = tones(48_000, 7, 8000); + let (info, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16)).unwrap(), Some("m4a")).unwrap(); + assert_eq!(info.layout, ChannelLayout::from_mask(0x13F)); + assert_eq!(out, buf); + // 5.1 with side surrounds decodes from ALAC as 5.1 with back surrounds, channel for channel. + let buf = tones(48_000, 6, 8000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1_SIDE); + assert_eq!(decode(&encode(&buf, &opts).unwrap(), Some("m4a")).unwrap().1, buf); + + // AAC: the decoded channel each input channel comes back as. 5.1 decodes in WAV order; the + // 6.1 and 7.1 streams have no speaker assignment and decode in AAC order (C L R Ls Rs Cs LFE + // and C Lc Rc L R Ls Rs LFE). + let wide = ChannelLayout::from_mask(0xFF); + let cases: [(usize, Option, &[usize]); 3] = + [(6, None, &[0, 1, 2, 3, 4, 5]), (7, None, &[2, 0, 1, 4, 5, 6, 3]), (8, Some(wide), &[2, 6, 7, 0, 1, 4, 5, 3])]; + for (channels, layout, decoded_from) in cases { + let buf = tones(48_000, channels, 48_000); + let mut opts = EncodeOptions::new(EncodeFormat::Aac); + opts.layout = layout; + let (info, out) = decode(&encode(&buf, &opts).unwrap(), Some("m4a")).unwrap(); + assert_eq!((usize::from(info.channels), out.frames()), (channels, 48_000)); + for (decoded, &input) in decoded_from.iter().enumerate() { + let db = snr(&buf.channels[input], &out.channels[decoded]); + assert!(db > 20.0, "{channels} channels: decoded {decoded} is not input {input} ({db} dB)"); + } + } +} + +/// MP3, AC-3 and E-AC-3 are raw streams: the audio comes back behind the codec's delay. +#[test] +fn raw_streams_decode_behind_the_codec_delay() { + let buf = tones(48_000, 2, 48_000); + for (format, codec, container, delay, floor) in [ + (EncodeFormat::Mp3, CodecId::Mp3, Container::MpegAudio, craft_audio::mp3::DELAY as usize, 25.0), + (EncodeFormat::Ac3, CodecId::Ac3, Container::Ac3, 256, 15.0), + (EncodeFormat::Eac3, CodecId::Eac3, Container::Ac3, 256, 15.0), + ] { + let file = encode(&buf, &EncodeOptions::new(format)).unwrap(); + let (info, out) = decode(&file, Some(format.extension())).unwrap(); + assert_eq!((info.codec, info.container, info.sample_rate, info.layout, info.damaged), (codec, container, 48_000, ChannelLayout::STEREO, 0)); + assert_eq!((format.codec(), format.container()), (codec, container)); + assert!(out.frames() >= 48_000 + delay, "{format:?}: {} frames", out.frames()); + for (want, got) in buf.channels.iter().zip(&out.channels) { + let db = snr(want, &got[delay..]); + assert!(db > floor, "{format:?}: {db} dB"); + } + } + // 5.1 with back surrounds is AC-3's 3/2 mode with an LFE, channel for channel. + let buf = tones(48_000, 6, 48_000); + let (info, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Ac3)).unwrap(), Some("ac3")).unwrap(); + assert_eq!(info.layout, ChannelLayout::SURROUND_5_1_SIDE); + for (c, (want, got)) in buf.channels.iter().zip(&out.channels).enumerate() { + // The encoder low-pass filters the LFE, which shifts its phase: it is compared by level. + if c == 3 { + let rms = |x: &[f32]| (x.iter().map(|&s| f64::from(s).powi(2)).sum::() / x.len() as f64).sqrt(); + let level = rms(&got[4800..]) / rms(want); + assert!((0.5..1.5).contains(&level), "LFE at {level} of its level"); + } else { + assert!(snr(want, &got[256..]) > 12.0, "channel {c}: {} dB", snr(want, &got[256..])); + } + } + // 7.1 is an E-AC-3 programme. + let buf = tones(48_000, 8, 4800); + assert!(is_unsupported(encode(&buf, &EncodeOptions::new(EncodeFormat::Ac3)))); + // (Read back by ffmpeg in `ffmpeg_reads_the_files`: this crate's file reader plays the 5.1 + // independent substream of a raw 7.1 stream.) + assert!(!encode(&buf, &EncodeOptions::new(EncodeFormat::Eac3)).unwrap().is_empty()); +} + +/// Blocks of any sizes give the bytes `encode` gives. +#[test] +fn streaming_writes_the_bytes_of_encode() { + let buf = tones(44_100, 2, 30_000); + for format in CODED { + let opts = EncodeOptions::new(format); + let whole = encode(&buf, &opts).unwrap(); + let mut enc = FileEncoder::new(Cursor::new(Vec::new()), &opts, 44_100, 2).unwrap(); + assert!(format!("{enc:?}").contains(&format!("{format:?}"))); + let mut at = 0; + for n in [1, 4095, 4097, 0, 9000, 12_807] { + let block: Vec<&[f32]> = buf.channels.iter().map(|c| &c[at..]).collect(); + enc.check_room(n as u64).unwrap(); + enc.write(&block, n).unwrap(); + at += n; + } + assert_eq!(at, buf.frames()); + assert!(enc.finish().unwrap().into_inner() == whole, "{format:?}"); + } +} + +/// A file starts at the sink's position. +#[test] +fn a_file_starts_at_the_sinks_position() { + let buf = tones(48_000, 1, 6000); + for format in CODED { + let opts = EncodeOptions::new(format); + let mut sink = Cursor::new(b"junk".to_vec()); + sink.seek(SeekFrom::End(0)).unwrap(); + let mut enc = FileEncoder::new(sink, &opts, 48_000, 1).unwrap(); + enc.write(&buf.channels, 6000).unwrap(); + let mut sink = enc.finish().unwrap(); + let end = sink.stream_position().unwrap(); + let bytes = sink.into_inner(); + assert_eq!(end, bytes.len() as u64, "{format:?}"); + assert!(bytes[4..] == encode(&buf, &opts).unwrap(), "{format:?}"); + } +} + +/// A file with no audio is still a file of its format. +#[test] +fn no_audio_gives_an_empty_file() { + let buf = AudioBuffer::new(48_000, 2, 0); + for format in CODED { + let file = encode(&buf, &EncodeOptions::new(format)).unwrap(); + if format.container() == Container::Mp4 { + let mp4 = craft_audio::craft_media::isobmff::open(file.as_slice()).unwrap(); + assert_eq!((mp4.tracks.len(), mp4.tracks[0].samples.len(), mp4.tracks[0].edits.len()), (1, 0, 0), "{format:?}"); + } else { + assert!(file.is_empty(), "{format:?}"); + } + } +} + +/// The bit rate asked for is the one written, moved to the nearest the format has. +#[test] +fn the_bit_rate_is_followed() { + let buf = tones(48_000, 2, 48_000); + let size = |opts: &EncodeOptions| encode(&buf, opts).unwrap().len(); + // MP3 at 48 kHz: 24 bytes per frame and kbit/s, 43 frames for a second and the delay. + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3)), 43 * 192 * 3); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(130_000)), 43 * 128 * 3); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(1)), 43 * 32 * 3); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(u32::MAX)), 43 * 320 * 3); + // AC-3: 32 packets of 1536 frames, 4 bytes per packet and kbit/s. + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Ac3)), 32 * 192 * 4); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Ac3).with_bitrate(100_000)), 32 * 96 * 4); + assert_eq!(size(&EncodeOptions::new(EncodeFormat::Eac3).with_bitrate(100_000)), 32 * 100 * 4); + // AAC: a second of audio at about the rate asked for, around the 128 kbit/s default. + let (low, default, high) = ( + size(&EncodeOptions::new(EncodeFormat::Aac).with_bitrate(64_000)), + size(&EncodeOptions::new(EncodeFormat::Aac)), + size(&EncodeOptions::new(EncodeFormat::Aac).with_bitrate(256_000)), + ); + assert!((7000..10_000).contains(&low) && (15_000..18_500).contains(&default) && (30_000..35_000).contains(&high), "{low} {default} {high}"); + // A rate no stream can carry is moved into range, not refused. + encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(u32::MAX)).unwrap(); + // The lowest rate still codes the audio: the encoder accepts rates that leave only silence + // (128 for 128 kbit/s is one), and the writer does not go that low. + for (sample_rate, channels) in [(8000, 1), (16_000, 2), (44_100, 2), (48_000, 6), (96_000, 2)] { + let buf = tones(sample_rate, channels, sample_rate as usize); + let (_, out) = decode(&encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128)).unwrap(), Some("m4a")).unwrap(); + let rms = |x: &[f32]| (x.iter().map(|&s| f64::from(s).powi(2)).sum::() / x.len() as f64).sqrt(); + let level = rms(&out.channels[0]) / rms(&buf.channels[0]); + assert!(level > 0.5, "{sample_rate} Hz, {channels} channels: {level} of the level"); + } + // Quality is AAC's; ALAC has no rate to control. + let (small, large) = + (size(&EncodeOptions::new(EncodeFormat::Aac).with_quality(0.0)), size(&EncodeOptions::new(EncodeFormat::Aac).with_quality(1.0))); + assert!(small < large, "{small} {large}"); + assert!(matches!(encode(&buf, &EncodeOptions::new(EncodeFormat::Aac).with_quality(f32::NAN)), Err(AudioError::Encode(_)))); + for format in [EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3] { + assert!(is_unsupported(encode(&buf, &EncodeOptions::new(format).with_quality(0.5))), "{format:?}"); + } + let alac = EncodeOptions::new(EncodeFormat::Alac); + assert_eq!(size(&alac), size(&alac.clone().with_bitrate(64_000))); + assert_eq!(alac.rate_control, None); + assert_eq!(alac.with_quality(0.5).rate_control, Some(RateControl::Quality(0.5))); +} + +/// What a format cannot hold is refused before anything is written. +#[test] +fn what_a_format_cannot_hold_is_refused() { + let refused = |format, sample_rate, channels: u16, layout: Option| { + let mut opts = EncodeOptions::new(format); + opts.layout = layout; + let mut sink = Cursor::new(Vec::new()); + let r = FileEncoder::new(&mut sink, &opts, sample_rate, channels).map(drop); + assert!(r.is_ok() || sink.into_inner().is_empty(), "{format:?}: bytes written for a refused file"); + assert_eq!(r.is_err(), encode(&AudioBuffer::new(sample_rate, channels, 100), &opts).is_err()); + r + }; + // Quad has no centre, which AAC's and ALAC's four channels have. + assert!(is_unsupported(refused(EncodeFormat::Aac, 48_000, 4, None))); + assert!(is_unsupported(refused(EncodeFormat::Alac, 48_000, 4, None))); + refused(EncodeFormat::Aac, 48_000, 4, Some(ChannelLayout::from_mask(0x107))).unwrap(); + // WAV 7.1 (backs and sides) is not the 7.1 of AAC and ALAC (a front pair left and right of centre). + assert!(is_unsupported(refused(EncodeFormat::Aac, 48_000, 8, None))); + assert!(is_unsupported(refused(EncodeFormat::Alac, 48_000, 8, Some(ChannelLayout::SURROUND_7_1)))); + assert!(is_unsupported(refused(EncodeFormat::Aac, 48_000, 2, Some(ChannelLayout::unordered(2))))); + for format in CODED { + assert!(is_unsupported(refused(format, 48_000, 9, None)), "{format:?}"); + assert!(matches!(refused(format, 48_000, 2, Some(ChannelLayout::MONO)), Err(AudioError::Encode(_))), "{format:?}"); + assert!(matches!(refused(format, 0, 2, None), Err(AudioError::Encode(_))), "{format:?}"); + assert!(matches!(refused(format, 48_000, 0, None), Err(AudioError::Encode(_))), "{format:?}"); + } + assert!(is_unsupported(refused(EncodeFormat::Mp3, 48_000, 3, None))); + assert!(is_unsupported(refused(EncodeFormat::Ac3, 48_000, 7, None))); + // Sample rates the codec has not. + for format in [EncodeFormat::Aac, EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3] { + assert!(matches!(refused(format, 44_000, 2, None), Err(AudioError::Encode(_))), "{format:?}"); + } + refused(EncodeFormat::Alac, 44_000, 2, None).unwrap(); + let float = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Float32); + assert!(is_unsupported(encode(&AudioBuffer::new(48_000, 2, 100), &float))); +} + +/// Samples no encoder should see: NaN is silence, and values past full scale do not fail a +/// write (AC-3, whose encoder refuses them, gets them clamped). +#[test] +fn non_finite_and_loud_samples_are_written() { + let mut buf = tones(48_000, 2, 6000); + buf.channels[0][100] = f32::NAN; + buf.channels[0][200] = f32::INFINITY; + buf.channels[1][300] = -7.5; + for format in CODED { + let file = encode(&buf, &EncodeOptions::new(format)).unwrap(); + let (_, out) = decode(&file, Some(format.extension())).unwrap(); + assert!(out.channels.iter().flatten().all(|s| s.is_finite()), "{format:?}"); + } +} + +/// A sink that fails once `room` bytes are written. +struct Full { + inner: Cursor>, + room: usize, +} + +impl Write for Full { + fn write(&mut self, data: &[u8]) -> std::io::Result { + if self.inner.get_ref().len() + data.len() > self.room { + return Err(std::io::Error::other("disk full")); + } + self.inner.write(data) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl Seek for Full { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} + +/// After a failed write the encoder is unusable: later writes and `finish` fail too. +#[test] +fn a_failed_write_ends_the_encoder() { + let buf = tones(48_000, 2, 48_000); + for format in CODED { + let mut enc = FileEncoder::new(Full { inner: Cursor::new(Vec::new()), room: 2000 }, &EncodeOptions::new(format), 48_000, 2).unwrap(); + assert!(matches!(enc.write(&buf.channels, 48_000), Err(AudioError::Io(_))), "{format:?}"); + assert!(matches!(enc.write(&buf.channels, 1), Err(AudioError::Encode(_))), "{format:?}"); + assert!(matches!(enc.finish(), Err(AudioError::Encode(_))), "{format:?}"); + } +} + +#[test] +fn the_formats_are_named() { + assert_eq!(encode_format_for("m4a"), Some(EncodeFormat::Aac)); + assert_eq!(encode_format_for(".ALAC"), Some(EncodeFormat::Alac)); + assert_eq!(encode_format_for("mp3"), Some(EncodeFormat::Mp3)); + assert_eq!(encode_format_for("ac3"), Some(EncodeFormat::Ac3)); + assert_eq!(encode_format_for("eac3"), Some(EncodeFormat::Eac3)); + assert_eq!(encode_format_for("ec3"), Some(EncodeFormat::Eac3)); + for &format in EncodeFormat::ALL { + assert!(ENCODE_EXTENSIONS.contains(&format.extension()), "{format:?}"); + let named = encode_format_for(format.extension()).unwrap(); + assert_eq!((named.extension(), named.mime_type()), (format.extension(), format.mime_type())); + assert_eq!(format.is_lossy(), !matches!(format.codec(), CodecId::Pcm | CodecId::Flac | CodecId::Alac)); + } + for name in ENCODE_EXTENSIONS { + assert!(encode_format_for(name).is_some(), "{name}"); + } + assert_eq!(ENCODE_EXTENSIONS.len(), 12); + for format in CODED { + assert!(EncodeFormat::ALL.contains(&format) && format.is_built()); + } + let features: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.feature()).collect(); + assert_eq!(features, ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode"]); +} + +/// ffmpeg's decode of `file` as interleaved `f32`, split into `channels` channels. +fn ffmpeg_decode(ff: &std::path::Path, file: &[u8], name: &str, channels: usize) -> Vec> { + let path = crate::testkit::fixtures_dir("file_formats").join(name); + std::fs::write(&path, file).unwrap(); + let out = Command::new(ff).args(["-v", "error", "-i"]).arg(&path).args(["-f", "f32le", "-"]).output().unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{name}: {}", String::from_utf8_lossy(&out.stderr)); + let mut planar = vec![Vec::new(); channels]; + for (i, s) in out.stdout.as_chunks::<4>().0.iter().enumerate() { + planar[i % channels].push(f32::from_le_bytes(*s)); + } + planar +} + +/// ffmpeg reads every format: the M4A files without their priming (it applies the edit list) and, +/// from ffmpeg 9, at the length written; ALAC exactly; the raw streams behind their delay. +#[test] +fn ffmpeg_reads_the_files() { + let ff = require_ffmpeg!(); + for (channels, layout) in [(1, None), (2, None), (6, None), (8, Some(ChannelLayout::from_mask(0xFF)))] { + let buf = tones(48_000, channels, 20_000); + let mut opts = EncodeOptions::new(EncodeFormat::Aac); + opts.layout = layout; + let out = ffmpeg_decode(&ff, &encode(&buf, &opts).unwrap(), &format!("aac_{channels}.m4a"), channels); + // The priming is skipped by every ffmpeg (the channels below line up). The padding of the + // last packet is cut by ffmpeg 9; ffmpeg 8 plays it, to the end of the 20th packet. + assert!([20_000, 20_480].contains(&out[0].len()), "AAC, {channels} channels: {} frames", out[0].len()); + if channels <= 6 { + // ffmpeg also returns 5.1 in WAV order. + for (c, (want, got)) in buf.channels.iter().zip(&out).enumerate() { + assert!(snr(want, got) > 20.0, "AAC, {channels} channels, channel {c}: {} dB", snr(want, got)); + } + } + let opts = opts.with_format(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16); + let opts = if channels == 6 { opts.with_layout(ChannelLayout::SURROUND_5_1) } else { opts }; + let out = ffmpeg_decode(&ff, &encode(&buf, &opts).unwrap(), &format!("alac_{channels}.m4a"), channels); + assert!(out == buf.channels, "ALAC, {channels} channels"); + } + let buf = tones(44_100, 2, 20_000); + for (format, delay, floor) in + [(EncodeFormat::Mp3, craft_audio::mp3::DELAY as usize, 25.0), (EncodeFormat::Ac3, 256, 15.0), (EncodeFormat::Eac3, 256, 15.0)] + { + let name = format!("stream.{}", format.extension()); + let out = ffmpeg_decode(&ff, &encode(&buf, &EncodeOptions::new(format)).unwrap(), &name, 2); + for (want, got) in buf.channels.iter().zip(&out) { + assert!( + got.len() >= 20_000 + delay && snr(want, &got[delay..]) > floor, + "{format:?}: {} frames, {} dB", + got.len(), + snr(want, &got[delay..]) + ); + } + } + // E-AC-3 7.1: the front channels, which the 5.1 downmix leaves as they are. + let buf = tones(48_000, 8, 20_000); + let out = ffmpeg_decode(&ff, &encode(&buf, &EncodeOptions::new(EncodeFormat::Eac3)).unwrap(), "stream_7_1.eac3", 8); + assert!(out[7].len() >= 20_256); + for c in 0..3 { + assert!(snr(&buf.channels[c], &out[c][256..]) > 12.0, "E-AC-3 7.1, channel {c}: {} dB", snr(&buf.channels[c], &out[c][256..])); + } +} + +/// Apple's decoder (macOS `afinfo`; skipped elsewhere) takes the priming and the length of an AAC +/// file from the edit list, which it does only for a track with a `roll` sample group. +#[test] +fn apple_reads_the_aac_priming_and_length() { + let Some(afinfo) = crate::testkit::oracle::find_tool("afinfo") else { return }; + for (frames, remainder) in [(20_000, 480), (1, 1023), (4096, 0)] { + let path = crate::testkit::fixtures_dir("file_formats").join(format!("apple_{frames}.m4a")); + std::fs::write(&path, encode(&tones(48_000, 2, frames), &EncodeOptions::new(EncodeFormat::Aac)).unwrap()).unwrap(); + let out = Command::new(&afinfo).arg(&path).output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains(&format!("{frames} valid frames + 1024 priming + {remainder} remainder")), "{frames} frames: {text}"); + } +} + +/// What `EncodeFormat` says a format takes is what the writer accepts: for every format, a file +/// can be begun exactly when the sample rate, the channel count and the layout are listed. +#[test] +fn the_format_queries_agree_with_the_writer() { + // Every rate a format lists, each with its neighbours, and some that none lists. + let mut rates: Vec = EncodeFormat::ALL.iter().filter_map(|f| f.sample_rates()).flatten().flat_map(|&r| [r - 1, r, r + 1]).collect(); + rates.extend([44_000, 176_400, 192_000]); + rates.sort_unstable(); + rates.dedup(); + let masks = [ + 0x4, 0x1, 0x3, 0xC, 0x600, 0x7, 0xB, 0x103, 0x33, 0x107, 0x603, 0xF, 0x10B, 0x37, 0x607, 0x10F, 0x60B, 0x3F, 0x60F, 0x13F, 0x70F, 0x63F, 0xFF, + ]; + let layouts = masks.iter().map(|&mask| ChannelLayout::from_mask(mask)).chain((1..=9).map(ChannelLayout::unordered)); + for layout in layouts { + for &format in EncodeFormat::ALL { + // 24 bits is a depth every format has. + let opts = EncodeOptions::new(format).with_layout(layout); + for &sample_rate in &rates { + let listed = format.sample_rates().is_none_or(|r| r.contains(&sample_rate)) + && layout.channels() <= format.max_channels() + && format.supports_layout(&layout); + let checked = opts.check(sample_rate, layout.channels()); + assert_eq!(checked.is_ok(), listed, "{format:?}, {sample_rate} Hz, {layout:?}: {checked:?}"); + let begun = FileEncoder::new(Cursor::new(Vec::new()), &opts, sample_rate, layout.channels()); + assert_eq!(begun.is_ok(), listed, "{format:?}, {sample_rate} Hz, {layout:?}"); + } + if let Some(fixed) = format.fixed_layouts(layout.channels()) { + assert!(fixed.iter().all(|l| format.supports_layout(l) && l.channels() == layout.channels())); + assert_eq!(format.supports_layout(&layout), fixed.iter().any(|l| same_speakers(l, &layout)), "{format:?}, {layout:?}"); + } + } + } + for &format in EncodeFormat::ALL { + assert!(!format.supports_layout(&ChannelLayout::unordered(0))); + assert_eq!(format.supports_quality(), EncodeOptions::new(format).with_quality(0.5).check(48_000, 2).is_ok() && format.is_lossy()); + assert_eq!(format.fixed_layouts(2).is_none(), matches!(format, EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac)); + } + // The most channels is the most: one more is refused, by the layouts of a format that has + // a fixed set and by the writer of one that has not. + let most: Vec = EncodeFormat::ALL.iter().map(|f| f.max_channels()).collect(); + assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8]); + for &format in EncodeFormat::ALL { + let most = format.max_channels(); + match format.fixed_layouts(most) { + Some(layouts) => assert!(!layouts.is_empty() && format.fixed_layouts(most + 1).unwrap().is_empty(), "{format:?}"), + None => { + let opts = EncodeOptions::new(format).with_bit_depth(BitDepth::Int16); + assert!(opts.check(48_000, most).is_ok() && opts.check(48_000, most + 1).is_err(), "{format:?}"); + assert!(format.supports_layout(&ChannelLayout::unordered(most)) && !format.supports_layout(&ChannelLayout::unordered(most + 1))); + } + } + } + assert_eq!(EncodeFormat::Ac3.fixed_layouts(3).unwrap().len(), 3); + assert!(EncodeFormat::Aac.fixed_layouts(9).unwrap().is_empty()); +} + +/// Whether two layouts name the same speakers, a surround pair being either sides or backs. +fn same_speakers(a: &ChannelLayout, b: &ChannelLayout) -> bool { + let one_pair = |mask: u32| if mask & 0x630 == 0x30 { mask & !0x30 | 0x600 } else { mask }; + matches!((a.mask(), b.mask()), (Some(a), Some(b)) if one_pair(a) == one_pair(b)) +} + +/// `bitrate` is the rate the file is written at, for the options and for the encoder they give. +#[test] +fn the_bit_rate_used_can_be_asked_for() { + let rate = |opts: EncodeOptions, sample_rate, channels| { + let asked = opts.bitrate(sample_rate, channels).unwrap(); + assert_eq!(FileEncoder::new(Cursor::new(Vec::new()), &opts, sample_rate, channels).unwrap().bitrate(), asked); + asked + }; + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Mp3), 48_000, 2), Some(192_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(130_000), 48_000, 2), Some(128_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(u32::MAX), 22_050, 1), Some(160_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Ac3).with_bitrate(191_999), 48_000, 2), Some(160_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Ac3), 48_000, 6), Some(448_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Eac3).with_bitrate(100_999), 48_000, 2), Some(100_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac), 48_000, 2), Some(128_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128), 48_000, 2), Some(24_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac).with_bitrate(u32::MAX), 8000, 1), Some(48_000)); + assert_eq!(rate(EncodeOptions::new(EncodeFormat::Aac).with_quality(0.5), 48_000, 2), None); + for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac, EncodeFormat::Alac] { + assert_eq!(rate(EncodeOptions::new(format).with_bitrate(96_000), 48_000, 2), None, "{format:?}"); + } + // The size of a second of MP3 is the rate reported. + let buf = tones(48_000, 2, 48_000); + let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(130_000); + assert_eq!(encode(&buf, &opts).unwrap().len() as u32, 43 * 1152 / 8 * opts.bitrate(48_000, 2).unwrap().unwrap() / 48_000); + assert!(is_unsupported(EncodeOptions::new(EncodeFormat::Mp3).bitrate(48_000, 6))); +} diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index 279246dc6a..c1c9e2131b 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -12,6 +12,7 @@ mod ac3_encoder_oracle; mod ac3_oracle; mod alac; mod concealment; +mod file_formats; mod mp3_decoder_oracle; mod mp3_encoder_oracle; mod mpa_oracle; diff --git a/crates/designcraft-format/src/lib.rs b/crates/designcraft-format/src/lib.rs index 6256eab1cc..eab431eab8 100644 --- a/crates/designcraft-format/src/lib.rs +++ b/crates/designcraft-format/src/lib.rs @@ -6,7 +6,7 @@ #![forbid(unsafe_code)] use std::collections::{HashMap, HashSet}; -use std::io::{Read, Seek}; +use std::io::{Cursor, Read, Seek, Write}; pub use craft_document_bundle::Asset; use craft_document_bundle::Spec; @@ -14,9 +14,10 @@ use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; pub const MIME: &str = "application/vnd.designcraft+zip"; -pub const VERSION: u32 = 4; +pub const VERSION: u32 = 5; pub const EXTENSION: &str = "designcraft"; pub const PREVIEW: &str = "preview.png"; +pub const PROXIES_DIRECTORY: &str = "proxies"; pub const MAX_PREVIEW_BYTES: u64 = 4 << 20; const BUNDLE: Spec<'static> = Spec { @@ -26,6 +27,7 @@ const BUNDLE: Spec<'static> = Spec { document_entry: "document.json", preview_entry: PREVIEW, assets_directory: "assets", + proxies_directory: PROXIES_DIRECTORY, format_name: "designcraft", legacy_assets_field: Some("assetData"), }; @@ -57,23 +59,53 @@ impl From for Error { pub struct Loaded { pub document: T, pub assets: Vec<(String, Vec)>, + /// Proxy previews (JPEG or PNG bytes) of linked assets, keyed by asset id. + pub proxies: Vec<(String, Vec)>, } /// The reader capability required by `document`, inferred from its neutral JSON schema and -/// embedded assets. Traversal beyond 64 levels conservatively requires version 4. +/// embedded assets. Traversal beyond 64 levels conservatively requires version 4. A linked +/// asset (`/assets//storage == "linked"`) requires version 5. pub fn required_version(document: &Value, assets: &[Asset<'_>]) -> u32 { + if has_linked_asset(document) { + return 5; + } if has_version_four_feature(document) { return 4; } if assets.iter().any(|asset| craft_eps::is_eps(asset.data)) { 3 } else { 2 } } -/// Serialize a document and its external assets as a `.designcraft` ZIP bundle. -pub fn save(document: &T, generator: &str, preview: Option<&[u8]>, assets: &[Asset<'_>]) -> Result, Error> { +/// Serialize a document, its embedded assets and the proxy previews of its linked assets as a +/// `.designcraft` ZIP bundle. Linked assets have a record in the document and no `assets` entry. +pub fn save( + document: &T, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], +) -> Result, Error> { + let mut out = Cursor::new(Vec::new()); + write_to(&mut out, document, generator, preview, assets, proxies)?; + Ok(out.into_inner()) +} + +/// Like [`save`], streaming the ZIP into `out`. A writer that returns an error (to cancel a +/// long save, say) stops the write and the error is returned as [`Error::Io`]. +pub fn write_to( + out: W, + document: &T, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], +) -> Result<(), Error> { let value = serde_json::to_value(document).map_err(|error| Error::Io(error.to_string()))?; + let embedded: Vec> = assets.iter().filter(|asset| !is_linked(&value, asset.id)).copied().collect(); + let assets = embedded.as_slice(); let version = required_version(&value, assets); let json = serde_json::to_vec_pretty(&value).map_err(|error| Error::Io(error.to_string()))?; - craft_document_bundle::write(&json, version, generator, preview, assets, BUNDLE).map_err(Into::into) + craft_document_bundle::write_to(out, &json, version, generator, preview, assets, proxies, BUNDLE).map_err(Into::into) } /// Read a `.designcraft` ZIP or legacy single-file JSON, applying all versioned schema migrations @@ -82,7 +114,7 @@ pub fn load(bytes: &[u8]) -> Result, Error> { let mut package = craft_document_bundle::read(bytes, VERSION, BUNDLE)?; upgrade_legacy_json(&mut package.document, package.version); let document = serde_json::from_value(package.document).map_err(|error| Error::NotOurs(error.to_string()))?; - Ok(Loaded { document, assets: package.assets }) + Ok(Loaded { document, assets: package.assets, proxies: package.proxies }) } /// Whether `bytes` are a native DesignCraft ZIP package. @@ -100,6 +132,17 @@ pub fn read_preview(reader: R) -> Option> { craft_document_bundle::read_preview_from(reader, PREVIEW) } +fn is_linked(document: &Value, id: &str) -> bool { + document.get("assets").and_then(|assets| assets.get(id)).and_then(|asset| asset.get("storage")).and_then(Value::as_str) == Some("linked") +} + +fn has_linked_asset(document: &Value) -> bool { + document + .get("assets") + .and_then(Value::as_object) + .is_some_and(|assets| assets.values().any(|asset| asset.get("storage").and_then(Value::as_str) == Some("linked"))) +} + fn has_version_four_feature(document: &Value) -> bool { let mut stack = vec![(document, 0usize)]; let mut visited = 0usize; diff --git a/crates/designcraft-format/src/tests.rs b/crates/designcraft-format/src/tests.rs index 0ef2ca191e..38cf1c34f5 100644 --- a/crates/designcraft-format/src/tests.rs +++ b/crates/designcraft-format/src/tests.rs @@ -7,7 +7,7 @@ fn native_bundle_roundtrips_document_assets_and_preview() -> Result<(), Box Result<(), Box Result<(), Box> { let oversized = vec![0u8; usize::try_from(MAX_PREVIEW_BYTES + 1)?]; - let bytes = save(&json!({}), "DesignCraft test", Some(&oversized), &[])?; + let bytes = save(&json!({}), "DesignCraft test", Some(&oversized), &[], &[])?; assert_eq!(read_preview(std::io::Cursor::new(bytes)), None); Ok(()) } @@ -65,8 +65,105 @@ fn legacy_json_extracts_assets_and_applies_v1_migrations() -> Result<(), Box Result<(), Box> { - let bytes = craft_document_bundle::write(b"{", VERSION + 1, "future", None, &[], BUNDLE)?; + let bytes = craft_document_bundle::write(b"{", VERSION + 1, "future", None, &[], &[], BUNDLE)?; assert!(matches!(load::(&bytes), Err(Error::TooNew(version)) if version == u64::from(VERSION + 1))); assert!(matches!(load::(b"not a package"), Err(Error::NotOurs(_)))); Ok(()) } + +fn linked_doc() -> Value { + json!({"assets":{"7":{"storage":"linked","mime":"image/png"},"8":{"mime":"image/png"}}}) +} + +#[test] +fn embedded_documents_keep_their_version() { + assert_eq!(required_version(&json!({"assets":{"7":{"storage":"embedded"},"8":{}}}), &[]), 2); +} + +#[test] +fn a_linked_asset_requires_version_five_and_old_readers_refuse_it() -> Result<(), Box> { + assert_eq!(required_version(&linked_doc(), &[]), 5); + let bytes = save(&linked_doc(), "t", None, &[], &[])?; + assert_eq!(craft_document_bundle::read(&bytes, 4, BUNDLE), Err(craft_document_bundle::Error::TooNew(5))); + let loaded = load::(&bytes)?; + assert_eq!(loaded.document, linked_doc()); + assert!(loaded.assets.is_empty()); + Ok(()) +} + +#[test] +fn proxies_round_trip_and_unknown_or_oversized_ones_are_skipped() -> Result<(), Box> { + let big = vec![0u8; usize::try_from(craft_document_bundle::PROXY_LIMIT)? + 1]; + let proxies = [ + Asset { id: "7", mime: "image/jpeg", data: b"jpeg" }, + Asset { id: "8", mime: "image/png", data: &big }, + Asset { id: "99", mime: "image/png", data: b"unknown" }, + ]; + let bytes = save(&linked_doc(), "t", None, &[], &proxies)?; + assert_eq!(load::(&bytes)?.proxies, [("7".to_owned(), b"jpeg".to_vec())]); + Ok(()) +} + +#[test] +fn proxy_paths_must_be_exactly_proxies_id_ext() -> Result<(), Box> { + let proxies = [ + Asset { id: "../x", mime: "image/png", data: b"a" }, + Asset { id: "a/b", mime: "image/png", data: b"b" }, + Asset { id: "7/8", mime: "image/png", data: b"c" }, + ]; + let bytes = save(&linked_doc(), "t", None, &[], &proxies)?; + assert!(load::(&bytes)?.proxies.is_empty()); + Ok(()) +} + +#[test] +fn write_to_stops_when_the_writer_fails() { + struct Failing { + inner: Cursor>, + budget: usize, + failed: bool, + calls_after_failure: std::rc::Rc>, + } + impl Write for Failing { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.failed { + self.calls_after_failure.set(self.calls_after_failure.get() + 1); + } + if self.budget < buf.len() { + self.failed = true; + return Err(std::io::Error::other("cancelled")); + } + self.budget -= buf.len(); + self.inner.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + if self.failed { + self.calls_after_failure.set(self.calls_after_failure.get() + 1); + } + self.inner.flush() + } + } + impl Seek for Failing { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + if self.failed { + self.calls_after_failure.set(self.calls_after_failure.get() + 1); + } + self.inner.seek(pos) + } + } + let data = vec![1u8; 4096]; + let assets = [Asset { id: "8", mime: "image/png", data: &data }]; + let calls = std::rc::Rc::new(std::cell::Cell::new(0)); + let out = Failing { inner: Cursor::new(Vec::new()), budget: 1024, failed: false, calls_after_failure: calls.clone() }; + let result = write_to(out, &linked_doc(), "t", None, &assets, &[]); + assert_eq!(calls.get(), 0, "no write, flush or seek reaches the writer after it failed"); + assert!(matches!(result, Err(Error::Io(message)) if message.contains("cancelled"))); +} + +#[test] +fn bytes_supplied_for_a_linked_asset_are_not_written() -> Result<(), Box> { + let assets = [Asset { id: "7", mime: "image/png", data: b"linked bytes" }, Asset { id: "8", mime: "image/png", data: b"kept" }]; + let bytes = save(&linked_doc(), "t", None, &assets, &[])?; + assert_eq!(load::(&bytes)?.assets, [("8".to_owned(), b"kept".to_vec())]); + Ok(()) +} diff --git a/crates/doc-binary/src/fib.rs b/crates/doc-binary/src/fib.rs index 7bb3ec1495..4224f69623 100644 --- a/crates/doc-binary/src/fib.rs +++ b/crates/doc-binary/src/fib.rs @@ -138,7 +138,9 @@ impl Fib { } let w_ident = u16le(0); if w_ident == 0xA5DC { - return Err(DocbinError::NotWord("Word 6.0/95 format, only Word 97-2003 is supported".into())); + // `read` sends Word 6.0/95 streams to `word6` before this FIB is parsed. This keeps any + // other caller from reading one with the Word 97 layout, which it doesn't have. + return Err(DocbinError::NotWord("a Word 6.0/95 file doesn't have the Word 97 FIB layout".into())); } if w_ident != W_IDENT { return Err(DocbinError::NotWord(format!("magic 0x{w_ident:04X}, expected 0x{W_IDENT:04X}"))); diff --git a/crates/doc-binary/src/fkp.rs b/crates/doc-binary/src/fkp.rs index 3de272da26..3a795d4a4f 100644 --- a/crates/doc-binary/src/fkp.rs +++ b/crates/doc-binary/src/fkp.rs @@ -29,6 +29,19 @@ pub(crate) struct Bins { sorted: bool, /// Page number (× 512 = byte offset in the WordDocument stream). pns: Vec, + /// Runs read ahead of time instead of pages (Word 6.0/95, whose FKPs and sprms are another + /// layout, translated by [`crate::word6`]): sorted by `lo`, not overlapping. + translated: Option>, +} + +/// One run of a [`Bins::translated`] table: the FCs `[lo, hi)` it covers, the paragraph style +/// (for PAPX runs) and a Word 97 grpprl. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct TranslatedRun { + pub(crate) lo: u32, + pub(crate) hi: u32, + pub(crate) istd: u16, + pub(crate) grpprl: Vec, } impl Bins { @@ -37,7 +50,7 @@ impl Bins { let fc = fc as usize; let lcb = lcb as usize; if lcb < 4 || !(lcb - 4).is_multiple_of(8) { - return Ok(Bins { fcs: Vec::new(), sorted: true, pns: Vec::new() }); + return Ok(Bins { fcs: Vec::new(), sorted: true, pns: Vec::new(), translated: None }); } let end = fc.checked_add(lcb).ok_or_else(|| DocbinError::Malformed("bin table overflow".into()))?; let plc = table.get(fc..end).ok_or_else(|| DocbinError::Malformed("bin table outside the Table stream".into()))?; @@ -56,7 +69,31 @@ impl Bins { pns.push(at(n + 1 + i).ok_or_else(|| DocbinError::Malformed("truncated bin aPn".into()))? & 0x003F_FFFF); } let sorted = fcs.windows(2).all(|w| w.first() <= w.get(1)); - Ok(Bins { fcs, sorted, pns }) + Ok(Bins { fcs, sorted, pns, translated: None }) + } + + /// A table of runs read ahead of time ([`TranslatedRun`]). Runs are sorted by start; one that + /// overlaps an earlier one (a corrupt file) or covers nothing is dropped. + pub(crate) fn translated(mut runs: Vec) -> Bins { + runs.sort_by_key(|r| r.lo); + let mut kept: Vec = Vec::with_capacity(runs.len()); + for r in runs { + if r.lo < r.hi && kept.last().is_none_or(|last| r.lo >= last.hi) { + kept.push(r); + } + } + Bins { fcs: Vec::new(), sorted: true, pns: Vec::new(), translated: Some(kept) } + } + + /// For a translated table: the run covering `fc`, or the gap `[lo, hi)` between runs that + /// holds it. + fn translated_at(runs: &[TranslatedRun], fc: u32) -> Result<&TranslatedRun, (u32, u32)> { + let i = runs.partition_point(|r| r.lo <= fc); + let prev = i.checked_sub(1).and_then(|i| runs.get(i)); + match prev { + Some(r) if fc < r.hi => Ok(r), + _ => Err((prev.map_or(0, |r| r.hi), runs.get(i).map_or(u32::MAX, |r| r.lo))), + } } /// The page containing `fc`, as a slice of the WordDocument stream, and the FC range @@ -77,13 +114,19 @@ impl Bins { /// The grpprl of the Chpx covering `fc` ([MS-DOC] ChpxFkp: rgfc u32s, rgb offsets ×2, /// crun in the last byte). - pub(crate) fn chpx<'w>(&self, word: &'w [u8], fc: u32) -> &'w [u8] { + pub(crate) fn chpx<'w>(&'w self, word: &'w [u8], fc: u32) -> &'w [u8] { self.chpx_run(word, fc).grpprl } /// [`Bins::chpx`] with the FC range over which the same grpprl is the answer, so a walk /// over consecutive characters looks it up once per run, not once per character. - pub(crate) fn chpx_run<'w>(&self, word: &'w [u8], fc: u32) -> ChpxRun<'w> { + pub(crate) fn chpx_run<'w>(&'w self, word: &'w [u8], fc: u32) -> ChpxRun<'w> { + if let Some(runs) = &self.translated { + return match Self::translated_at(runs, fc) { + Ok(r) => ChpxRun { grpprl: &r.grpprl, lo: r.lo, hi: r.hi }, + Err((lo, hi)) => ChpxRun { grpprl: &[], lo, hi }, + }; + } let none = ChpxRun { grpprl: &[], lo: 1, hi: 0 }; let Some((page, page_lo, page_hi)) = self.page(word, fc) else { return none }; let Some(&crun) = page.get(511) else { return none }; @@ -113,7 +156,13 @@ impl Bins { /// ([MS-DOC] PapxFkp: rgfc u32s — each the FC *following* a paragraph mark —, rgbx BX /// entries (1 offset byte + 12 PHE bytes), crun in the last byte; the PAPX itself is a /// PapxInFkp with the cb/cb' size quirk). Query with the FC of the character after the mark. - pub(crate) fn papx<'w>(&self, word: &'w [u8], fc: u32) -> (u16, &'w [u8]) { + pub(crate) fn papx<'w>(&'w self, word: &'w [u8], fc: u32) -> (u16, &'w [u8]) { + if let Some(runs) = &self.translated { + return match Self::translated_at(runs, fc) { + Ok(r) => (r.istd, &r.grpprl), + Err(_) => (0, &[]), + }; + } let Some((page, _, _)) = self.page(word, fc) else { return (0, &[]) }; let Some(&crun) = page.get(511) else { return (0, &[]) }; // BX is 13 bytes; cap crun at what fits before byte 511. diff --git a/crates/doc-binary/src/lib.rs b/crates/doc-binary/src/lib.rs index 386e753f5b..b2d7f3729a 100644 --- a/crates/doc-binary/src/lib.rs +++ b/crates/doc-binary/src/lib.rs @@ -6,6 +6,9 @@ //! like the other Craft parsers, is lenient by design (unknown structures are skipped, bad numbers //! fall back to defaults) and bounded (stream sizes, piece counts and property counts are //! capped), so hostile input yields an error or a best-effort document, never a panic. +//! +//! Word 6.0/95 files, which that specification does not cover, are read by `word6` from their +//! observed layout: their text, formatting and tables so far. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // The code came from an app whose lints allow this. #![allow(clippy::type_complexity)] @@ -29,6 +32,7 @@ mod sections; mod sprm; mod stsh; mod table; +mod word6; use std::sync::Arc; @@ -220,6 +224,9 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> if word.len() as u64 > MAX_STREAM { return Err(DocbinError::Limit(format!("WordDocument stream is {} bytes", word.len()))); } + if word6::is_word6(&word) { + return read_word6(&comp, &word, max_paragraphs); + } let enc = fib::peek_encryption(&word); // The FIB names the Table stream (0Table or 1Table); fall back to whichever exists, // since files written by other writers sometimes carry the wrong bit. @@ -431,6 +438,55 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> Ok(doc) } +/// Read a Word 6.0/95 file ([`word6`]): its main text, with its character and paragraph +/// formatting and table rows translated to Word 97 sprms, through the same walk as a Word 97 file. +/// Its paragraph styles are read too; character styles and the other stories are not yet, and a +/// section mark reads as a page break. +fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: usize) -> Result { + let fib = word6::Fib6::parse(word)?; + let content = word6::content(word, &fib)?; + let mut doc = Document::new(); + // Word opens these files in compatibility mode 11 too. + doc.settings.compat_mode = 11; + if let Some(core) = metadata::read(comp) { + doc.core = core; + } + doc.body.clear(); + // The paragraph styles, built as for Word 97 files from their translated formatting. + doc.styles = Arc::new(fmt::stylesheet(&content.styles, &content.fonts, stsh::StandardFonts::default())); + let sheet: StyleSheet = StyleSheet::clone(&doc.styles); + // As for Word 97 files: the text read can't exceed twice the stream, nor the absolute ceiling. + let budget = std::cell::Cell::new((word.len() as u64).saturating_mul(2).min(MAX_TOTAL_CHARS)); + let work = Work::new(MAX_WORK); + let paragraphs = ParaBudget { left: std::cell::Cell::new(max_paragraphs), exceeded: std::cell::Cell::new(false) }; + let mut pics = media::Pictures::for_input(word.len()); + let ctx = WalkCtx { + word, + data: &[], + pieces: &content.pieces, + chpx_bins: &content.chpx, + papx_bins: &content.papx, + fonts: &content.fonts, + raw_styles: &content.styles, + sheet: &sheet, + notes: &[], + marks: &[], + drawn: &[], + sect_ends: &[], + budget: &budget, + paragraphs: ¶graphs, + work: &work, + }; + let paras = walk(&ctx, 0, fib.ccp_text, &mut pics); + if paragraphs.exceeded.get() { + return Err(paragraph_limit(max_paragraphs)); + } + doc.body = table::assemble(paras); + doc.ensure_nonempty(); + work.log(); + Ok(doc) +} + fn paragraph_limit(max_paragraphs: usize) -> DocbinError { DocbinError::Limit(format!("the document has more than {max_paragraphs} paragraphs and table cells")) } @@ -648,6 +704,20 @@ fn walk<'a>(ctx: &WalkCtx<'a>, cp_start: u32, cp_end: u32, pics: &mut media::Pic // querying at the mark's own FC finds that paragraph's properties. let fc_mark = ctx.pieces.fc_of_cp(cp).unwrap_or(0); let (istd, papx) = ctx.papx_bins.papx(ctx.word, fc_mark); + // The Prm of the piece holding the mark adds its paragraph sprms after the PAPX's + // ([MS-DOC] §2.4.6.1, step 5), as Word 6/95's fast saves record a paragraph change. + let extra = prm_paragraph_sprms(ctx.pieces.piece_prm(cp), ctx.work); + let combined; + let papx: &[u8] = if extra.is_empty() { + papx + } else { + // Re-framed from its Prls, so that a pad byte at its end can't swallow the + // first appended opcode. + let mut v: Vec = sprm::iter(papx).flat_map(|p| p.op.to_le_bytes().into_iter().chain(p.operand.iter().copied())).collect(); + v.extend_from_slice(&extra); + combined = v; + &combined + }; if let Some(st) = ctx.raw_styles.get(istd as usize).filter(|s| !s.name.is_empty()) { pb.props.style = Some(fmt::style_id(&st.name)); } @@ -991,13 +1061,42 @@ struct FmtState<'a> { /// paragraph style stay the same, so a Prm grpprl (up to 64 KB) is interpreted once per /// formatting change, not once per character (#3692). struct FmtMemo<'a> { - /// The CHPX grpprl, compared by address: it is a slice of the WordDocument stream. + /// The CHPX grpprl, compared by address: a slice of the WordDocument stream, or of a Word 6.0/95 + /// file's translated runs, both of which stay put for the walk. chpx: &'a [u8], prm: u16, style: Option, props: CharProps, } +/// The paragraph and table sprms (sgc 1 and 5) of a piece's Prm, as Prls to append to a +/// paragraph's PAPX: a Prm0's single sprm, or those of the Prm1's grpprl. A Prm1 grpprl is +/// charged to `work`, as for [`apply_prm`]. +fn prm_paragraph_sprms(prm: PrmRef<'_>, work: &Work) -> Vec { + let mut out = Vec::new(); + match prm { + PrmRef::Sprm0 { isprm, val } => { + if let Some(op) = sprm::from_prm0(isprm) + && matches!(Prl { op, operand: &[] }.sgc(), 1 | 5) + { + out.extend_from_slice(&op.to_le_bytes()); + out.push(val); + } + } + PrmRef::Grpprl(Some(g)) => { + if !work.charge(g.len() as u64, Cost::Formatting) { + return out; + } + for prl in sprm::iter(g).filter(|p| matches!(p.sgc(), 1 | 5)) { + out.extend_from_slice(&prl.op.to_le_bytes()); + out.extend_from_slice(prl.operand); + } + } + PrmRef::None | PrmRef::Grpprl(None) => {} + } + out +} + /// Apply a piece's Prm (Prm0 short sprm or Prm1 grpprl) to character properties. A Prm1 /// grpprl is charged to `work`; once that is spent the grpprl is skipped. fn apply_prm(props: &mut CharProps, prm: PrmRef<'_>, fonts: &[String], base: &CharProps, work: &Work) { diff --git a/crates/doc-binary/src/piece.rs b/crates/doc-binary/src/piece.rs index 5f36a8198a..701a4bc67c 100644 --- a/crates/doc-binary/src/piece.rs +++ b/crates/doc-binary/src/piece.rs @@ -1,20 +1,71 @@ //! The piece table ([MS-DOC] `Clx`/`Pcdt`/`PlcPcd`): where every character position lives in //! the WordDocument stream, and how it is encoded. +//! +//! Word 6.0/95 files ([`crate::word6`]) keep the same `Clx` shape, but every piece's text is at a +//! plain byte offset: 8-bit text in the code page of its piece's or run's font (or the document's), +//! or UTF-16 in a file with the FIB's fExtChar flag. -use craft_codepage::cp1252; +use craft_codepage::{code_page_byte, cp1252, is_byte_code_page}; use crate::DocbinError; /// Most pieces any real file has; more means a corrupt `PlcPcd`. const MAX_PIECES: usize = 1_000_000; -/// One piece: text at FcCompressed `fc` (30-bit offset + compression bit). +/// How a piece's characters are stored. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Text { + /// UTF-16LE at `fc`. + Utf16, + /// Windows-1252, one byte per character at `fc / 2` (Word 97 FcCompressed). + Compressed, + /// One byte per character at `fc` itself, in the code page [`PieceTable::code_page_at`] gives + /// that byte (Word 6.0/95). + Bytes, +} + +/// One piece: its text at `fc` (for Word 97, the 30-bit offset of FcCompressed). #[derive(Clone, Copy, Debug)] struct Pcd { fc: u32, - compressed: bool, - /// `Prm`: either a single sprm (Prm0) or an index into the Clx's Prc grpprls (Prm1). + text: Text, + /// `Prm`: either a single sprm (Prm0) or an index into the Clx's Prc grpprls (Prm1). In a Word + /// 6.0/95 table the Prcs hold translated grpprls ([`PieceTable::parse_word6`]), and a Prm0's + /// isprm is already the opcode [MS-DOC]'s isprm table maps. prm: u16, + /// For a Word 6.0/95 [`Text::Bytes`] piece whose Prm names a font: that font's code page, + /// which outranks the runs' ([`PieceTable::code_page_at`]). + code_page: Option, +} + +impl Pcd { + /// The byte offset of the character `step / 2` characters into the piece. `step` is twice + /// the CP offset, so one formula serves all three encodings. + fn fc_at(&self, step: u32) -> Option { + match self.text { + Text::Utf16 => self.fc.checked_add(step), + Text::Compressed => self.fc.checked_add(step)?.checked_div(2), + Text::Bytes => self.fc.checked_add(step / 2), + } + } +} + +/// The code page of the 8-bit text in the byte range `[lo, hi)` of the WordDocument stream. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct CodePageRun { + pub(crate) lo: u32, + pub(crate) hi: u32, + pub(crate) code_page: u16, +} + +/// How a Word 6.0/95 file's text is stored and decoded ([`crate::word6`]). +pub(crate) struct Word6Text { + /// UTF-16 rather than 8-bit (the FIB's fExtChar flag). + pub(crate) wide: bool, + /// The code page of 8-bit text that no piece or run gives one for. + pub(crate) default_code_page: u16, + /// The code page of each byte range, from its run's font (sorted by `lo`, not overlapping). + pub(crate) code_pages: Vec, } /// The parsed piece table plus the grpprls of the Prcs that Prm1 references. @@ -23,11 +74,58 @@ pub(crate) struct PieceTable { cps: Vec, pieces: Vec, prc_grpprls: Vec>, + /// For [`Text::Bytes`] pieces: the code page of each byte range, sorted by `lo`, not + /// overlapping. Bytes outside every range are in `default_code_page`. + code_pages: Vec, + default_code_page: u16, } impl PieceTable { /// Parse the `Clx` at `table[fc .. fc+lcb]`. pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result { + Self::parse_clx(table, fc, lcb, None) + } + + /// Parse a Word 6.0/95 `Clx` at `word[fc .. fc+lcb]`: the Word 97 shape, but every piece's text + /// is at its plain byte offset. `piece_code_page` gives the code page a piece's raw Prm + /// imposes (with the Clx's raw Prc grpprls to look Prm1 indices up in), if any; then each Prc + /// grpprl is replaced by `translate_prc`'s Word 97 sprms, which the walk applies to the piece. + pub(crate) fn parse_word6( + word: &[u8], + fc: u32, + lcb: u32, + text: Word6Text, + piece_code_page: impl Fn(u16, &[Vec]) -> Option, + translate_prc: impl Fn(&[u8]) -> Vec, + ) -> Result { + let mut t = Self::parse_clx(word, fc, lcb, Some(text.wide))?; + if !text.wide { + for p in &mut t.pieces { + p.code_page = piece_code_page(p.prm, &t.prc_grpprls); + } + } + t.prc_grpprls = t.prc_grpprls.iter().map(|g| translate_prc(g)).collect(); + t.code_pages = text.code_pages; + t.default_code_page = text.default_code_page; + Ok(t) + } + + /// One Word 6.0/95 piece: `ccp` characters from byte `fc` on. This covers a file that was not + /// fast-saved, which has no `Clx`. + pub(crate) fn contiguous_word6(fc: u32, ccp: u32, text: Word6Text) -> PieceTable { + let kind = if text.wide { Text::Utf16 } else { Text::Bytes }; + PieceTable { + cps: vec![0, ccp], + pieces: vec![Pcd { fc, text: kind, prm: 0, code_page: None }], + prc_grpprls: Vec::new(), + code_pages: text.code_pages, + default_code_page: text.default_code_page, + } + } + + /// `word6`: `None` for Word 97 and later, `Some(wide)` for a Word 6.0/95 file (whose raw Prms + /// and Prcs are kept for [`PieceTable::parse_word6`]). + fn parse_clx(table: &[u8], fc: u32, lcb: u32, word6: Option) -> Result { let fc = fc as usize; let lcb = lcb as usize; if lcb == 0 { @@ -95,9 +193,26 @@ impl PieceTable { return Err(DocbinError::Malformed("truncated aPcd".into())); }; let prm = plc.get(at + 4..at + 6).map(|b| u16::from_le_bytes([b[0], b[1]])).unwrap_or(0); - pieces.push(Pcd { fc: fc_raw & 0x3FFF_FFFF, compressed: fc_raw & 0x4000_0000 != 0, prm }); + pieces.push(match word6 { + // A plain byte offset, with no compression bit: 8-bit text, or UTF-16 in a file with + // fExtChar. The raw Prm is kept for `parse_word6`. + Some(wide) => Pcd { fc: fc_raw, text: if wide { Text::Utf16 } else { Text::Bytes }, prm, code_page: None }, + None => { + let text = if fc_raw & 0x4000_0000 != 0 { Text::Compressed } else { Text::Utf16 }; + Pcd { fc: fc_raw & 0x3FFF_FFFF, text, prm, code_page: None } + } + }); + } + Ok(PieceTable { cps, pieces, prc_grpprls, code_pages: Vec::new(), default_code_page: 1252 }) + } + + /// The code page of the 8-bit text byte at `fc` (in [`Text::Bytes`] pieces). + fn code_page_at(&self, fc: u32) -> u16 { + let i = self.code_pages.partition_point(|r| r.lo <= fc); + match i.checked_sub(1).and_then(|i| self.code_pages.get(i)) { + Some(r) if fc < r.hi => r.code_page, + _ => self.default_code_page, } - Ok(PieceTable { cps, pieces, prc_grpprls }) } /// The Prls this piece's `Prm` adds. Bit 0 (`fComplex`) discriminates: a Prm0 @@ -133,8 +248,7 @@ impl PieceTable { let p = self.piece_of(cp)?; let i = self.cps.partition_point(|&c| c <= cp).checked_sub(1)?; let cp0 = *self.cps.get(i)?; - let step = cp.checked_sub(cp0)?.checked_mul(2)?; - if p.compressed { p.fc.checked_add(step)?.checked_div(2) } else { p.fc.checked_add(step) } + p.fc_at(cp.checked_sub(cp0)?.checked_mul(2)?) } /// The piece holding `cp`, with the CP range it covers: for every CP in that range the @@ -167,13 +281,24 @@ impl PieceTable { let (Some(p), Some(&cp0)) = (self.pieces.get(i), self.cps.get(i)) else { return Err(u32::MAX) }; let Some(off) = cp.checked_sub(cp0) else { return Err(next) }; let off = off as usize; - if p.compressed { - // 8-bit, Windows-1252, one byte per character, stored at fc/2. - let at = ((p.fc / 2) as usize).checked_add(off); - return match at.and_then(|a| word.get(a)) { - Some(&b) => Ok((cp1252(b), 1)), - None => Err(next), - }; + match p.text { + Text::Compressed => { + // 8-bit, Windows-1252, one byte per character, stored at fc/2. + let at = ((p.fc / 2) as usize).checked_add(off); + return match at.and_then(|a| word.get(a)) { + Some(&b) => Ok((cp1252(b), 1)), + None => Err(next), + }; + } + Text::Bytes => { + // 8-bit, one byte per character at fc, in its run's code page. + let at = (p.fc as usize).checked_add(off); + return match at.and_then(|a| Some((u32::try_from(a).ok()?, *word.get(a)?))) { + Some((a, b)) => Ok((byte_char(p.code_page.unwrap_or_else(|| self.code_page_at(a)), b), 1)), + None => Err(next), + }; + } + Text::Utf16 => {} } // UTF-16LE, one 16-bit unit per character, stored at fc. let unit = |k: usize| -> Option { @@ -207,8 +332,7 @@ impl PieceSpan<'_> { /// [`PieceTable::fc_of_cp`] for a CP inside the span. pub(crate) fn fc_at(&self, cp: u32) -> Option { - let step = cp.checked_sub(self.cp_lo)?.checked_mul(2)?; - if self.pcd.compressed { self.pcd.fc.checked_add(step)?.checked_div(2) } else { self.pcd.fc.checked_add(step) } + self.pcd.fc_at(cp.checked_sub(self.cp_lo)?.checked_mul(2)?) } /// The raw Prm of the piece: two CPs with the same value get the same [`PrmRef`]. @@ -228,3 +352,23 @@ pub(crate) enum PrmRef<'a> { /// Prm1: a grpprl from a Prc (absent if out of range). Grpprl(Option<&'a [u8]>), } + +/// Windows' code page number for symbol fonts (CP_SYMBOL). +pub(crate) const SYMBOL_CODE_PAGE: u16 = 42; + +/// One byte of 8-bit text in `code_page`. The East Asian code pages store a character as a lead +/// and a trail byte, which one CP per byte can't represent, so their bytes above ASCII read as +/// U+FFFD rather than as unrelated Windows-1252 letters. +fn byte_char(code_page: u16, b: u8) -> char { + if code_page == SYMBOL_CODE_PAGE { + // Each character from the space up to its private-use code point, as Word reads a document + // marked as Symbol; control characters (paragraph marks, fields) stay themselves. + if b < 0x20 { char::from(b) } else { char::from_u32(0xF000 + u32::from(b)).unwrap_or('\u{FFFD}') } + } else if is_byte_code_page(code_page) { + code_page_byte(code_page, b) + } else if b.is_ascii() { + char::from(b) + } else { + '\u{FFFD}' + } +} diff --git a/crates/doc-binary/src/tests.rs b/crates/doc-binary/src/tests.rs index 80cef32570..ec56506954 100644 --- a/crates/doc-binary/src/tests.rs +++ b/crates/doc-binary/src/tests.rs @@ -10,6 +10,7 @@ use super::read; mod drawing; mod encrypted; mod metadata; +mod word6; /// Offset in the WordDocument stream where test text pieces are placed (past the FIB). const TEXT_FC: u32 = 0x600; @@ -176,12 +177,15 @@ fn wrong_magic_rejected() { } #[test] -fn word_6_95_rejected() { - let mut fib = fib_bytes(&FibSpec::default()); +fn word_6_95_magic_goes_to_the_word6_reader() { + // A Word 6.0/95 signature is no longer refused: the stream is read as that version (here an + // empty document, since a Word 97 FIB holds no Word 6 text length). The flags are cleared: + // the Word 97 default sets fExtChar, which the Word 6 reader refuses. + let mut fib = fib_bytes(&FibSpec { flags: 0, ..FibSpec::default() }); fib[0] = 0xDC; fib[1] = 0xA5; let f = cfb_file(&[("WordDocument", &fib)]); - assert!(matches!(read(&f), Err(super::DocbinError::NotWord(m)) if m.contains("6.0/95"))); + assert!(read(&f).is_ok()); } #[test] @@ -882,8 +886,6 @@ fn corpus_files_open() { let bytes = std::fs::read(&p).expect("read"); let doc = match super::read(&bytes) { Ok(d) => d, - // Word 6/95 files are a documented, intentional rejection. - Err(super::DocbinError::NotWord(m)) if m.contains("6.0/95") => continue, Err(e) => panic!("{}: {e}", p.display()), }; assert!(!doc.styles.styles.is_empty(), "{}: no styles", p.display()); @@ -2106,6 +2108,29 @@ fn one_section(text: &'static str, sepx: Vec, papx_entries: Vec<(u32, u16, V } } +#[test] +fn piece_prm_paragraph_formatting_applies_to_the_marks_paragraph() { + // [MS-DOC] §2.4.6.1 step 5: the Prm of the piece holding the paragraph mark adds its paragraph + // sprms after the PAPX's. Prm1 -> a Prc with sprmPDxaLeft80 (1440 twips) and sprmPJc80 + // (centred); Prm0 isprm 0x05 (sprmPJc) with operand 2 (right). + let prcs = vec![grpprl(&[(0x840F, &1440i16.to_le_bytes()), (0x2403, &[0x01])])]; + let para = |prm: u16| { + let spec = RichSpec { + text: "Text\r", + styles: vec![(1, 0x0FFF, "Normal", Vec::new(), Vec::new())], + fonts: vec!["Times New Roman"], + chpx_runs: vec![(0, Vec::new())], + papx_entries: vec![(4, 0, grpprl(&[(0x840F, &360i16.to_le_bytes())]))], + }; + let doc = read(&rich_doc_with(&spec, &RichExtra { prcs: prcs.clone(), prm, ..Default::default() })).expect("opens"); + let p = para0(&doc); + (p.props.indent_left, p.props.align) + }; + assert_eq!(para(0x0000), (Some(18.0), None), "no Prm: the PAPX's indent"); + assert_eq!(para(0x0001), (Some(72.0), Some(craft_wordmodel::props::Align::Center)), "Prm1: the Prc's sprms override the PAPX's"); + assert_eq!(para(0x020A), (Some(18.0), Some(craft_wordmodel::props::Align::Right)), "Prm0: sprmPJc right"); +} + #[test] fn piece_prm_character_formatting_applied() { // #458. Bit 0 of a Prm is fComplex ([MS-DOC] §2.9.215/§2.9.216): Prm0 = isprm in bits diff --git a/crates/doc-binary/src/tests/word6.rs b/crates/doc-binary/src/tests/word6.rs new file mode 100644 index 0000000000..fa3f68a515 --- /dev/null +++ b/crates/doc-binary/src/tests/word6.rs @@ -0,0 +1,747 @@ +//! Word 6.0/95 fixtures, built in code. No public specification describes this version; these +//! build the layout observed in real files and described in `crate::word6`. + +use proptest::prelude::*; + +use super::{body_texts, cfb_file}; +use crate::{DocbinError, read}; + +/// Where the text starts: right after the FIB, as in every observed file. +const TEXT_AT: u32 = 0x300; + +/// One stylesheet entry as Word 6/95 stores it. +#[derive(Clone, Copy, Default)] +struct Std<'a> { + /// The built-in style id, or 0x0FFE for a user-defined style. + sti: u16, + /// 1 paragraph, 2 character. + sgc: u16, + /// The base style's index, or 0x0FFF. + base: u16, + name: &'a str, + /// Paragraph sprms (paragraph styles only). + papx: &'a [u8], + /// Character sprms. + chpx: &'a [u8], +} + +/// The stylesheet bytes for `styles`: the 14-byte header (count, fixed-part size 8, …), then per +/// style a size and the entry, or 0 for an empty slot. +fn stylesheet(styles: &[Option]) -> Vec { + let mut v = vec![14u8, 0]; + for w in [styles.len() as u16, 8, 1, 0x4B, 0x0F, 0, 0] { + v.extend_from_slice(&w.to_le_bytes()); + } + for (istd, st) in styles.iter().enumerate() { + let Some(st) = st else { + v.extend_from_slice(&[0, 0]); + continue; + }; + let cupx: u16 = if st.sgc == 1 { 2 } else { 1 }; + let mut e = Vec::new(); + for w in [st.sti, st.sgc | st.base << 4, cupx, 0] { + e.extend_from_slice(&w.to_le_bytes()); + } + e.push(st.name.len() as u8); + e.extend_from_slice(st.name.as_bytes()); + e.push(0); + let upx = |e: &mut Vec, bytes: &[u8]| { + if e.len() % 2 == 1 { + e.push(0); + } + e.extend_from_slice(&(bytes.len() as u16).to_le_bytes()); + e.extend_from_slice(bytes); + }; + if st.sgc == 1 { + let mut papx = (istd as u16).to_le_bytes().to_vec(); + papx.extend_from_slice(st.papx); + upx(&mut e, &papx); + } + upx(&mut e, st.chpx); + v.extend_from_slice(&(e.len() as u16).to_le_bytes()); + v.extend_from_slice(&e); + } + v +} + +/// What a test Word 6.0/95 file holds. Offsets in `runs` and `pieces` are into `text`. +#[derive(Clone, Default)] +struct Doc6<'a> { + nfib: u16, + flags: u16, + /// The stored 8-bit text. + text: &'a [u8], + /// (charset, name) per font index. + fonts: &'a [(u8, &'a str)], + /// The font table's entries as raw bytes instead of `fonts` (the size word is added). + raw_fonts: Option<&'a [u8]>, + /// Contiguous character runs (lo, hi, grpprl), all in one FKP page. + runs: &'a [(u32, u32, &'a [u8])], + /// Contiguous paragraph runs (lo, hi, grpprl), style 0, all in one FKP page. Each covers the + /// paragraph whose mark lies in it. + paras: &'a [(u32, u32, &'a [u8])], + /// For a fast-saved file: (length, offset) per piece, in CP order. + pieces: Option<&'a [(u32, u32)]>, + /// Each piece's Prm (0 when absent or shorter than `pieces`). + prms: &'a [u16], + /// The Clx's Prc grpprls, which a Prm1 indexes. + prcs: &'a [&'a [u8]], + /// The FIB's character set word at 0x14. + chse: u16, + /// The style of each paragraph run (0, Normal, when absent or shorter than `paras`). + para_styles: &'a [u16], + /// The stylesheet: one entry per style index, `None` for an empty slot. + styles: &'a [Option>], + /// The main text's length in characters, when it isn't the stored bytes' (16-bit text). + ccp: Option, +} + +fn put16(v: &mut [u8], at: usize, x: u16) { + v[at..at + 2].copy_from_slice(&x.to_le_bytes()); +} + +fn put32(v: &mut [u8], at: usize, x: u32) { + v[at..at + 4].copy_from_slice(&x.to_le_bytes()); +} + +/// Append one FKP page for `runs` and its bin table, and return the bin table's (fc, lcb). A +/// character page has a 1-byte entry per run and CHPXs (byte count + grpprl); a paragraph page +/// has 7-byte entries and PAPXs (word count + style 0 + grpprl padded to whole words). +fn fkp(w: &mut Vec, runs: &[(u32, u32, &[u8])], papx: bool, istds: &[u16]) -> (u32, u32) { + let (Some(first), Some(last)) = (runs.first(), runs.last()) else { return (0, 0) }; + w.resize(w.len().div_ceil(512) * 512, 0); + let pn = (w.len() / 512) as u16; + let crun = runs.len(); + let entry = if papx { 7 } else { 1 }; + let mut page = [0u8; 512]; + for (k, (lo, _, _)) in runs.iter().enumerate() { + put32(&mut page, 4 * k, TEXT_AT + lo); + } + put32(&mut page, 4 * crun, TEXT_AT + last.1); + // Records from the end of the page down, each at an even offset. + let mut top = 511usize; + for (k, (_, _, g)) in runs.iter().enumerate() { + let body: Vec = if papx { + let mut b = istds.get(k).copied().unwrap_or(0).to_le_bytes().to_vec(); + b.extend_from_slice(g); + if b.len() % 2 == 1 { + b.push(0); + } + b + } else if g.is_empty() { + continue; + } else { + g.to_vec() + }; + let at = (top - 1 - body.len()) & !1; + page[at] = if papx { (body.len() / 2) as u8 } else { body.len() as u8 }; + page[at + 1..at + 1 + body.len()].copy_from_slice(&body); + page[4 * (crun + 1) + entry * k] = (at / 2) as u8; + top = at; + } + page[511] = crun as u8; + w.extend_from_slice(&page); + let mut bte = Vec::new(); + bte.extend_from_slice(&(TEXT_AT + first.0).to_le_bytes()); + bte.extend_from_slice(&(TEXT_AT + last.1).to_le_bytes()); + bte.extend_from_slice(&pn.to_le_bytes()); + let at = w.len() as u32; + w.extend_from_slice(&bte); + (at, bte.len() as u32) +} + +/// The WordDocument stream: FIB, text, then the FKP pages, font table and piece table. +fn word_stream(d: &Doc6) -> Vec { + let mut w = vec![0u8; TEXT_AT as usize]; + w.extend_from_slice(d.text); + let ccp = match (d.ccp, d.pieces) { + (Some(ccp), _) => ccp, + (None, pieces) => match pieces { + Some(p) => p.iter().map(|(len, _)| len).sum(), + None => d.text.len() as u32, + }, + }; + let mut pairs: Vec<(usize, u32, u32)> = Vec::new(); + for (pair, runs, papx) in [(12, d.runs, false), (13, d.paras, true)] { + let (fc, lcb) = fkp(&mut w, runs, papx, d.para_styles); + if lcb > 0 { + pairs.push((pair, fc, lcb)); + } + } + if !d.styles.is_empty() { + let st = stylesheet(d.styles); + pairs.push((1, w.len() as u32, st.len() as u32)); + w.extend_from_slice(&st); + } + if !d.fonts.is_empty() || d.raw_fonts.is_some() { + let mut ffn = vec![0u8, 0]; + ffn.extend_from_slice(d.raw_fonts.unwrap_or_default()); + for (charset, name) in d.fonts { + let mut e = vec![0u8, 0x16, 0x90, 0x01, *charset, 0x00]; + e.extend_from_slice(name.as_bytes()); + e.push(0); + e[0] = (e.len() - 1) as u8; + ffn.extend_from_slice(&e); + } + let size = ffn.len() as u16; + put16(&mut ffn, 0, size); + pairs.push((15, w.len() as u32, ffn.len() as u32)); + w.extend_from_slice(&ffn); + } + if let Some(pieces) = d.pieces { + let mut plc = Vec::new(); + let mut cp = 0u32; + plc.extend_from_slice(&cp.to_le_bytes()); + for (len, _) in pieces { + cp += len; + plc.extend_from_slice(&cp.to_le_bytes()); + } + for (i, (_, off)) in pieces.iter().enumerate() { + plc.extend_from_slice(&[0, 0]); + plc.extend_from_slice(&(TEXT_AT + off).to_le_bytes()); + plc.extend_from_slice(&d.prms.get(i).copied().unwrap_or(0).to_le_bytes()); + } + let mut clx = Vec::new(); + for g in d.prcs { + clx.push(0x01); + clx.extend_from_slice(&(g.len() as u16).to_le_bytes()); + clx.extend_from_slice(g); + } + clx.push(0x02); + clx.extend_from_slice(&(plc.len() as u32).to_le_bytes()); + clx.extend_from_slice(&plc); + pairs.push((33, w.len() as u32, clx.len() as u32)); + w.extend_from_slice(&clx); + } + put16(&mut w, 0x00, 0xA5DC); + put16(&mut w, 0x02, if d.nfib == 0 { 0x0065 } else { d.nfib }); + put16(&mut w, 0x06, 0x0409); + put16(&mut w, 0x0A, d.flags | if d.pieces.is_some() { 0x0004 } else { 0 }); + put16(&mut w, 0x0C, 0x0065); + put16(&mut w, 0x14, d.chse); + put32(&mut w, 0x18, TEXT_AT); + put32(&mut w, 0x1C, TEXT_AT + d.text.len() as u32); + let len = w.len() as u32; + put32(&mut w, 0x20, len); + put32(&mut w, 0x34, ccp); + for (i, fc, lcb) in pairs { + put32(&mut w, 0x58 + i * 8, fc); + put32(&mut w, 0x58 + i * 8 + 4, lcb); + } + w +} + +/// A Word 6.0/95 file holding `d`: the WordDocument stream only, as the real ones have no Table +/// stream. +fn word6_file(d: &Doc6) -> Vec { + cfb_file(&[("WordDocument", &word_stream(d))]) +} + +fn texts(d: &Doc6) -> Vec { + body_texts(&read(&word6_file(d)).expect("a Word 6.0/95 file opens")) +} + +/// Fonts 0 (Western) and 1 (Cyrillic, charset 204), as the Russian files have. +const FONTS: &[(u8, &str)] = &[(0, "Times New Roman"), (204, "Times New Roman Cyr")]; + +#[test] +fn word_6_and_95_files_open_as_paragraphs() { + for nfib in [0x0065, 0x0068] { + let d = Doc6 { nfib, text: b"Hello\rWorld\r", ..Default::default() }; + assert_eq!(texts(&d), ["Hello", "World"], "nFib 0x{nfib:04X}"); + } +} + +#[test] +fn fast_saved_text_follows_the_piece_table() { + // Stored out of order; the pieces' fcs are plain byte offsets (Word 97 would halve them). + let d = Doc6 { text: b"World\rHello\r", pieces: Some(&[(6, 6), (6, 0)]), ..Default::default() }; + assert_eq!(texts(&d), ["Hello", "World"]); +} + +#[test] +fn fast_saved_file_without_a_piece_table_is_malformed() { + let d = Doc6 { flags: 0x0004, text: b"Hello\r", ..Default::default() }; + assert!(matches!(read(&word6_file(&d)), Err(DocbinError::Malformed(_)))); +} + +#[test] +fn a_runs_font_charset_chooses_its_code_page() { + // "Da " in font 0, then 0xC4 0xE0 ("Да" in Windows-1251) in the Cyrillic font 1. + let text = b"Da \xC4\xE0\r"; + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[]), (3, 5, &[0x5D, 0x01, 0x00]), (5, 6, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Da Да"]); +} + +/// Text in an East Asian code page (a Japanese font, charset 128: Shift-JIS) is refused, not +/// read a byte at a time into replacement characters (review of wordcraft#6345). +#[test] +fn east_asian_text_is_refused_not_lost() { + let fonts: &[(u8, &str)] = &[(0, "Times New Roman"), (128, "MS Mincho")]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text: b"\x93\xfa\r", fonts, runs, ..Default::default() }; + assert!(matches!(read(&word6_file(&d)), Err(DocbinError::NotWord(e)) if e.contains("East Asian"))); + // The same file in a Western font still opens. + let d = Doc6 { text: b"\x93\xfa\r", fonts, runs: &[], ..Default::default() }; + assert_eq!(texts(&d).len(), 1); +} + +#[test] +fn the_font_sprm_is_found_after_other_sprms() { + // As in real files: bold-like toggles, a size, a picture anchor's length-prefixed sprm. + let text = b"\xC4\xE0\r"; + for g in [&[0x55, 0x81, 0x63, 0x18, 0x00, 0x5D, 0x01, 0x00][..], &[0x75, 0x01, 0x44, 0x04, 0, 0, 0, 0, 0x5D, 0x01, 0x00][..]] { + let runs: &[(u32, u32, &[u8])] = &[(0, 2, g), (2, 3, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"], "grpprl {g:02X?}"); + } +} + +#[test] +fn the_last_font_sprm_of_a_run_chooses_its_code_page() { + // Font 0, then font 1 (Cyrillic): the later sprm is the one the formatting applies. + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x00, 0x00, 0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); +} + +#[test] +fn an_unknown_sprm_leaves_font_0() { + // 0x99 has no known operand length, so the rest can't be framed: font 0 (Windows-1252). + let text = b"\xC4\xE0\r"; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x99, 0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn the_toggle_sprms_before_the_font_are_framed() { + // 0x57 (strike, a one-byte toggle in [MS-DOC]'s Prm0 isprm table) before the font sprm: the + // font must still be found, or the Cyrillic text reads as Windows-1252. + let text = b"\xC4\xE0\r"; + for op in [0x57, 0x58, 0x59, 0x5C] { + let g = [op, 0x01, 0x5D, 0x01, 0x00]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &g), (2, 3, &[])]; + let d = Doc6 { text, fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"], "opcode 0x{op:02X}"); + } +} + +#[test] +fn a_font_entry_too_short_for_its_charset_ends_the_font_table() { + // Entry 0 says it is 3 bytes long, which can't hold the charset at offset 4. The bytes after + // it (the next entry, whose flags byte is 0xCC) must not be read as font 0's charset. + let raw: &[u8] = &[0x02, 0x16, 0x90, 0x05, 0xCC, 0x90, 0x01, 0xCC, 0x00, b'X', 0]; + let d = Doc6 { text: b"\xC4\xE0\r", raw_fonts: Some(raw), runs: &[(0, 3, &[])], ..Default::default() }; + assert_eq!(texts(&d), ["Äà"], "font 0 has no charset: Windows-1252"); +} + +#[test] +fn a_bin_table_naming_one_page_many_times_reads_it_once() { + // A hostile bin table: 1,000,000 entries, all naming one page of 50 Cyrillic runs. The text still + // reads right; that the page is read once is pinned in `word6::tests`. + let text: Vec = std::iter::repeat_n(0xC4u8, 50).chain(*b"\r").collect(); + let g: &[u8] = &[0x5D, 0x01, 0x00]; + let runs: Vec<(u32, u32, &[u8])> = (0..50).map(|i| (i, i + 1, g)).chain([(50, 51, &[][..])]).collect(); + let mut w = word_stream(&Doc6 { text: &text, fonts: FONTS, runs: &runs, ..Default::default() }); + let u32_at = |w: &[u8], at: usize| u32::from_le_bytes([w[at], w[at + 1], w[at + 2], w[at + 3]]); + let bte_fc = u32_at(&w, 0x58 + 12 * 8) as usize; + let pn = u16::from_le_bytes([w[bte_fc + 8], w[bte_fc + 9]]); + let n = 1_000_000usize; + let mut bte = Vec::with_capacity(4 * (n + 1) + 2 * n); + bte.extend_from_slice(&TEXT_AT.to_le_bytes()); + for _ in 0..n { + bte.extend_from_slice(&(TEXT_AT + 51).to_le_bytes()); + } + for _ in 0..n { + bte.extend_from_slice(&pn.to_le_bytes()); + } + let at = w.len() as u32; + w.extend_from_slice(&bte); + put32(&mut w, 0x58 + 12 * 8, at); + put32(&mut w, 0x58 + 12 * 8 + 4, bte.len() as u32); + let doc = read(&cfb_file(&[("WordDocument", &w)])).expect("opens"); + assert_eq!(body_texts(&doc), ["Д".repeat(50)]); +} + +/// `s` as UTF-16LE bytes. +fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +#[test] +fn a_file_with_extended_characters_holds_utf16_text() { + // fExtChar (0x1000): Word reads the text as 16-bit units. + let text = utf16("Да ok\r"); + let d = Doc6 { flags: 0x1000, text: &text, ccp: Some(6), ..Default::default() }; + assert_eq!(texts(&d), ["Да ok"]); +} + +#[test] +fn utf16_text_stops_at_the_end_of_its_bytes() { + // Word reads no more 16-bit characters than the text's byte range (0x18..0x1C) holds, even + // when the character count says more. + let text = utf16("Hi\r"); + let d = Doc6 { flags: 0x1000, text: &text, ccp: Some(50), ..Default::default() }; + assert_eq!(texts(&d), ["Hi"]); +} + +#[test] +fn text_stops_at_the_end_of_its_bytes() { + // The same for 8-bit text: Word read 19 characters of a file whose count said 40. The font + // table after the text must not be read as body text. + let d = Doc6 { text: b"Hi\r", ccp: Some(50), fonts: FONTS, ..Default::default() }; + assert_eq!(texts(&d), ["Hi"]); +} + +#[test] +fn fast_saved_utf16_pieces_are_at_plain_byte_offsets() { + let text = utf16("World\rHello\r"); + let d = Doc6 { flags: 0x1000, text: &text, pieces: Some(&[(6, 12), (6, 0)]), ..Default::default() }; + assert_eq!(texts(&d), ["Hello", "World"]); +} + +#[test] +fn a_macintosh_document_reads_as_mac_roman() { + // FIB 0x14 = 0x0100: byte 0x8E is "é" (Mac Roman), not "Ž" (Windows-1252), even in a run whose + // font is Cyrillic. + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { chse: 0x0100, text: b"H\x8E\r", fonts: FONTS, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Hé"]); +} + +#[test] +fn a_symbol_document_maps_characters_to_private_use() { + // FIB 0x14 = 0x0002: every character from the space up is U+F000 + byte; marks stay marks. + let d = Doc6 { chse: 0x0002, text: b"Hi\x8E\rA\r", ..Default::default() }; + assert_eq!(texts(&d), ["\u{F048}\u{F069}\u{F08E}", "\u{F041}"]); +} + +#[test] +fn another_character_set_leaves_only_ascii_readable() { + let d = Doc6 { chse: 0x0001, text: b"H\x8Ei\r", ..Default::default() }; + assert_eq!(texts(&d), ["H\u{FFFD}i"]); +} + +#[test] +fn a_prm_on_the_marks_piece_formats_its_paragraph() { + // As Word 95 fast-saves a 1" left indent on the first paragraph: the piece holding its mark + // has Prm1 -> Prc `11 a0 05` (left indent 1440), and its PAPX says nothing. Word shows 72 pt; + // the second paragraph keeps none. + let text = b"First\rSecond\r"; + let pieces: &[(u32, u32)] = &[(5, 0), (1, 5), (7, 6)]; + let d = Doc6 { text, pieces: Some(pieces), prms: &[0, 0x0001], prcs: &[&[0x11, 0xA0, 0x05]], ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + let paras: Vec<_> = doc.body.iter().filter_map(|b| b.as_para()).collect(); + assert_eq!(paras.iter().map(|p| p.text.as_str()).collect::>(), ["First", "Second"]); + assert_eq!((paras[0].props.indent_left, paras[1].props.indent_left), (Some(72.0), None)); +} + +#[test] +fn a_pieces_prm_formats_its_text() { + // As Word 95 fast-saves formatting: piece 0 has Prm1 -> a Prc setting font 1 and bold, which + // its character run doesn't. Piece 0 shows in font 1, bold (and decodes in its code page); + // piece 1 keeps the run's plain formatting. + let text = b"\xC4\xE0\xC4\xE0\r"; + let d = + Doc6 { text, fonts: FONTS, pieces: Some(&[(2, 0), (3, 2)]), prms: &[0x0001], prcs: &[&[0x5D, 0x01, 0x00, 0x55, 0x01]], ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + let p = first_para(&doc); + assert_eq!(p.text, "ДаÄà"); + let first = &p.runs.first().expect("a run").props; + assert_eq!((first.font.as_deref(), first.bold), (Some("Times New Roman Cyr"), Some(true))); + let last = &p.runs.last().expect("a run").props; + assert_eq!((last.font.as_deref(), last.bold), (None, None)); +} + +#[test] +fn a_font_in_a_pieces_prm_chooses_its_code_page() { + // As Word 95 fast-saves a font change: piece 0 ("\xC4\xE0") has Prm1 -> Prc 0 = sprm 0x5D font 1 + // (Cyrillic), while its character run names no font. Piece 1 keeps the run's font 0. + let text = b"\xC4\xE0\xC4\xE0\r"; + let d = Doc6 { text, fonts: FONTS, pieces: Some(&[(2, 0), (3, 2)]), prms: &[0x0001], prcs: &[&[0x5D, 0x01, 0x00]], ..Default::default() }; + assert_eq!(texts(&d), ["ДаÄà"]); +} + +#[test] +fn a_prm_index_past_the_prcs_is_ignored() { + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, pieces: Some(&[(3, 0)]), prms: &[0x0011], prcs: &[&[0x5D, 0x01, 0x00]], ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn password_protected_files_are_refused() { + let d = Doc6 { flags: 0x0100, text: b"secret\r", ..Default::default() }; + assert!(matches!(read(&word6_file(&d)), Err(DocbinError::Encryption(_)))); +} + +/// The first paragraph of `doc`'s body. +fn first_para(doc: &craft_wordmodel::Document) -> &craft_wordmodel::para::Paragraph { + doc.body.iter().find_map(|b| b.as_para()).expect("a paragraph") +} + +#[test] +fn character_formatting_is_read() { + // Bold on, italic as the opposite of the (unread, so plain) style, 14 pt, red, single + // underline, font 2: the Word 6 opcodes as observed. + let g: &[u8] = &[0x55, 0x01, 0x56, 0x81, 0x63, 0x1C, 0x00, 0x62, 0x06, 0x5E, 0x01, 0x5D, 0x02, 0x00]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, g), (2, 3, &[])]; + let fonts = &[(0, "Times New Roman"), (2, "Symbol"), (0, "Arial")]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\r", fonts, runs, ..Default::default() })).expect("opens"); + let p = first_para(&doc); + let c = &p.runs.first().expect("a run").props; + assert_eq!((c.bold, c.italic, c.size), (Some(true), Some(true), Some(14.0))); + assert_eq!(c.color, Some(craft_wordmodel::props::TextColor::Rgb(craft_wordmodel::props::Rgb(0xFF, 0, 0)))); + assert_eq!(c.underline, Some(craft_wordmodel::props::Underline::Single)); + assert_eq!(c.font.as_deref(), Some("Arial")); +} + +#[test] +fn unseen_operand_values_are_left_unread() { + // Underline 3 and "multiple" line spacing were never seen in a real file, so they aren't + // guessed at. + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[0x5E, 0x03])]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, &[0x14, 0xF0, 0x00, 0x01, 0x00])]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\r", runs, paras, ..Default::default() })).expect("opens"); + let p = first_para(&doc); + assert_eq!(p.runs.first().and_then(|r| r.props.underline), None); + assert_eq!(p.props.line_spacing, None); +} + +#[test] +fn an_unseen_alignment_value_is_left_unread() { + // Only 0-3 were seen; 4 would otherwise become "distribute" and 0xFF "left". + for jc in [0x04u8, 0xFF] { + let g = [0x05, jc]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, &g)]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\r", paras, ..Default::default() })).expect("opens"); + assert_eq!(first_para(&doc).props.align, None, "jc {jc:#04x}"); + } +} + +#[test] +fn paragraph_formatting_is_read() { + // Justified, 0.5" left and 0.25" right indents, a 0.5" hanging first line, at least 27 pt. + let g: &[u8] = &[0x05, 0x03, 0x11, 0xD0, 0x02, 0x10, 0x68, 0x01, 0x13, 0x30, 0xFD, 0x14, 0x1C, 0x02, 0x00, 0x00]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, g), (3, 6, &[0x05, 0x01])]; + let doc = read(&word6_file(&Doc6 { text: b"Hi\rHo\r", paras, ..Default::default() })).expect("opens"); + let ps: Vec<_> = doc.body.iter().filter_map(|b| b.as_para()).collect(); + let p = &ps[0].props; + assert_eq!(p.align, Some(craft_wordmodel::props::Align::Justify)); + assert_eq!((p.indent_left, p.indent_right, p.indent_first), (Some(36.0), Some(18.0), Some(-36.0))); + assert_eq!(p.line_spacing, Some(craft_wordmodel::props::LineSpacing::AtLeast(27.0))); + assert_eq!(ps[1].props.align, Some(craft_wordmodel::props::Align::Center)); +} + +/// A Word 6 table definition sprm (0xBE): the cell edges, then a 10-byte descriptor per cell +/// whose first word holds the merge flags. +fn def_table(edges: &[i16], rgfs: &[u16]) -> Vec { + let mut rest = vec![rgfs.len() as u8]; + for e in edges { + rest.extend_from_slice(&e.to_le_bytes()); + } + for r in rgfs { + rest.extend_from_slice(&r.to_le_bytes()); + rest.extend_from_slice(&[0; 8]); + } + let mut v = vec![0xBE]; + v.extend_from_slice(&((rest.len() + 1) as u16).to_le_bytes()); + v.extend_from_slice(&rest); + v +} + +/// The rows of the first table in `doc`'s body, each as its cells' texts. +fn table_rows(doc: &craft_wordmodel::Document) -> Vec> { + let t = doc.body.iter().find_map(|b| match b.as_ref() { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }); + let t = t.expect("a table"); + t.rows + .iter() + .map(|r| r.cells.iter().map(|c| c.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::>().join("|")).collect()) + .collect() +} + +#[test] +fn table_rows_and_merged_cells_are_read() { + // Row 1: "A", "B". Row 2: "C" merged across both cells. In-table marks carry 0x18, the row + // ends 0x18, 0x19 and the table definition. + let text = b"A\x07B\x07\x07C\x07\x07\x07after\r"; + let mut row1 = vec![0x18, 1, 0x19, 1]; + row1.extend(def_table(&[0, 1440, 2880], &[0, 0])); + let mut row2 = vec![0x18, 1, 0x19, 1]; + row2.extend(def_table(&[0, 1440, 2880], &[0x0001, 0x0002])); + let cell: &[u8] = &[0x18, 1]; + let paras: &[(u32, u32, &[u8])] = &[(0, 2, cell), (2, 4, cell), (4, 5, &row1), (5, 7, cell), (7, 8, cell), (8, 9, &row2), (9, 15, &[])]; + let doc = read(&word6_file(&Doc6 { text, paras, ..Default::default() })).expect("opens"); + assert_eq!(table_rows(&doc), [vec!["A", "B"], vec!["C"]]); + assert_eq!(body_texts(&doc), ["after"], "the paragraph after the table stays outside it"); +} + +#[test] +fn several_merges_in_one_row_each_keep_their_cells() { + // Five cells merged as [A B] [C] [D E]: the second merge must not be shifted by the first. + let text = b"A\x07B\x07C\x07D\x07E\x07\x07"; + let mut row = vec![0x18, 1, 0x19, 1]; + row.extend(def_table(&[0, 100, 200, 300, 400, 500], &[0x0001, 0x0002, 0x0000, 0x0001, 0x0002])); + let cell: &[u8] = &[0x18, 1]; + let paras: &[(u32, u32, &[u8])] = &[(0, 2, cell), (2, 4, cell), (4, 6, cell), (6, 8, cell), (8, 10, cell), (10, 11, &row)]; + let doc = read(&word6_file(&Doc6 { text, paras, ..Default::default() })).expect("opens"); + assert_eq!(table_rows(&doc), [vec!["A|B", "C", "D|E"]]); +} + +#[test] +fn a_field_shows_its_cached_result() { + let d = Doc6 { text: b"Date \x13DATE \x1412/12/97\x15\r", ..Default::default() }; + let text = read(&word6_file(&d)).expect("opens").plain_text(craft_wordmodel::StoryRef::Body); + assert!(text.contains("Date 12/12/97"), "{text:?}"); + assert!(!text.contains("DATE"), "{text:?}"); +} + +/// A fixture's paragraph styles: Normal, an empty slot, then "Mine" (user-defined, centred, bold, on +/// Normal) and "Heading" stored under a local name with sti 1. +const STYLES: &[Option] = &[ + Some(Std { sti: 0, sgc: 1, base: 0x0FFF, name: "Standard", papx: &[], chpx: &[0x61, 0x09, 0x04] }), + None, + Some(Std { sti: 0x0FFE, sgc: 1, base: 0, name: "Mine", papx: &[0x05, 0x01], chpx: &[0x55, 0x01] }), + Some(Std { sti: 1, sgc: 1, base: 0, name: "Überschrift 1", papx: &[0x08, 0x01], chpx: &[0x55, 0x81, 0x63, 0x20, 0x00] }), +]; + +/// Each paragraph's style name, through the document's style sheet. +fn style_names(doc: &craft_wordmodel::Document) -> Vec { + doc.body + .iter() + .filter_map(|b| b.as_para()) + .map(|p| p.props.style.as_deref().and_then(|id| doc.styles.get(id)).map_or(String::new(), |s| s.name.clone())) + .collect() +} + +#[test] +fn paragraphs_take_their_styles() { + let paras: &[(u32, u32, &[u8])] = &[(0, 2, &[]), (2, 4, &[]), (4, 6, &[])]; + let d = Doc6 { text: b"A\rB\rC\r", paras, para_styles: &[0, 2, 3], styles: STYLES, ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + // A built-in style goes by its built-in name, whatever the file stores (as in Word). + assert_eq!(style_names(&doc), ["Normal", "Mine", "Heading 1"]); +} + +#[test] +fn styles_carry_their_formatting_and_base() { + let d = Doc6 { text: b"A\r", styles: STYLES, ..Default::default() }; + let doc = read(&word6_file(&d)).expect("opens"); + let mine = doc.styles.styles.iter().find(|s| s.name == "Mine").expect("Mine"); + assert_eq!(mine.para.align, Some(craft_wordmodel::props::Align::Center)); + assert_eq!(mine.chr.bold, Some(true)); + assert_eq!(mine.based_on.as_deref().and_then(|id| doc.styles.get(id)).map(|s| s.name.as_str()), Some("Normal")); + let heading = doc.styles.styles.iter().find(|s| s.name == "Heading 1").expect("Heading 1"); + assert_eq!((heading.para.keep_next, heading.chr.size), (Some(true), Some(16.0))); +} + +#[test] +fn bulleted_styles_frame_past_their_numbering() { + // 0x0D (1 byte) and 0x0C (a count byte and its bytes) before the indents, as in the corpus. + let mut papx = vec![0x05, 0x03, 0x0D, 0x0B, 0x11, 0x1C, 0x01, 0x13, 0xE4, 0xFE, 0x0C, 4, 0xFF, 0x01, 0x00, 0x08]; + papx.extend_from_slice(&[0x0E, 0x01, 0x2C, 0x00, 0x1D, 0x60, 0x1A, 0xF8, 0xFF, 0x25, 0x02, 0x10, 0x68, 0x01]); + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", papx: &papx, ..Default::default() })]; + let doc = read(&word6_file(&Doc6 { text: b"A\r", styles, ..Default::default() })).expect("opens"); + let normal = doc.styles.get("Normal").expect("Normal"); + assert_eq!((normal.para.indent_left, normal.para.indent_first, normal.para.indent_right), (Some(14.2), Some(-14.2), Some(18.0))); +} + +#[test] +fn a_runs_language_or_its_styles_chooses_the_code_page_without_a_font() { + // No font named anywhere: the style's language decides (Russian -> Windows-1251), as in Word. + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x19, 0x04], ..Default::default() })]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, styles, ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); + // The run's own language outranks the style's. + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[0x61, 0x09, 0x04])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, styles, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn font_0_is_not_a_fallback() { + // Font 0 is Cyrillic, but nothing names it and the style's language is English: Word reads + // Windows-1252. + let fonts = &[(204, "Times New Roman Cyr"), (0, "Arial")]; + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x09, 0x04], ..Default::default() })]; + // A character run that names no font (where the reader used to take font 0). + let runs: &[(u32, u32, &[u8])] = &[(0, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts, styles, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Äà"]); +} + +#[test] +fn a_font_named_in_the_style_chooses_the_code_page() { + // The base style names the Cyrillic font 1; the run and its own style name none. + let styles = &[ + Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x5D, 0x01, 0x00], ..Default::default() }), + Some(Std { sti: 0x0FFE, sgc: 1, base: 0, name: "Child", ..Default::default() }), + ]; + let paras: &[(u32, u32, &[u8])] = &[(0, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts: FONTS, styles, paras, para_styles: &[1], ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); +} + +#[test] +fn an_ansi_font_leaves_the_code_page_to_the_language() { + // Arial (ANSI) named on the run, the style's language Russian: Word reads Cyrillic. + let fonts = &[(0, "Times New Roman"), (0, "Arial")]; + let styles = &[Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x19, 0x04], ..Default::default() })]; + let runs: &[(u32, u32, &[u8])] = &[(0, 2, &[0x5D, 0x01, 0x00]), (2, 3, &[])]; + let d = Doc6 { text: b"\xC4\xE0\r", fonts, styles, runs, ..Default::default() }; + assert_eq!(texts(&d), ["Да"]); +} + +/// A fixture with every structure read: runs, fonts and a piece table. +fn full_stream() -> Vec { + let runs: &[(u32, u32, &[u8])] = &[(0, 6, &[0x55, 0x81]), (6, 9, &[0x5D, 0x01, 0x00]), (9, 12, &[])]; + let styles = &[ + Some(Std { sgc: 1, base: 0x0FFF, name: "Normal", chpx: &[0x61, 0x09, 0x04], ..Default::default() }), + None, + Some(Std { sti: 0x0FFE, sgc: 1, base: 0, name: "Mine", papx: &[0x05, 0x01], chpx: &[0x55, 0x01] }), + ]; + let paras: &[(u32, u32, &[u8])] = &[(0, 6, &[]), (6, 12, &[])]; + word_stream(&Doc6 { + text: b"Hello\r\xC4\xE0\rx\r\r", + fonts: FONTS, + runs, + paras, + para_styles: &[2, 0], + styles, + pieces: Some(&[(6, 0), (6, 6)]), + ..Default::default() + }) +} + +#[test] +fn the_full_fixture_reads() { + let f = cfb_file(&[("WordDocument", &full_stream())]); + let doc = read(&f).expect("opens"); + assert_eq!(body_texts(&doc), ["Hello", "Да", "x", ""]); + assert_eq!(style_names(&doc)[0], "Mine"); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn corrupt_word6_streams_never_panic(edits in proptest::collection::vec((0..0x700usize, any::()), 1..16)) { + let mut w = full_stream(); + for (at, b) in edits { + if let Some(x) = w.get_mut(at) { + *x = b; + } + } + let _ = read(&cfb_file(&[("WordDocument", &w)])); + } + + #[test] + fn truncated_word6_streams_never_panic(n in 0..0x700usize) { + let w = full_stream(); + let _ = read(&cfb_file(&[("WordDocument", &w[..n.min(w.len())])])); + } +} diff --git a/crates/doc-binary/src/word6.rs b/crates/doc-binary/src/word6.rs new file mode 100644 index 0000000000..e9fab2d740 --- /dev/null +++ b/crates/doc-binary/src/word6.rs @@ -0,0 +1,842 @@ +//! Word 6.0 and Word 95 `.doc` files (`wIdent` 0xA5DC, `nFib` 0x0065 and 0x0068). +//! +//! No public specification describes this version: [MS-DOC] covers Word 97 and later. Everything +//! here is observed, from the layout of real files checked against what Word shows when it opens +//! them (its text through COM, its formatting in the `.docx` Word saves from them), plus the Word +//! 97 structures in [MS-DOC] that these files visibly share. Nothing else is assumed. +//! +//! What is read: the main text, its paragraphs and fields, the code page of each run, the +//! character and paragraph formatting listed below, table rows, and the paragraph styles (with +//! their formatting). Character styles, sections, headers and footers, notes, pictures, borders, +//! shading and tabs are not read yet. +//! +//! The layout as observed: +//! +//! - A compound file with a `WordDocument` stream and **no Table stream**: the structures that +//! Word 97 keeps in `0Table`/`1Table` live in the WordDocument stream itself. +//! - The FIB is one fixed block. The flags at 0x0A have the Word 97 meaning for bit 2 (fast-saved, +//! set exactly in the files that carry a piece table) and, as far as can be told, bit 8 +//! (encrypted). The text starts at the u32 at 0x18, and the main text's length in characters is +//! the u32 at 0x34. +//! - From 0x58, (u32 fc, u32 lcb) pairs, in the order of Word 97's `FibRgFcLcb97`. Index 12 is the +//! character bin table, 13 the paragraph bin table, 15 the font table and 33 the piece table. +//! - Text is one byte per character, in the code page of the font of its run. The FIB's language +//! does not choose it: files marked English hold Russian and Czech text that Word shows as such. +//! - Both bin tables hold 2-byte page numbers (Word 97: 4 bytes). The FKP pages have the Word 97 +//! layout, except that a paragraph page's entries are 7 bytes (an offset byte and 6 more; Word +//! 97: 13), and a PAPX is a count of 2-byte words followed by exactly that many words: the +//! 2-byte style index, then the grpprl (padded with one 0 byte to whole words). +//! - Sprms have **1-byte opcodes**. Those with a 1-byte operand match the opcodes [MS-DOC]'s +//! `Prm0` table lists for the same properties (bold 0x55, colour 0x62, in-table 0x18…); the +//! others were identified against Word. See [`chp`] and [`pap`]. +//! - A font table entry is a size byte (the entry's length − 1), a flags byte, a 2-byte weight, the +//! charset byte, one more byte, then the name in 8-bit characters. +//! - The stylesheet (pair 1) has the Word 97 shape with smaller parts: a u16 header size (14), +//! then a header of that many bytes whose first two words are the style count and the size of +//! a style's fixed part (8, Word 97: 10); +//! then per style a u16 size (0: an empty slot) and that many bytes: the fixed part (sti, then +//! kind and base style, then UPX count and next style, then a size), the name (a length byte, +//! 8-bit characters, a 0), and the UPXs, each a u16 size and its bytes, padded to even. A +//! paragraph style's first UPX is its style index and paragraph sprms, the second its character +//! sprms; a character style has one, its character sprms. + +use craft_codepage::charset_code_page; + +use crate::DocbinError; +use crate::fkp::{Bins, TranslatedRun}; +use crate::piece::{CodePageRun, PieceTable, SYMBOL_CODE_PAGE, Word6Text}; +use crate::stsh::RawStyle; + +/// `wIdent` of a Word 6.0/95 file. +const W_IDENT: u16 = 0xA5DC; +const OFF_FLAGS: usize = 0x0A; +/// Fast-saved: the text is in pieces listed by a piece table. +const F_COMPLEX: u16 = 0x0004; +/// Password-protected (Word 97's bit; no unprotected file sets it). +const F_ENCRYPTED: u16 = 0x0100; +/// Word 97's `fExtChar` bit. Word reads a Word 6.0/95 file that sets it as UTF-16 text (each +/// piece's fc a plain byte offset), and so does this reader. +const F_EXT_CHAR: u16 = 0x1000; +/// The document's character set (u16): 0 Windows, 0x0100 Macintosh (all 8-bit text is Mac Roman, +/// whatever the fonts say), 0x0002 Symbol (every byte a private-use character). Word reads the +/// bytes above ASCII of any other value as U+FFFD. +const OFF_CHSE: usize = 0x14; +const OFF_FC_MAC: usize = 0x1C; +/// Bin table entries read, as for Word 97 (`fkp::MAX_BINS`). +const MAX_BINS: usize = 100_000; +/// FKP runs read (character or paragraph): far more than any real file's, and few enough to stay small. +const MAX_RUNS: usize = 1_000_000; +const OFF_FC_MIN: usize = 0x18; +const OFF_CCP_TEXT: usize = 0x34; +const OFF_PAIRS: usize = 0x58; +/// Pairs read: up to and including the piece table's. +const PAIRS: usize = 34; +const PAIR_STSH: usize = 1; +const PAIR_BTE_CHPX: usize = 12; +const PAIR_BTE_PAPX: usize = 13; +const PAIR_FONTS: usize = 15; +const PAIR_CLX: usize = 33; +/// More characters than Word's own documents get near: the FIB is corrupt (as for Word 97). +const MAX_CCP: u32 = 100_000_000; +/// The font table's entries: more than any real file has. +const MAX_FONTS: usize = 0x1_0000; +/// FKP page size in bytes. +const PAGE: usize = 512; +/// Size of a paragraph FKP entry (offset byte + 6). +const PAPX_BX: usize = 7; +/// Most cells a row's table definition is read for (the model's own cap is 63). +const MAX_CELLS: usize = 63; +/// Styles read: style indexes stop below 0x0FFF ("no style"). +const MAX_STYLES: usize = 0x0FFE; +/// Base-style links followed when a style inherits a font or language. +const MAX_STYLE_DEPTH: usize = 16; + +/// Character sprms read, by Word 6.0/95 opcode. Each one was matched against Word's own reading of +/// the corpus files (the `.docx` it saves from them). +mod chp { + /// Bold, a toggle (0 off, 1 on, 0x80 as the style, 0x81 the opposite of the style). + pub(super) const BOLD: u8 = 0x55; + /// Italic, a toggle. + pub(super) const ITALIC: u8 = 0x56; + /// Small capitals, a toggle. + pub(super) const SMALL_CAPS: u8 = 0x5A; + /// All capitals, a toggle. + pub(super) const CAPS: u8 = 0x5B; + /// The font: a 2-byte index into the font table. + pub(super) const FONT: u8 = 0x5D; + /// Underline: 0 none, 1 single (the only values seen). + pub(super) const UNDERLINE: u8 = 0x5E; + /// Colour: an index into Word's 16-colour palette, as Word 97's `Ico`. + pub(super) const COLOR: u8 = 0x62; + /// Size in half-points (2 bytes). + pub(super) const SIZE: u8 = 0x63; + /// The language (2 bytes, a Windows LCID): with no non-ANSI font, it gives the code page. + pub(super) const LID: u8 = 0x61; +} + +/// Paragraph and table sprms read, by Word 6.0/95 opcode, matched like [`chp`]'s. +mod pap { + /// Alignment: 0 left, 1 centred, 2 right, 3 justified. + pub(super) const JC: u8 = 0x05; + /// Keep with the next paragraph (1 byte; on the heading styles H1-H6, which Word shows with + /// keepNext; [MS-DOC]'s isprm table has sprmPFKeepFollow at 0x08). + pub(super) const KEEP_NEXT: u8 = 0x08; + /// Right indent in twips (signed, 2 bytes). + pub(super) const RIGHT: u8 = 0x10; + /// Left indent in twips. + pub(super) const LEFT: u8 = 0x11; + /// First-line indent in twips, relative to the left one (negative: hanging). + pub(super) const FIRST: u8 = 0x13; + /// Line spacing: the 4-byte Word 97 `LSPD` (dyaLine, fMultLinespace). + pub(super) const LINE: u8 = 0x14; + /// The paragraph is in a table. + pub(super) const IN_TABLE: u8 = 0x18; + /// The mark ends a table row. + pub(super) const TTP: u8 = 0x19; + /// Row alignment (2 bytes): 1 centred. + pub(super) const ROW_JC: u8 = 0xB6; + /// Row height in twips (signed, 2 bytes): positive at least, negative exactly. + pub(super) const ROW_HEIGHT: u8 = 0xBD; + /// The row's cells: u16 count, cell count, (count + 1) i16 cell edges, then a 10-byte + /// descriptor per cell whose first word's bit 0 starts a horizontal merge and bit 1 continues + /// it. + pub(super) const DEF_TABLE: u8 = 0xBE; +} + +/// Word 97 opcodes the translations produce ([MS-DOC] §2.6). +mod w97 { + pub(super) const C_BOLD: u16 = 0x0835; + pub(super) const C_ITALIC: u16 = 0x0836; + pub(super) const C_SMALL_CAPS: u16 = 0x083A; + pub(super) const C_CAPS: u16 = 0x083B; + pub(super) const C_KUL: u16 = 0x2A3E; + pub(super) const C_ICO: u16 = 0x2A42; + pub(super) const C_HPS: u16 = 0x4A43; + pub(super) const C_FTC0: u16 = 0x4A4F; + pub(super) const P_JC80: u16 = 0x2403; + pub(super) const P_KEEP_FOLLOW: u16 = 0x2406; + pub(super) const P_DXA_RIGHT80: u16 = 0x840E; + pub(super) const P_DXA_LEFT80: u16 = 0x840F; + pub(super) const P_DXA_LEFT1_80: u16 = 0x8411; + pub(super) const P_DYA_LINE: u16 = 0x6412; + pub(super) const P_IN_TABLE: u16 = 0x2416; + pub(super) const P_TTP: u16 = 0x2417; + pub(super) const T_JC: u16 = 0x5400; + pub(super) const T_ROW_HEIGHT: u16 = 0x9407; + pub(super) const T_DEF_TABLE: u16 = 0xD608; + pub(super) const T_MERGE: u16 = 0x5624; +} + +/// Is this WordDocument stream a Word 6.0/95 one? +pub(crate) fn is_word6(word: &[u8]) -> bool { + word.get(0..2) == Some(&W_IDENT.to_le_bytes()[..]) +} + +/// The fields of a Word 6.0/95 FIB that are read. +#[derive(Clone, Debug)] +pub(crate) struct Fib6 { + complex: bool, + /// Text is UTF-16 (fExtChar). + wide: bool, + chse: u16, + fc_min: u32, + fc_mac: u32, + /// Characters in the main text. + pub(crate) ccp_text: u32, + pairs: [(u32, u32); PAIRS], +} + +impl Fib6 { + pub(crate) fn parse(word: &[u8]) -> Result { + let u16_at = |at: usize| word.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |at: usize| word.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + if word.len() < OFF_PAIRS + PAIRS * 8 { + return Err(DocbinError::NotWord(format!("Word 6.0/95 WordDocument stream is {} bytes", word.len()))); + } + let flags = u16_at(OFF_FLAGS).unwrap_or(0); + if flags & F_ENCRYPTED != 0 { + return Err(DocbinError::Encryption("password-protected Word 6.0/95 files can't be opened".into())); + } + let ccp_text = u32_at(OFF_CCP_TEXT).unwrap_or(0); + if ccp_text > MAX_CCP { + return Err(DocbinError::Limit(format!("document claims {ccp_text} characters"))); + } + let mut pairs = [(0, 0); PAIRS]; + for (i, p) in pairs.iter_mut().enumerate() { + let at = OFF_PAIRS + i * 8; + *p = (u32_at(at).unwrap_or(0), u32_at(at + 4).unwrap_or(0)); + } + Ok(Fib6 { + complex: flags & F_COMPLEX != 0, + wide: flags & F_EXT_CHAR != 0, + chse: u16_at(OFF_CHSE).unwrap_or(0), + fc_min: u32_at(OFF_FC_MIN).unwrap_or(0), + fc_mac: u32_at(OFF_FC_MAC).unwrap_or(0), + ccp_text, + pairs, + }) + } + + /// The (fc, lcb) pair at index `i`, if it points at anything. + fn pair(&self, i: usize) -> Option<(u32, u32)> { + self.pairs.get(i).copied().filter(|&(_, lcb)| lcb > 0) + } +} + +/// Everything the walk needs from a Word 6.0/95 file besides its text stream. +pub(crate) struct Content { + pub(crate) pieces: PieceTable, + /// Character formatting, translated to Word 97 grpprls. + pub(crate) chpx: Bins, + /// Paragraph formatting and table rows, translated to Word 97 grpprls. + pub(crate) papx: Bins, + /// Font names by index (the walk resolves translated font sprms against them). + pub(crate) fonts: Vec, + /// The styles by index, their formatting translated to Word 97 grpprls. + pub(crate) styles: Vec, +} + +/// Read the text, formatting and fonts of a Word 6.0/95 file. +/// +/// 8-bit text decodes, as Word does, in the code page of: the document's character set when it +/// isn't Windows ([`OFF_CHSE`]); else the font a piece's Prm names (as Word 95 writes when a fast +/// save changes a font) when its charset has a code page; else, the same for the font of the +/// character run, or the one its paragraph style (or a base of it) names; else the language of +/// the run, or of its paragraph style; else Windows-1252. A font is only one named somewhere: +/// font 0 is not a fallback, and a font with the ANSI charset leaves the choice to the language. +pub(crate) fn content(word: &[u8], fib: &Fib6) -> Result { + let fonts = fib.pair(PAIR_FONTS).map(|(fc, lcb)| font_table(word, fc, lcb)).unwrap_or_default(); + let chp_runs = fib.pair(PAIR_BTE_CHPX).map(|(fc, lcb)| fkp_runs(word, fc, lcb, false)).unwrap_or_default(); + let pap_runs = fib.pair(PAIR_BTE_PAPX).map(|(fc, lcb)| fkp_runs(word, fc, lcb, true)).unwrap_or_default(); + let (styles, facts) = fib.pair(PAIR_STSH).map(|(fc, lcb)| stylesheet(word, fc, lcb)).unwrap_or_default(); + let windows = fib.chse == 0; + let default_code_page = match fib.chse { + // Text that no run covers is formatted by the Normal style. + 0 => text_code_page(&fonts, &facts, 0, None, None), + 0x0100 => MAC_ROMAN, + 0x0002 => SYMBOL_CODE_PAGE, + // Not a code page: bytes above ASCII read as U+FFFD. + _ => 0, + }; + let code_pages = if windows { code_page_runs(&chp_runs, &pap_runs, &facts, &fonts, default_code_page) } else { Vec::new() }; + // shortcut: East Asian (lead and trail byte) text is refused, as all Word 6.0/95 files were + // before; read it a character at a time when the piece walk can decode byte pairs. + let east_asian = || DocbinError::NotWord("Word 6.0/95 text in an East Asian code page is not read yet".into()); + if craft_codepage::is_multibyte_code_page(default_code_page) || code_pages.iter().any(|r| craft_codepage::is_multibyte_code_page(r.code_page)) { + return Err(east_asian()); + } + let multibyte_piece = std::cell::Cell::new(false); + let text = Word6Text { wide: fib.wide, default_code_page, code_pages }; + let pieces = if fib.complex { + let (fc, lcb) = fib.pair(PAIR_CLX).ok_or_else(|| DocbinError::Malformed("the fast-saved file has no piece table".into()))?; + // A Prm1's Prc may name the piece's font (sprm 0x5D); a Prm0 can't, its operand being one + // byte. + let piece_code_page = |prm: u16, prcs: &[Vec]| -> Option { + if !windows || prm & 1 == 0 { + return None; + } + let cp = last_font(prcs.get(usize::from(prm >> 1))?).and_then(|f| font_code_page(&fonts, f)); + if cp.is_some_and(craft_codepage::is_multibyte_code_page) { + multibyte_piece.set(true); + } + cp + }; + // The Prcs then carry Word 97 sprms, as the CHPXs and PAPXs do: the walk applies their + // character sprms to the piece's text and their paragraph sprms to the paragraph whose mark + // the piece holds. + let table = PieceTable::parse_word6(word, fc, lcb, text, piece_code_page, translate_prc)?; + if multibyte_piece.get() { + return Err(east_asian()); + } + table + } else { + // Word reads no more characters than the text's byte range (fcMin..fcMac) holds, one byte + // each or two for UTF-16, whatever the character count says. + let unit = if fib.wide { 2 } else { 1 }; + let ccp = fib.ccp_text.min(fib.fc_mac.saturating_sub(fib.fc_min) / unit); + PieceTable::contiguous_word6(fib.fc_min, ccp, text) + }; + let chpx = Bins::translated(chp_runs.iter().map(|r| TranslatedRun { lo: r.lo, hi: r.hi, istd: 0, grpprl: translate_chp(r.grpprl) }).collect()); + let papx = + Bins::translated(pap_runs.iter().map(|r| TranslatedRun { lo: r.lo, hi: r.hi, istd: r.istd, grpprl: translate_pap(r.grpprl) }).collect()); + Ok(Content { pieces, chpx, papx, fonts: fonts.into_iter().map(|f| f.name).collect(), styles }) +} + +/// Mac OS Roman, the 8-bit text of a Macintosh Word document. +const MAC_ROMAN: u16 = craft_codepage::MAC_ROMAN_CODE_PAGE; + +/// The code page of font `font`'s charset, if it has one (not for ANSI, default or symbol +/// charsets, whose text Word decodes by its language). +fn font_code_page(fonts: &[Font], font: u16) -> Option { + fonts.get(usize::from(font)).and_then(|f| charset_code_page(i32::from(f.charset))) +} + +/// Windows' ANSI code page for the language `lid` (an LCID), which Word uses for 8-bit text in a +/// font without a charset of its own. Russian (1251) and English (1252) were checked against Word; +/// the rest is the standard Windows assignment. +fn lid_code_page(lid: u16) -> u16 { + match lid & 0x03FF { + // Serbian in Cyrillic (0x0C1A, 0x1C1A); Croatian and Serbian in Latin otherwise. + 0x1A => match lid { + 0x0C1A | 0x1C1A => 1251, + _ => 1250, + }, + 0x02 | 0x19 | 0x22 | 0x23 | 0x2F | 0x3F | 0x40 | 0x44 | 0x50 => 1251, + 0x05 | 0x0E | 0x15 | 0x18 | 0x1B | 0x1C | 0x24 => 1250, + 0x08 => 1253, + 0x1F => 1254, + 0x0D => 1255, + 0x01 | 0x20 | 0x29 => 1256, + 0x25..=0x27 => 1257, + 0x2A => 1258, + 0x1E => 874, + 0x11 => 932, + 0x12 => 949, + 0x04 => match lid { + 0x0804 | 0x1004 => 936, + _ => 950, + }, + _ => 1252, + } +} + +/// A style's own font and language sprms and its base, for inheritance ([`StyleFacts::resolve`]). +#[derive(Clone, Copy, Debug, Default)] +struct StyleFacts { + base: u16, + font: Option, + lid: Option, +} + +impl StyleFacts { + /// Style `istd`'s font and language, each from the style itself or the nearest base that has + /// one. + fn resolve(facts: &[StyleFacts], istd: u16) -> (Option, Option) { + let (mut font, mut lid) = (None, None); + let mut at = istd; + for _ in 0..MAX_STYLE_DEPTH { + let Some(f) = facts.get(usize::from(at)) else { break }; + font = font.or(f.font); + lid = lid.or(f.lid); + if font.is_some() && lid.is_some() { + break; + } + at = f.base; + } + (font, lid) + } +} + +/// The styles of the stylesheet at `word[fc..fc+lcb]`, by index (an empty slot is a default +/// style, which keeps the indexes aligned), with their formatting translated, and each style's +/// own font and language. Reading stops at the first entry that runs past the table. +fn stylesheet(word: &[u8], fc: u32, lcb: u32) -> (Vec, Vec) { + let Some(st) = (fc as usize).checked_add(lcb as usize).and_then(|end| word.get(fc as usize..end)) else { return Default::default() }; + let u16_at = |b: &[u8], at: usize| b.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]])); + let Some(cb_header) = u16_at(st, 0).map(usize::from) else { return Default::default() }; + let (Some(cstd), Some(cb_base)) = (u16_at(st, 2), u16_at(st, 4)) else { return Default::default() }; + let cb_base = usize::from(cb_base); + let (mut styles, mut facts) = (Vec::new(), Vec::new()); + let mut at = 2 + cb_header; + for _ in 0..usize::from(cstd).min(MAX_STYLES) { + let Some(cb) = u16_at(st, at).map(usize::from) else { break }; + let Some(std) = st.get(at + 2..at + 2 + cb) else { break }; + at += 2 + cb; + let (style, fact) = style(std, cb_base).unwrap_or_else(|| (RawStyle::default(), StyleFacts { base: 0x0FFF, ..Default::default() })); + styles.push(style); + facts.push(fact); + } + (styles, facts) +} + +/// The names of the built-in styles by sti: the "Index within built-in styles" of the reserved +/// style names in [MS-OE376] (Part 4 §2.7.3.9), which [MS-DOC]'s StdfBase says sti is. 0x0FFE +/// (user-defined) and anything past the table keep the name stored in the file. +const BUILT_IN_NAMES: [&str; 107] = [ + "Normal", + "heading 1", + "heading 2", + "heading 3", + "heading 4", + "heading 5", + "heading 6", + "heading 7", + "heading 8", + "heading 9", + "index 1", + "index 2", + "index 3", + "index 4", + "index 5", + "index 6", + "index 7", + "index 8", + "index 9", + "toc 1", + "toc 2", + "toc 3", + "toc 4", + "toc 5", + "toc 6", + "toc 7", + "toc 8", + "toc 9", + "Normal Indent", + "footnote text", + "annotation text", + "header", + "footer", + "index heading", + "caption", + "table of figures", + "envelope address", + "envelope return", + "footnote reference", + "annotation reference", + "line number", + "page number", + "endnote reference", + "endnote text", + "table of authorities", + "macro", + "toa heading", + "List", + "List Bullet", + "List Number", + "List 2", + "List 3", + "List 4", + "List 5", + "List Bullet 2", + "List Bullet 3", + "List Bullet 4", + "List Bullet 5", + "List Number 2", + "List Number 3", + "List Number 4", + "List Number 5", + "Title", + "Closing", + "Signature", + "Default Paragraph Font", + "Body Text", + "Body Text Indent", + "List Continue", + "List Continue 2", + "List Continue 3", + "List Continue 4", + "List Continue 5", + "Message Header", + "Subtitle", + "Salutation", + "Date", + "Body Text First Indent", + "Body Text First Indent 2", + "Note Heading", + "Body Text 2", + "Body Text 3", + "Body Text Indent 2", + "Body Text Indent 3", + "Block Text", + "Hyperlink", + "FollowedHyperlink", + "Strong", + "Emphasis", + "Document Map", + "Plain Text", + "E-mail Signature", + "HTML Top of Form", + "HTML Bottom of Form", + "Normal (Web)", + "HTML Acronym", + "HTML Address", + "HTML Cite", + "HTML Code", + "HTML Definition", + "HTML Keyboard", + "HTML Preformatted", + "HTML Sample", + "HTML Typewriter", + "HTML Variable", + "Normal Table", + "annotation subject", +]; + +/// One style entry (`None` for an empty slot or one too short for its fixed part and name). +fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> { + let u16_at = |at: usize| std.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]])); + if cb_base < 8 { + return None; + } + let (sti, kind_base, upx_next) = (u16_at(0)? & 0x0FFF, u16_at(2)?, u16_at(4)?); + let (stk, istd_base, cupx) = ((kind_base & 0x000F) as u8, kind_base >> 4, usize::from(upx_next & 0x000F)); + let len = usize::from(*std.get(cb_base)?); + // A built-in style goes by its built-in name, as in Word, whatever name the file stores + // ("Default" or "Обычный" for Normal). Other names are 8-bit, as Word shows them + // (Windows-1252: names it couldn't store read back with '?'). + let stored = std.get(cb_base + 1..cb_base + 1 + len)?; + let name: String = match BUILT_IN_NAMES.get(usize::from(sti)) { + Some(built_in) => (*built_in).to_owned(), + None => stored.iter().map(|&b| craft_codepage::cp1252(b)).collect(), + }; + let mut upxs: Vec<&[u8]> = Vec::new(); + let mut j = cb_base + 1 + len + 1; + for _ in 0..cupx.min(3) { + j += j % 2; + let Some(n) = u16_at(j).map(usize::from) else { break }; + let Some(upx) = std.get(j + 2..j + 2 + n) else { break }; + upxs.push(upx); + j += 2 + n; + } + // A paragraph style: style index + paragraph sprms, then character sprms. A character style: + // character sprms. + let (papx, chpx) = match stk { + 1 => (upxs.first().and_then(|u| u.get(2..)).unwrap_or_default(), upxs.get(1).copied().unwrap_or_default()), + _ => (&[][..], upxs.first().copied().unwrap_or_default()), + }; + let fact = StyleFacts { base: istd_base, font: last_font(chpx), lid: last_lid(chpx) }; + Some((RawStyle { stk, istd_base, name, papx: translate_pap(papx), chpx: translate_chp(chpx) }, fact)) +} + +/// One font table entry. +struct Font { + name: String, + charset: u8, +} + +/// The fonts of the font table at `word[fc..fc+lcb]`, by index. A truncated entry ends the table. +fn font_table(word: &[u8], fc: u32, lcb: u32) -> Vec { + let Some(table) = (fc as usize).checked_add(lcb as usize).and_then(|end| word.get(fc as usize..end)) else { return Vec::new() }; + // The table starts with its own size, which bounds the entries along with `lcb`. + let size = table.get(0..2).map_or(0, |b| usize::from(u16::from_le_bytes([b[0], b[1]]))); + let table = table.get(..size.min(table.len())).unwrap_or_default(); + let mut fonts = Vec::new(); + let mut at = 2usize; + while let Some(&cb_m1) = table.get(at) { + let next = at + usize::from(cb_m1) + 1; + // The entry must lie inside the table and hold its charset (one too short is corrupt). + let Some(entry) = table.get(at..next) else { break }; + let (Some(&charset), Some(name)) = (entry.get(4), entry.get(6..)) else { break }; + if fonts.len() >= MAX_FONTS { + break; + } + // An 8-bit name; font names are ASCII in every file seen, other bytes read as Latin-1. + let name = name.split(|&b| b == 0).next().unwrap_or_default().iter().map(|&b| char::from(b)).collect(); + fonts.push(Font { name, charset }); + at = next; + } + fonts +} + +/// One FKP run as stored: its FC range, the paragraph style (PAPX runs) and its Word 6 grpprl. +struct Run<'w> { + lo: u32, + hi: u32, + istd: u16, + grpprl: &'w [u8], +} + +/// The page numbers of a bin table with `n` entries ((n+1) u32 FCs, then n u16 page numbers), +/// each once, however many entries name it: a page's runs carry their own FCs, so reading it +/// again would only repeat them. The entries read are capped as for Word 97. +fn distinct_pages(plc: &[u8], n: usize) -> Vec { + let mut pns: Vec = (0..n.min(MAX_BINS)) + .filter_map(|i| plc.get(4 * (n + 1) + 2 * i..4 * (n + 1) + 2 * i + 2).map(|b| usize::from(u16::from_le_bytes([b[0], b[1]])))) + .collect(); + pns.sort_unstable(); + pns.dedup(); + pns +} + +/// Every run of the FKP pages a bin table at `word[fc..fc+lcb]` lists, each page read once and +/// at most [`MAX_RUNS`] runs in all. Unreadable pages are skipped. +fn fkp_runs(word: &[u8], fc: u32, lcb: u32, papx: bool) -> Vec> { + let Some(plc) = (fc as usize).checked_add(lcb as usize).and_then(|end| word.get(fc as usize..end)) else { return Vec::new() }; + let Some(n) = plc.len().checked_sub(4).filter(|r| r % 6 == 0).map(|r| r / 6) else { return Vec::new() }; + let entry = if papx { PAPX_BX } else { 1 }; + let mut runs = Vec::new(); + for pn in distinct_pages(plc, n) { + if runs.len() >= MAX_RUNS { + break; + } + let Some(page) = pn.checked_mul(PAGE).and_then(|at| word.get(at..at.checked_add(PAGE)?)) else { continue }; + let crun = usize::from(page.get(PAGE - 1).copied().unwrap_or(0)); + // The FCs and the entries must fit before the count byte. + if 4 * (crun + 1) + entry * crun >= PAGE { + continue; + } + let fc_at = |k: usize| page.get(4 * k..4 * k + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + for k in 0..crun { + let (Some(lo), Some(hi)) = (fc_at(k), fc_at(k + 1)) else { break }; + let off = usize::from(page.get(4 * (crun + 1) + entry * k).copied().unwrap_or(0)) * 2; + let (istd, grpprl) = match (off, papx) { + (0, _) => (0, &[][..]), + // A CHPX: a byte count, then the grpprl. + (_, false) => (0, page.get(off).and_then(|&cb| page.get(off + 1..off + 1 + usize::from(cb))).unwrap_or_default()), + // A PAPX: a count of 2-byte words, then the style index and the grpprl. + (_, true) => { + let body = page.get(off).and_then(|&cw| page.get(off + 1..off + 1 + 2 * usize::from(cw))).unwrap_or_default(); + let istd = body.get(0..2).map_or(0, |b| u16::from_le_bytes([b[0], b[1]])); + (istd, body.get(2..).unwrap_or_default()) + } + }; + runs.push(Run { lo, hi, istd, grpprl }); + } + } + runs +} + +/// The sprms of a Word 6.0/95 grpprl as (opcode, operand). Reading stops at an opcode whose +/// operand length is not known, since the rest can't be framed, and at a lone trailing 0 (the +/// padding of a PAPX to whole words). +fn sprms(grpprl: &[u8]) -> impl Iterator { + let mut rest = grpprl; + std::iter::from_fn(move || { + let (&op, after) = rest.split_first()?; + let len = match op { + // 0x55-0x5C are the character toggles of [MS-DOC]'s Prm0 isprm table (bold, italic, + // strike, outline, shadow, small caps, caps, hidden), all one byte; 0x55, 0x56, 0x5A + // and 0x5B are also seen in real files. + // 0x0D, 0x0E, 0x1D, 0x25 and 0x2C are one-byte paragraph sprms of [MS-DOC]'s isprm table + // too (numbering level, no line numbers, frame anchoring, wrapping, no hyphenation). + 0x05 | 0x08 | 0x0D | 0x0E | 0x18 | 0x19 | 0x1D | 0x25 | 0x2C | 0x33 | 0x55..=0x5C | 0x5E | 0x62 | 0x68 | 0x75 | 0xB7 | 0xB9 => 1, + // 0x1A/0x1B: a frame's position; 0x6B: kerning in half-points (H1 has 0x0024; Word + // shows kern=36). + 0x10 | 0x11 | 0x13 | 0x15 | 0x16 | 0x1A | 0x1B | 0x26 | 0x27 | 0x28 | 0x29 | 0x2F | 0x50 | 0x5D | 0x60 | 0x61 | 0x63 | 0x6B | 0xB6 + | 0xB8 | 0xBD | 0xC0 => 2, + 0x14 => 4, + // A count byte, then that many bytes (0x0C: a bulleted style's numbering, 52 bytes). + 0x0C | 0x0F | 0x44 | 0xBF => 1 + usize::from(*after.first()?), + // A 2-byte count, then one byte fewer than it says (as Word 97's sprmTDefTable). + 0xBE => 2 + usize::from(u16::from_le_bytes([*after.first()?, *after.get(1)?])).saturating_sub(1), + _ => return None, + }; + let operand = after.get(..len)?; + rest = after.get(len..).unwrap_or_default(); + Some((op, operand)) + }) +} + +/// Append a Word 97 Prl: opcode, then operand. +fn prl(out: &mut Vec, op: u16, operand: &[u8]) { + out.extend_from_slice(&op.to_le_bytes()); + out.extend_from_slice(operand); +} + +/// A Word 6.0/95 CHPX grpprl as the Word 97 sprms it stands for. Sprms not read are left out. +fn translate_chp(grpprl: &[u8]) -> Vec { + let mut out = Vec::new(); + for (op, v) in sprms(grpprl) { + match op { + chp::BOLD => prl(&mut out, w97::C_BOLD, v), + chp::ITALIC => prl(&mut out, w97::C_ITALIC, v), + chp::SMALL_CAPS => prl(&mut out, w97::C_SMALL_CAPS, v), + chp::CAPS => prl(&mut out, w97::C_CAPS, v), + // Only none and single were seen; any other value is left unread. + chp::UNDERLINE if matches!(v, [0] | [1]) => prl(&mut out, w97::C_KUL, v), + chp::COLOR => prl(&mut out, w97::C_ICO, v), + chp::SIZE => prl(&mut out, w97::C_HPS, v), + chp::FONT => prl(&mut out, w97::C_FTC0, v), + _ => {} + } + } + out +} + +/// A Word 6.0/95 Prc grpprl as the Word 97 sprms it stands for: character and paragraph sprms +/// alike (Word 95 records a paragraph change before a fast save as a Prc on the mark's piece). +fn translate_prc(grpprl: &[u8]) -> Vec { + [translate_chp(grpprl), translate_pap(grpprl)].concat() +} + +/// A Word 6.0/95 PAPX grpprl as the Word 97 sprms it stands for, table rows included. Sprms not +/// read are left out. +fn translate_pap(grpprl: &[u8]) -> Vec { + let mut out = Vec::new(); + for (op, v) in sprms(grpprl) { + match op { + // Only 0-3 were seen: another value is left unread. + pap::JC if matches!(v, [0..=3]) => prl(&mut out, w97::P_JC80, v), + pap::KEEP_NEXT => prl(&mut out, w97::P_KEEP_FOLLOW, v), + pap::RIGHT => prl(&mut out, w97::P_DXA_RIGHT80, v), + pap::LEFT => prl(&mut out, w97::P_DXA_LEFT80, v), + pap::FIRST => prl(&mut out, w97::P_DXA_LEFT1_80, v), + // Only "at least" spacing was seen (a positive height, not a multiple): the other + // forms are left unread. + pap::LINE => { + if let [l0, l1, 0, 0] = v + && i16::from_le_bytes([*l0, *l1]) > 0 + { + prl(&mut out, w97::P_DYA_LINE, v); + } + } + pap::IN_TABLE => prl(&mut out, w97::P_IN_TABLE, v), + pap::TTP => prl(&mut out, w97::P_TTP, v), + pap::ROW_JC => prl(&mut out, w97::T_JC, v), + pap::ROW_HEIGHT => prl(&mut out, w97::T_ROW_HEIGHT, v), + pap::DEF_TABLE => def_table(&mut out, v), + _ => {} + } + } + out +} + +/// A Word 6.0/95 table definition as a Word 97 `sprmTDefTable` holding the cell edges (the only +/// part the table reader uses) and one `sprmTMerge` per horizontal merge. +fn def_table(out: &mut Vec, v: &[u8]) { + let Some(&itc) = v.get(2) else { return }; + let itc = usize::from(itc).min(MAX_CELLS); + let Some(edges) = v.get(3..3 + 2 * (itc + 1)) else { return }; + // Word 97 operand: cb (u16: the bytes after it, plus one), the cell count, the edges. + let cb = (1 + edges.len() + 1) as u16; + out.extend_from_slice(&w97::T_DEF_TABLE.to_le_bytes()); + out.extend_from_slice(&cb.to_le_bytes()); + out.push(itc as u8); + out.extend_from_slice(edges); + let cells = v.get(3 + edges.len()..).unwrap_or_default(); + let mut merges: Vec<(usize, usize)> = Vec::new(); + let mut start: Option = None; + for i in 0..=itc { + let rgf = cells.get(10 * i..10 * i + 2).map_or(0, |b| u16::from_le_bytes([b[0], b[1]])); + let continues = i < itc && rgf & 0x0002 != 0 && rgf & 0x0001 == 0; + if continues { + continue; + } + // A merge runs from its first cell through every cell that continues it. + if let Some(a) = start.take() + && i > a + 1 + { + merges.push((a, i)); + } + if i < itc && rgf & 0x0001 != 0 { + start = Some(i); + } + } + // Right to left: the table reader folds each merge's cells into its first one as it goes, so + // a merge further right must be applied before one to its left moves its cells. + for (a, b) in merges.into_iter().rev() { + prl(out, w97::T_MERGE, &[a as u8, b as u8]); + } +} + +/// The code page of text in paragraph style `istd` whose run names `run_font` and `run_lid`: the +/// run's font, else the style's (nearest in its base chain), when that font's charset has a code +/// page; else the run's language, else the style's; else Windows-1252. +fn text_code_page(fonts: &[Font], facts: &[StyleFacts], istd: u16, run_font: Option, run_lid: Option) -> u16 { + let (style_font, style_lid) = StyleFacts::resolve(facts, istd); + run_font.or(style_font).and_then(|f| font_code_page(fonts, f)).or_else(|| run_lid.or(style_lid).map(lid_code_page)).unwrap_or(1252) +} + +/// The language a grpprl names (sprm 0x61), if any: the last one. +fn last_lid(grpprl: &[u8]) -> Option { + sprms(grpprl).filter(|(op, _)| *op == chp::LID).filter_map(|(_, v)| Some(u16::from_le_bytes([*v.first()?, *v.get(1)?]))).last() +} + +/// The byte ranges whose code page is not the document default `default`, cut at every character and paragraph run +/// boundary, each stretch in [`text_code_page`]'s. Sorted by start and not overlapping. +fn code_page_runs(chp: &[Run], pap: &[Run], facts: &[StyleFacts], fonts: &[Font], default: u16) -> Vec { + let sorted = |runs: &[Run]| -> Vec<(u32, u32, usize)> { + let mut v: Vec<(u32, u32, usize)> = runs.iter().enumerate().filter(|(_, r)| r.lo < r.hi).map(|(i, r)| (r.lo, r.hi, i)).collect(); + v.sort_unstable(); + v + }; + let (chp_sorted, pap_sorted) = (sorted(chp), sorted(pap)); + let covering = |v: &[(u32, u32, usize)], fc: u32| -> Option { + let k = v.partition_point(|&(lo, _, _)| lo <= fc).checked_sub(1)?; + v.get(k).filter(|&&(_, hi, _)| fc < hi).map(|&(_, _, i)| i) + }; + let mut cuts: Vec = chp_sorted.iter().chain(pap_sorted.iter()).flat_map(|&(lo, hi, _)| [lo, hi]).collect(); + cuts.sort_unstable(); + cuts.dedup(); + let mut out: Vec = Vec::new(); + for w in cuts.windows(2) { + let (&lo, &hi) = (w.first().unwrap_or(&0), w.get(1).unwrap_or(&0)); + let run = covering(&chp_sorted, lo).and_then(|i| chp.get(i)); + let para = covering(&pap_sorted, lo).and_then(|i| pap.get(i)); + if run.is_none() && para.is_none() { + continue; + } + let run_font = run.and_then(|r| last_font(r.grpprl)); + let run_lid = run.and_then(|r| last_lid(r.grpprl)); + let code_page = text_code_page(fonts, facts, para.map_or(0, |p| p.istd), run_font, run_lid); + if code_page == default { + continue; + } + match out.last_mut() { + Some(last) if last.hi == lo && last.code_page == code_page => last.hi = hi, + _ => out.push(CodePageRun { lo, hi, code_page }), + } + } + out +} + +/// The font a CHPX or Prc grpprl names (sprm 0x5D), if any: the last one, as a later sprm +/// overrides an earlier one when the formatting is applied (a font before an opcode of unknown +/// length stands). +fn last_font(grpprl: &[u8]) -> Option { + sprms(grpprl).filter(|(op, _)| *op == chp::FONT).filter_map(|(_, v)| Some(u16::from_le_bytes([*v.first()?, *v.get(1)?]))).last() +} + +#[cfg(test)] +mod tests { + #[test] + fn a_page_named_by_many_bin_entries_is_read_once() { + // A hostile bin table: a million entries all naming page 7, and one naming page 3. + let n = 1_000_001usize; + let mut plc = vec![0u8; 4 * (n + 1)]; + for i in 0..n { + plc.extend_from_slice(&(if i == 5 { 3u16 } else { 7u16 }).to_le_bytes()); + } + assert_eq!(super::distinct_pages(&plc, n), [3, 7]); + } + + #[test] + fn bin_entries_past_the_cap_are_not_read() { + let n = super::MAX_BINS + 1; + let mut plc = vec![0u8; 4 * (n + 1)]; + for i in 0..n { + plc.extend_from_slice(&(if i == n - 1 { 9u16 } else { 7u16 }).to_le_bytes()); + } + assert_eq!(super::distinct_pages(&plc, n), [7]); + } +} diff --git a/crates/docpath/tests/long_path.rs b/crates/docpath/tests/long_path.rs new file mode 100644 index 0000000000..2ecf08ba15 --- /dev/null +++ b/crates/docpath/tests/long_path.rs @@ -0,0 +1,29 @@ +//! Paths long enough that a per-level recursive descent would exhaust the stack. Parsing is +//! iterative — `resolve` and `classify` reach `parse_share` at a fixed depth — so these come +//! back; a refusal is fine, a crash is not. + +use craft_docpath::{classify, resolve}; + +/// Half a megabyte of components under a UNC share: one component per level for a parser that +/// recursed on each separator. +#[test] +fn a_half_megabyte_unc_path_comes_back() { + let mut path = String::from(r"\\?\UNC\host\share"); + for _ in 0..(1 << 18) { + path.push_str(r"\d"); + } + let _ = resolve(&path, None); + let _ = classify(&path); +} + +/// Sixteen thousand nested verbatim prefixes: each level was a candidate recursive call when the +/// UNC prefixes were first reviewed. +#[test] +fn nested_verbatim_prefixes_come_back() { + let mut path = String::new(); + for _ in 0..(1 << 14) { + path.push_str(r"\\?\UNC\"); + } + let _ = resolve(&path, None); + let _ = classify(&path); +} diff --git a/crates/document-bundle/src/lib.rs b/crates/document-bundle/src/lib.rs index 18e40a3ff5..70a960a1f4 100644 --- a/crates/document-bundle/src/lib.rs +++ b/crates/document-bundle/src/lib.rs @@ -6,15 +6,17 @@ //! bounded reads and extraction of legacy base64 asset maps. Entry names and MIME type are //! supplied by the format using the bundle. -use std::io::{Read, Seek}; +use std::io::{Cursor, Read, Seek, Write}; -use craft_zip::{Archive, Compression, Limits, Writer}; +use craft_zip::{Archive, Limits}; use serde_json::Value; const MAX_ENTRIES: u64 = 100_000; const JSON_LIMIT: u64 = 256 << 20; const ASSET_LIMIT: u64 = 1 << 30; const EXPANSION_LIMIT: u64 = 4 << 30; +/// Largest proxy preview read from a bundle; larger entries are skipped. +pub const PROXY_LIMIT: u64 = 1 << 20; /// Per-entry and total-expansion limits for an untrusted document bundle. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -46,6 +48,8 @@ pub struct Spec<'a> { pub preview_entry: &'a str, /// Directory prefix for embedded assets, without a trailing slash. pub assets_directory: &'a str, + /// Directory prefix for proxy previews of linked assets, without a trailing slash. + pub proxies_directory: &'a str, /// Metadata value written in the `format` field. pub format_name: &'a str, /// Old single-file JSON field containing base64 assets keyed by decimal id. @@ -72,6 +76,8 @@ pub struct Package { pub version: u64, /// Embedded asset bytes keyed by decimal asset id. pub assets: Vec<(String, Vec)>, + /// Proxy preview bytes (JPEG or PNG) keyed by decimal asset id, for ids the document lists. + pub proxies: Vec<(String, Vec)>, } /// Why a document bundle could not be read or written. @@ -116,24 +122,104 @@ pub fn starts_with_mimetype(prefix: &[u8], spec: Spec<'_>) -> bool { craft_zip::stored_mimetype(prefix).is_some_and(|mime| mime == spec.mimetype.as_bytes()) } -/// Write a ZIP document bundle containing the serialized document, metadata, preview and assets. -pub fn write(document: &[u8], version: u32, generator: &str, preview: Option<&[u8]>, assets: &[Asset<'_>], spec: Spec<'_>) -> Result, Error> { - let mut writer = Writer::new(); - writer.add(spec.mimetype_entry, spec.mimetype.as_bytes(), Compression::Stored).map_err(|e| Error::Write(e.to_string()))?; - let metadata = serde_json::json!({"format":spec.format_name, "version":version, "generator":generator}); - let metadata = serde_json::to_vec(&metadata).map_err(|e| Error::Write(e.to_string()))?; - writer.add(spec.metadata_entry, &metadata, Compression::Deflated).map_err(|e| Error::Write(e.to_string()))?; - if let Some(preview) = preview { - writer.add(spec.preview_entry, preview, Compression::Stored).map_err(|e| Error::Write(e.to_string()))?; +/// Refuses every write and seek after the first failure of the wrapped writer. Dropping a +/// `ZipWriter` after an error finalizes the archive, which must not touch a cancelled target. +struct Latch { + inner: W, + failed: bool, +} + +impl Latch { + fn latched() -> std::io::Error { + std::io::Error::other("writer already failed") } - writer.add(spec.document_entry, document, Compression::Deflated).map_err(|e| Error::Write(e.to_string()))?; +} + +impl Write for Latch { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.failed { + return Err(Self::latched()); + } + self.inner.write(buf).inspect_err(|_| self.failed = true) + } + fn flush(&mut self) -> std::io::Result<()> { + if self.failed { + return Err(Self::latched()); + } + self.inner.flush().inspect_err(|_| self.failed = true) + } +} + +impl Seek for Latch { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + if self.failed { + return Err(Self::latched()); + } + self.inner.seek(pos).inspect_err(|_| self.failed = true) + } +} + +fn write_err(e: impl std::fmt::Display) -> Error { + Error::Write(e.to_string()) +} + +/// Write a ZIP document bundle containing the serialized document, metadata, preview, assets and +/// proxy previews. +pub fn write( + document: &[u8], + version: u32, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], + spec: Spec<'_>, +) -> Result, Error> { + let mut out = Cursor::new(Vec::new()); + write_to(&mut out, document, version, generator, preview, assets, proxies, spec)?; + Ok(out.into_inner()) +} + +/// Like [`write`], streaming the archive into `out`. A writer that fails (for example to cancel +/// a long save) stops the write at the next member or buffer and the error is returned. +#[allow(clippy::too_many_arguments)] +pub fn write_to( + out: W, + document: &[u8], + version: u32, + generator: &str, + preview: Option<&[u8]>, + assets: &[Asset<'_>], + proxies: &[Asset<'_>], + spec: Spec<'_>, +) -> Result<(), Error> { + use zip::CompressionMethod::{Deflated, Stored}; + let mut zip = zip::ZipWriter::new(Latch { inner: out, failed: false }); + let mut add = |name: &str, data: &[u8], method: zip::CompressionMethod| -> Result<(), Error> { + let options = zip::write::SimpleFileOptions::default() + .compression_method(method) + .compression_level(if method == Deflated { Some(6) } else { None }) + .last_modified_time(zip::DateTime::default()) + .large_file(u64::try_from(data.len()).unwrap_or(u64::MAX) >= u64::from(u32::MAX) / 2); + zip.start_file(name, options).map_err(|e| Error::Write(format!("{name}: {e}")))?; + zip.write_all(data).map_err(|e| Error::Write(format!("{name}: {e}"))) + }; + add(spec.mimetype_entry, spec.mimetype.as_bytes(), Stored)?; + let metadata = serde_json::json!({"format":spec.format_name, "version":version, "generator":generator}); + add(spec.metadata_entry, &serde_json::to_vec(&metadata).map_err(write_err)?, Deflated)?; + if let Some(preview) = preview { + add(spec.preview_entry, preview, Stored)?; + } + add(spec.document_entry, document, Deflated)?; for asset in assets.iter().filter(|asset| !asset.data.is_empty()) { let path = format!("{}/{}.{}", spec.assets_directory, asset.id, extension(asset.mime)); - let compression = - if matches!(asset.mime, "image/png" | "image/jpeg" | "image/gif" | "image/webp") { Compression::Stored } else { Compression::Deflated }; - writer.add(&path, asset.data, compression).map_err(|e| Error::Write(e.to_string()))?; + let method = if matches!(asset.mime, "image/png" | "image/jpeg" | "image/gif" | "image/webp") { Stored } else { Deflated }; + add(&path, asset.data, method)?; } - writer.finish().map_err(|e| Error::Write(e.to_string())) + for proxy in proxies.iter().filter(|proxy| !proxy.data.is_empty()) { + let ext = if proxy.mime == "image/jpeg" { "jpg" } else { "png" }; + add(&format!("{}/{}.{ext}", spec.proxies_directory, proxy.id), proxy.data, Stored)?; + } + zip.finish().map(drop).map_err(write_err) } /// Read a ZIP bundle or legacy JSON document within bounded member sizes. @@ -186,7 +272,40 @@ pub fn read_with_limits(bytes: &[u8], supported_version: u32, spec: Spec<'_>, li embedded.push((id.to_owned(), data)); } } - Ok(Package { document, version, assets: embedded }) + let proxies = read_proxies(&mut archive, &wanted, spec); + Ok(Package { document, version, assets: embedded, proxies }) +} + +/// Proxy previews for known asset ids. Only `/.jpg|png` is accepted; entries over +/// [`PROXY_LIMIT`] or that fail to read are skipped. +fn read_proxies(archive: &mut Archive<'_>, wanted: &std::collections::HashSet, spec: Spec<'_>) -> Vec<(String, Vec)> { + let prefix = format!("{}/", spec.proxies_directory); + let mut proxies = Vec::new(); + for path in archive.names().map(|name| name.into_owned()).collect::>() { + let Some(member) = path.strip_prefix(&prefix) else { continue }; + let Some((id, ext)) = member.split_once('.') else { continue }; + if !matches!(ext, "jpg" | "png") || !wanted.contains(id) || id.parse::().is_err() { + continue; + } + if archive.declared_size(&path).is_none_or(|size| size > PROXY_LIMIT) { + continue; + } + let Some(size) = archive.declared_size(&path) else { continue }; + if archive.budget().remaining() < size { + break; + } + match archive.read(&path, PROXY_LIMIT) { + Ok(Some(data)) => proxies.push((id.to_owned(), data)), + Ok(None) => {} + // A failed read may have decompressed up to `size` bytes without being charged. + Err(_) => { + if archive.budget_mut().charge(size).is_err() { + break; + } + } + } + } + proxies } /// Read a preview with a fixed maximum size without decompressing the full bundle. @@ -235,7 +354,7 @@ fn read_legacy(bytes: &[u8], spec: Spec<'_>) -> Result { object.remove(field); } } - Ok(Package { document, version: 1, assets }) + Ok(Package { document, version: 1, assets, proxies: Vec::new() }) } fn decode_base64(input: &str) -> Vec { @@ -271,6 +390,7 @@ mod tests { document_entry: "document.json", preview_entry: "preview.png", assets_directory: "assets", + proxies_directory: "proxies", format_name: "test", legacy_assets_field: Some("assetData"), }; @@ -278,8 +398,8 @@ mod tests { #[test] fn writes_and_reads_bundle_members() { let payload = [1u8, 2, 3]; - let bytes = - write(br#"{"assets":{"7":{}}}"#, 4, "Test 0.1", Some(b"png"), &[Asset { id: "7", mime: "image/png", data: &payload }], SPEC).unwrap(); + let bytes = write(br#"{"assets":{"7":{}}}"#, 4, "Test 0.1", Some(b"png"), &[Asset { id: "7", mime: "image/png", data: &payload }], &[], SPEC) + .unwrap(); assert!(has_document(&bytes, SPEC)); assert!(starts_with_mimetype(&bytes, SPEC)); let loaded = read(&bytes, 4, SPEC).unwrap(); @@ -298,7 +418,7 @@ mod tests { #[test] fn refuses_newer_versions() { - let bytes = write(b"{}", 9, "future", None, &[], SPEC).unwrap(); + let bytes = write(b"{}", 9, "future", None, &[], &[], SPEC).unwrap(); assert_eq!(read(&bytes, 4, SPEC), Err(Error::TooNew(9))); } @@ -307,11 +427,31 @@ mod tests { let bytes = vec![7u8; 128]; let document = br#"{"assets":{"7":{}}}"#; let limits = ReadLimits { json_bytes: 1 << 20, compressed_asset_bytes: 8, expansion_bytes: 1 << 20 }; - let stored = write(document, 4, "test", None, &[Asset { id: "7", mime: "image/png", data: &bytes }], SPEC).unwrap(); + let stored = write(document, 4, "test", None, &[Asset { id: "7", mime: "image/png", data: &bytes }], &[], SPEC).unwrap(); let package = read_with_limits(&stored, 4, SPEC, limits).unwrap(); assert_eq!(package.assets, [("7".to_owned(), bytes.clone())]); - let compressed = write(document, 4, "test", None, &[Asset { id: "7", mime: "application/octet-stream", data: &bytes }], SPEC).unwrap(); + let compressed = write(document, 4, "test", None, &[Asset { id: "7", mime: "application/octet-stream", data: &bytes }], &[], SPEC).unwrap(); assert!(read_with_limits(&compressed, 4, SPEC, limits).is_err()); } + + #[test] + fn failed_proxy_reads_are_charged_and_stop_reading_when_the_budget_is_spent() { + let pad = " ".repeat(40_000); + let document = format!(r#"{{"assets":{{"1":{{}},"2":{{}},"3":{{}},"4":{{}}}},"pad":"{pad}"}}"#); + let blobs: Vec> = (1u8..=4).map(|n| vec![n.wrapping_mul(50); 1000]).collect(); + let ids = ["1", "2", "3", "4"]; + let proxies: Vec> = ids.iter().zip(&blobs).map(|(id, data)| Asset { id, mime: "image/png", data }).collect(); + let mut bytes = write(document.as_bytes(), 4, "t", None, &[], &proxies, SPEC).unwrap(); + // Corrupt proxies 1 to 3 so their reads fail their checksum. + for blob in &blobs[..3] { + let at = bytes.windows(blob.len()).position(|w| w == blob.as_slice()).unwrap(); + bytes[at + 500] ^= 0xFF; + } + let source = bytes.len() as u64; + let all = read(&bytes, 4, SPEC).unwrap(); + assert_eq!(all.proxies.len(), 1); + let tight = ReadLimits { json_bytes: 1 << 20, compressed_asset_bytes: 1 << 20, expansion_bytes: 40_100 + 2_500 - source }; + assert!(read_with_limits(&bytes, 4, SPEC, tight).unwrap().proxies.is_empty()); + } } diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index d506252853..0f95b4f76f 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -119,6 +119,10 @@ pub(crate) struct Reader<'p> { pub theme_fills: shape_style::ThemeFills, /// The fill of the group being read (what its members' `a:grpFill` stands for). pub group_fill: Option, + /// The package has no default table style (no styles part, or none marked `w:default`): + /// Word then gives tables no cell margins rather than its Normal Table's 0.08". Set by + /// `read_styles`, which runs before any story with tables is read. + pub no_default_table_style: bool, } /// The package path that internal relationship `id` points at, if it has type `kind` (an `rt` @@ -193,6 +197,7 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, theme_fills: Default::default(), group_fill: None, chunks, + no_default_table_style: true, }; r.doc.missing_pictures.main = main.clone(); r.pc.major_font = r.doc.settings.major_font.clone(); @@ -210,6 +215,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, let fallback = match t { rt::STYLES => "word/styles.xml", rt::NUMBERING => "word/numbering.xml", + rt::FOOTNOTES => "word/footnotes.xml", + rt::ENDNOTES => "word/endnotes.xml", _ => return None, }; pkg.get(fallback).map(|_| fallback.to_string()) diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index 2c8d025b16..dc61b3a288 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -389,15 +389,22 @@ impl PropCtx { } "w:numPr" => { let num = k.child_val("w:numId").and_then(u32_of); - let ilvl = k.child_val("w:ilvl").and_then(u32_of); - let level = ilvl.unwrap_or(0).min(8) as u8; - match (num, ilvl) { - (Some(num), _) => p.numbering = Some(NumRef { num, level }), - // A level without a list: the list comes from the based-on style, as in - // a Heading 3 that only says "level 3" of Heading 2's list. Resolved once - // the styles are read (`resolve_list_levels`). - (None, Some(_)) => p.numbering = Some(NumRef { num: LEVEL_ONLY, level }), - (None, None) => {} + let ilvl_node = k.child("w:ilvl"); + let ilvl = + ilvl_node.and_then(|node| node.attr("w:val")).and_then(int).filter(|level| (0..=8).contains(level)).map(|level| level as u32); + // A missing level means level zero. A present but malformed/out-of-range + // level invalidates this numbering reference instead of silently becoming + // level zero; the latter can turn hostile input into a real list. + if ilvl_node.is_none() || ilvl.is_some() { + let level = ilvl.unwrap_or(0) as u8; + match (num, ilvl) { + (Some(num), _) => p.numbering = Some(NumRef { num, level }), + // A level without a list: the list comes from the based-on style, as in + // a Heading 3 that only says "level 3" of Heading 2's list. Resolved once + // the styles are read (`resolve_list_levels`). + (None, Some(_)) => p.numbering = Some(NumRef { num: LEVEL_ONLY, level }), + (None, None) => {} + } } } "w:pBdr" => p.borders = Some(self.borders(k)), @@ -817,20 +824,21 @@ pub fn sectpr(pc: &PropCtx, e: &El) -> (SectionProps, Vec) { s.footnote_columns = k.attr("w:val").and_then(u32_of).filter(|v| (1..=45).contains(v)); } "w:lnNumType" => { - let mut l = LineNumbering::default(); - if let Some(v) = k.attr("w:countBy").and_then(u32_of) { - l.count_by = v.clamp(1, 100); + // Word leaves line numbering off unless `w:countBy` gives an interval above 0, + // whatever `w:start`, `w:distance` and `w:restart` say (#6209, observed in Word). + if let Some(count_by) = k.attr("w:countBy").and_then(u32_of).filter(|&v| v > 0) { + let mut l = LineNumbering { count_by: count_by.clamp(1, 100), ..LineNumbering::default() }; + if let Some(v) = k.attr("w:start").and_then(int) { + l.start = (v.clamp(0, 32_767) + 1) as u32; + } + l.distance = tw(k, "w:distance").unwrap_or(0.0).max(0.0); + l.restart = match k.attr("w:restart") { + Some("newSection") => LineNumberRestart::Section, + Some("continuous") => LineNumberRestart::Continuous, + _ => LineNumberRestart::Page, + }; + s.line_numbers = Some(l); } - if let Some(v) = k.attr("w:start").and_then(int) { - l.start = (v.clamp(0, 32_767) + 1) as u32; - } - l.distance = tw(k, "w:distance").unwrap_or(0.0).max(0.0); - l.restart = match k.attr("w:restart") { - Some("newSection") => LineNumberRestart::Section, - Some("continuous") => LineNumberRestart::Continuous, - _ => LineNumberRestart::Page, - }; - s.line_numbers = Some(l); } "w:vAlign" => { s.valign = match k.attr("w:val") { diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 0550557f1a..770375365a 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -113,6 +113,8 @@ pub struct StoryCtx { pub story_depth: usize, /// Reading a header or footer (not a text box inside one): where Word keeps its watermark. pub in_hf: bool, + /// Reading a table cell's paragraphs (not a text box inside one). + in_cell: bool, } /// Paragraph content under construction. diff --git a/crates/docx/src/read/story/blocks.rs b/crates/docx/src/read/story/blocks.rs index e72f16bf6f..38c35a02b9 100644 --- a/crates/docx/src/read/story/blocks.rs +++ b/crates/docx/src/read/story/blocks.rs @@ -276,6 +276,10 @@ impl Reader<'_> { if sc.fields.iter().any(|f| f.phase == Phase::Instr) && para.plain_text().is_empty() { para.mark.hidden = Some(true); } + // A cell's paragraphs are marked once their table is read: its style counts. + if !sc.in_cell { + self.doc.styles.mark_runs_as_word_draws_them(&mut para, None); + } para.normalize(); para } @@ -314,15 +318,32 @@ impl Reader<'_> { // ---- tables ---- + /// Word gives a table no cell margins when the file has no default table style and neither the + /// table nor its style sets them; saving may write a default Normal Table, so the zeros are + /// kept as the table's own. shortcut: they stay direct formatting (a table style applied later + /// keeps them), until the model knows the file's default table style. A `w:tblCellMar` that sets + /// only some sides keeps them: only the sides it omits become 0. + fn no_default_margins(&self, props: &mut craft_wordmodel::props::TableProps) { + if self.no_default_table_style + && props.cell_margins.is_none() + && props.style.as_deref().and_then(|id| self.doc.styles.table_style(id)).is_none_or(|s| s.parts.cell_margins.is_none()) + { + props.cell_margins = Some([0.0; 4]); + } + } + fn read_table(&mut self, sc: &mut StoryCtx, t: &El, rels: &Rels, depth: usize) -> Option { let mut table = Table::default(); if let Some(p) = t.child("w:tblPr") { table.props = self.pc.tblpr(p); if let Some(ch) = p.child("w:tblPrChange") { - let old = ch.child("w:tblPr").map(|o| self.pc.tblpr(o)).unwrap_or_default(); + let mut old = ch.child("w:tblPr").map(|o| self.pc.tblpr(o)).unwrap_or_default(); + // Rejecting the change brings back these properties: with the same margins. + self.no_default_margins(&mut old); table.props.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, ch), old); } } + self.no_default_margins(&mut table.props); if let Some(g) = t.child("w:tblGrid") { table.grid = g .children("w:gridCol") @@ -355,8 +376,10 @@ impl Reader<'_> { continue; } let mut blocks = Blocks::new(); + let outer = std::mem::replace(&mut sc.in_cell, true); self.read_blocks(sc, tc, rels, &mut blocks, depth + 4); self.flush_pending(sc, &mut blocks); + sc.in_cell = outer; row.cells.push(Cell { props, blocks, controls: cell_controls }); } if !row.cells.is_empty() { @@ -370,6 +393,20 @@ impl Reader<'_> { let cols = table.cols().clamp(1, MAX_COLS); table.grid = vec![72.0; cols]; } + // The cells' paragraphs, with the run formatting the table style gives each cell (a + // table inside has marked its own). + let chrs = self.doc.styles.table_cells_chr(&table); + for (ri, row) in table.rows.iter_mut().enumerate() { + for (ci, cell) in row.cells.iter_mut().enumerate() { + let chr = chrs.as_ref().and_then(|c| c.get(ri)?.get(ci)); + for b in &mut cell.blocks { + if let Block::Para(p) = Arc::make_mut(b) { + self.doc.styles.mark_runs_as_word_draws_them(p, chr); + p.normalize(); + } + } + } + } Some(table) } } diff --git a/crates/docx/src/read/styles.rs b/crates/docx/src/read/styles.rs index edc17f21fc..e12749a87d 100644 --- a/crates/docx/src/read/styles.rs +++ b/crates/docx/src/read/styles.rs @@ -1,10 +1,22 @@ use super::{ - AbstractNum, DocxError, El, Level, LevelSuffix, Num, NumFormat, PartFormat, Reader, Style, StyleKind, StyleSheet, TablePart, TableStyleParts, - VAlign, flag, int, props, tw, u32_of, + AbstractNum, DocxError, El, Level, LevelSuffix, Num, NumFormat, PartFormat, Reader, RevisionKind, Style, StyleKind, StyleSheet, TablePart, + TableStyleParts, VAlign, flag, int, props, tw, u32_of, }; use crate::units::tw_i16; +use craft_wordmodel::props::PropChange; use std::sync::Arc; +fn numbering_level_index(value: Option<&str>) -> Option { + match value { + None => Some(0), + Some(value) => int(value).filter(|level| (0..=8).contains(level)).map(|level| level as usize), + } +} + +fn style_is_default(style: &El) -> bool { + style.attr("w:default").is_some_and(|value| !matches!(value.trim(), "0" | "false" | "off" | "False" | "FALSE")) +} + /// Built-in style names Word stores in lower case, and how the UI shows them. pub(crate) const LOWER_NAMES: &[(&str, &str)] = &[ ("caption", "Caption"), @@ -52,6 +64,20 @@ fn builtin_heading_level(name: &str) -> Option { } impl Reader<'_> { + /// Whether a style's kept (last) definition is a default table style. + fn has_default_table_style(&self, root: &El) -> bool { + let mut defaults: Vec = Vec::new(); + for s in root.children("w:style").take(10_000) { + let Some(raw_id) = s.attr("w:styleId").filter(|i| !i.is_empty()) else { continue }; + let id = self.pc.style_id(raw_id); + defaults.retain(|d| *d != id); + if s.attr("w:type") == Some("table") && style_is_default(s) { + defaults.push(id); + } + } + !defaults.is_empty() + } + pub(super) fn read_styles(&mut self, path: &str) -> Result<(), DocxError> { /// Largest `w:latentStyles` kept (Word's has ~380 exceptions, ~40 KB). const MAX_LATENT_STYLES_XML: usize = 1 << 20; @@ -59,9 +85,7 @@ impl Reader<'_> { // The default paragraph style must be called `Normal` in our model. let has_normal = root.children("w:style").any(|s| s.attr("w:styleId") == Some("Normal")); if !has_normal - && let Some(def) = root - .children("w:style") - .find(|s| s.attr("w:type") == Some("paragraph") && s.attr("w:default").is_some_and(|v| v == "1" || v == "true")) + && let Some(def) = root.children("w:style").find(|s| s.attr("w:type") == Some("paragraph") && style_is_default(s)) && let Some(id) = def.attr("w:styleId") { self.pc.alias.insert(id.to_string(), "Normal".into()); @@ -85,6 +109,7 @@ impl Reader<'_> { } } let mut sheet = StyleSheet::empty(); + let mut normal_is_default = None; sheet.default_para_present = root.child("w:docDefaults").and_then(|dd| dd.child("w:pPrDefault")).is_some(); if let Some(dd) = root.child("w:docDefaults") { if let Some(r) = dd.child("w:rPrDefault").and_then(|d| d.child("w:rPr")) { @@ -112,6 +137,13 @@ impl Reader<'_> { "numbering" => StyleKind::Numbering, _ => StyleKind::Paragraph, }; + if kind == StyleKind::Paragraph && id == "Normal" { + // Word treats the built-in Normal style as the paragraph default when the file + // doesn't nominate another style. Keep that fact for an explicitly declared + // Normal; the gallery later synthesizes a visually identical Normal when the + // file did not declare one, and that synthetic style is not source provenance. + normal_is_default = Some(s.attr("w:default").is_none()); + } let name = s.child_val("w:name").map(ui_style_name).unwrap_or_else(|| id.clone()); let r = |n: &str| s.child_val(n).filter(|v| !v.is_empty()).map(|v| self.pc.style_id(v)); let mut st = Style { @@ -127,7 +159,7 @@ impl Reader<'_> { builtin: !s.attr("w:customStyle").is_some_and(|v| matches!(v.trim(), "1" | "true" | "on")), locked: flag(s, "w:locked").unwrap_or(false), // Only where the writer couldn't tell from the id (it flags the English ids). - default: s.attr("w:default").is_some_and(|v| v == "1" || v == "true") + default: style_is_default(s) && !matches!( (kind, id.as_str()), (StyleKind::Paragraph, "Normal") @@ -137,26 +169,50 @@ impl Reader<'_> { ), ..Default::default() }; + let mut old_para = None; + let mut old_chr = None; if let Some(p) = s.child("w:pPr") { st.para = self.pc.ppr(p).0; + if let Some(ch) = p.child("w:pPrChange") { + let old = ch.child("w:pPr").map(|o| self.pc.ppr(o).0.formatting()).unwrap_or_default(); + old_para = Some((self.revision(RevisionKind::Format, ch), old)); + } } // Word gives its built-in heading styles their outline level whether or not the file // writes `w:outlineLvl` (some producers leave it out): "heading 2" is level 2 in the // Navigation pane and the table of contents, whatever its id (#4696). if kind == StyleKind::Paragraph && st.builtin - && st.para.outline_level.is_none() && let Some(level) = s.child_val("w:name").and_then(builtin_heading_level) { - st.para.outline_level = Some(level); + if st.para.outline_level.is_none() { + st.para.outline_level = Some(level); + } + if let Some((_, old)) = &mut old_para + && old.outline_level.is_none() + { + old.outline_level = Some(level); + } } if let Some(rp) = s.child("w:rPr") { st.chr = self.pc.rpr(rp); + if let Some(ch) = rp.child("w:rPrChange") { + let old = ch.child("w:rPr").map(|o| self.pc.rpr(o).formatting()).unwrap_or_default(); + old_chr = Some((self.revision(RevisionKind::Format, ch), old)); + } } if kind == StyleKind::Table { let parts = self.table_style_parts(s, &mut st); st.table = (parts != TableStyleParts::default()).then_some(parts); } + // CT_Style has no `stylePrChange`. Keep its two valid revision carriers separate: a + // foreign document may attribute paragraph and run changes to different authors. + if let Some((rev, old)) = old_para { + st.para_change = PropChange::boxed(rev, old); + } + if let Some((rev, old)) = old_chr { + st.chr_change = PropChange::boxed(rev, old); + } // A style defined twice (some generators write their own Heading 1 after a // placeholder one) is the last definition, whole: Word drops the earlier one rather // than merging the two (observed with synthetic documents). @@ -165,6 +221,7 @@ impl Reader<'_> { None => sheet.styles.push(st), } } + self.no_default_table_style = !self.has_default_table_style(&root); // Styles that give only a list level take the list from the style they are based on // (Heading 3: level 3 of Heading 2's outline list). let fixed: Vec> = sheet @@ -181,6 +238,30 @@ impl Reader<'_> { for (s, n) in sheet.styles.iter_mut().zip(fixed) { s.para.numbering = n; } + if !sheet.styles.iter().any(|style| style.kind == StyleKind::Paragraph && style.default) + && normal_is_default == Some(true) + && let Some(normal) = sheet.styles.iter_mut().find(|style| style.kind == StyleKind::Paragraph && style.id == "Normal") + { + normal.default = true; + } + let old_fixed: Vec>> = sheet + .styles + .iter() + .map(|s| { + s.para_change.as_ref().map(|ch| match ch.old.numbering { + Some(n) if n.num == props::LEVEL_ONLY => { + let base = s.based_on.as_deref().and_then(|b| props::chain_list(&sheet, b)); + base.map(|num| craft_wordmodel::props::NumRef { num, level: n.level }) + } + other => other, + }) + }) + .collect(); + for (s, n) in sheet.styles.iter_mut().zip(old_fixed) { + if let (Some(ch), Some(n)) = (&mut s.para_change, n) { + ch.old.numbering = n; + } + } if sheet.default_para.numbering.is_some_and(|n| n.num == props::LEVEL_ONLY) { sheet.default_para.numbering = None; } @@ -250,11 +331,11 @@ impl Reader<'_> { for a in root.children("w:abstractNum").take(10_000) { let Some(id) = a.attr("w:abstractNumId").and_then(u32_of) else { continue }; let mut levels: Vec = (0..9).map(default_level).collect(); + let mut explicit_levels = [false; 9]; for l in a.children("w:lvl") { - let i = l.attr("w:ilvl").and_then(u32_of).unwrap_or(0) as usize; - if let Some(slot) = levels.get_mut(i) { - *slot = self.level(l, i); - } + let Some(i) = numbering_level_index(l.attr("w:ilvl")) else { continue }; + levels[i] = self.level(l, i); + explicit_levels[i] = true; } if let Some(link) = a.child_val("w:numStyleLink") { links.push((id, link.to_string())); @@ -264,6 +345,7 @@ impl Reader<'_> { id, name: a.child_val("w:name").map(str::to_string), levels, + explicit_levels: Some(explicit_levels), nsid: a.child_val("w:nsid").filter(|v| hex(v)).map(str::to_ascii_uppercase), tmpl: a.child_val("w:tmpl").filter(|v| hex(v)).map(str::to_ascii_uppercase), multi_level_type: a @@ -278,7 +360,9 @@ impl Reader<'_> { let (Some(id), Some(abs)) = (n.attr("w:numId").and_then(u32_of), n.child_val("w:abstractNumId").and_then(u32_of)) else { continue }; let (mut start_overrides, mut level_overrides) = (Vec::new(), Vec::new()); for o in n.children("w:lvlOverride").take(9) { - let lvl = o.attr("w:ilvl").and_then(u32_of).unwrap_or(0).min(8) as u8; + let Some(raw_level) = o.attr("w:ilvl") else { continue }; + let Some(lvl) = numbering_level_index(Some(raw_level)) else { continue }; + let lvl = lvl as u8; if let Some(s) = o.child_val("w:startOverride").and_then(u32_of) { start_overrides.push((lvl, s)); } else if let Some(s) = o.child("w:lvl").and_then(|l| l.child_val("w:start")).and_then(u32_of) { @@ -295,9 +379,13 @@ impl Reader<'_> { for (aid, style) in links { let num = self.doc.styles.get(&self.pc.style_id(&style)).and_then(|s| s.para.numbering).map(|n| n.num); let src = num.and_then(|n| nums.iter().find(|x: &&Num| x.id == n)).map(|x| x.abstract_id); - let levels = src.filter(|s| *s != aid).and_then(|s| abstracts.iter().find(|a: &&AbstractNum| a.id == s)).map(|a| a.levels.clone()); - if let (Some(levels), Some(a)) = (levels, abstracts.iter_mut().find(|a| a.id == aid)) { + let source = src + .filter(|s| *s != aid) + .and_then(|s| abstracts.iter().find(|a: &&AbstractNum| a.id == s)) + .map(|a| (a.levels.clone(), a.explicit_levels)); + if let (Some((levels, explicit_levels)), Some(a)) = (source, abstracts.iter_mut().find(|a| a.id == aid)) { a.levels = levels; + a.explicit_levels = explicit_levels; } } Arc::make_mut(&mut self.doc.numbering).abstracts = abstracts; diff --git a/crates/docx/src/units.rs b/crates/docx/src/units.rs index 74edfb13cc..295fe76215 100644 --- a/crates/docx/src/units.rs +++ b/crates/docx/src/units.rs @@ -56,8 +56,12 @@ pub fn measure(s: &str, per_pt: f32) -> Option { "emu" => v / 12_700.0, _ => return None, }; - let pt = pt as f32; - pt.is_finite().then_some(pt.clamp(-MAX_LEN_PT, MAX_LEN_PT)) + // Clamp while still in f64: a large but finite OOXML measurement can overflow f32 before + // the output limit is applied, even though its bounded point value is representable. + if pt.is_nan() { + return None; + } + Some(pt.clamp(-f64::from(MAX_LEN_PT), f64::from(MAX_LEN_PT)) as f32) } /// `w:line` under `lineRule="auto"`: the multiple of single line spacing, in 240ths (240 = @@ -196,6 +200,8 @@ mod tests { assert_eq!(measure("nan", 20.0), None); assert_eq!(measure("1e400", 20.0), None); assert_eq!(measure("99999999999999", 20.0), Some(MAX_LEN_PT)); + assert_eq!(measure("1e300pt", 20.0), Some(MAX_LEN_PT)); + assert_eq!(measure("-1e300pt", 20.0), Some(-MAX_LEN_PT)); assert_eq!(measure("x", 20.0), None); // `w:line` auto: the multiple in 240ths without a unit, through twips with one (#2329). assert_eq!(line_multiple("240"), Some(1.0)); diff --git a/crates/docx/src/write/glossary.rs b/crates/docx/src/write/glossary.rs index 35a2289bcd..7d5a017912 100644 --- a/crates/docx/src/write/glossary.rs +++ b/crates/docx/src/write/glossary.rs @@ -87,7 +87,7 @@ impl Writer<'_> { } rels.add(rt::GLOSSARY, &file(part), false); push_part(entries, overrides, part, w.into_bytes(), GLOSSARY_CONTENT_TYPE, prels); - push_part(entries, overrides, styles, styles_xml(doc), &format!("{CT_WML}styles+xml"), PartRels::default()); + push_part(entries, overrides, styles, styles_xml(self), &format!("{CT_WML}styles+xml"), PartRels::default()); if lists { push_part(entries, overrides, numbering, numbering_xml(doc), &format!("{CT_WML}numbering+xml"), PartRels::default()); } diff --git a/crates/docx/src/write/parts.rs b/crates/docx/src/write/parts.rs index f1b11e8ff9..4cb847276c 100644 --- a/crates/docx/src/write/parts.rs +++ b/crates/docx/src/write/parts.rs @@ -126,7 +126,7 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result { } /// `w:id`, `w:author` and `w:date` of a tracked change by revision `idx`. - pub(super) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { + pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { let (id, author, date) = self.rev_attrs(idx); let mut a = vec![("w:id", id), ("w:author", author)]; if !date.is_empty() { diff --git a/crates/docx/src/write/styles.rs b/crates/docx/src/write/styles.rs index c4013ebff7..3bcf9ab97f 100644 --- a/crates/docx/src/write/styles.rs +++ b/crates/docx/src/write/styles.rs @@ -1,4 +1,6 @@ -use super::{Document, Level, LevelSuffix, ParaProps, Style, StyleKind, TablePart, VAlign, W, props, xml}; +use super::{Level, LevelSuffix, ParaProps, Style, StyleKind, TablePart, VAlign, W, Writer, props, xml}; +use crate::write::props::open_change; +use craft_wordmodel::Document; /// Built-in names Word keeps in lower case in styles.xml. fn file_style_name(name: &str) -> String { @@ -16,7 +18,8 @@ fn file_style_name(name: &str) -> String { name.to_string() } -pub(super) fn styles_xml(doc: &Document) -> Vec { +pub(super) fn styles_xml(wr: &mut Writer<'_>) -> Vec { + let doc = wr.doc; let s = &doc.styles; let mut w = W::new(); let ns = xml::body_ns(); @@ -50,13 +53,15 @@ pub(super) fn styles_xml(doc: &Document) -> Vec { // Kinds whose default style the file named (`w:default`); the English ids stand in otherwise. let flagged: Vec = s.styles.iter().filter(|st| st.default).map(|st| st.kind).collect(); for st in &s.styles { - style_xml(&mut w, st, &flagged); + style_xml(wr, &mut w, st, &flagged); } w.close("w:styles"); w.into_bytes() } -fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { +/// One `w:style` element. A tracked change of its paragraph/run properties is nested in the +/// corresponding property element as `w:pPrChange` / `w:rPrChange`. +fn style_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style, flagged: &[StyleKind]) { let ty = match st.kind { StyleKind::Paragraph => "paragraph", StyleKind::Character => "character", @@ -70,9 +75,14 @@ fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { | (StyleKind::Table, "TableNormal") | (StyleKind::Numbering, "NoList") ); - let is_default = st.default || (english_default && !flagged.contains(&st.kind)); + let normal_is_explicitly_off = st.kind == StyleKind::Paragraph && st.id == "Normal" && !st.default && flagged.contains(&StyleKind::Paragraph); + let is_default = st.default || (english_default && !flagged.contains(&st.kind) && !normal_is_explicitly_off); let mut a = vec![("w:type", ty), ("w:styleId", st.id.as_str())]; - if is_default { + if normal_is_explicitly_off { + // Preserve a model where Normal is explicitly not default. Without this, the fallback + // `english_default` marker makes the reader infer a change on round trip. + a.push(("w:default", "0")); + } else if is_default { a.push(("w:default", "1")); } if !st.builtin { @@ -102,16 +112,7 @@ fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { if st.locked { w.empty("w:locked", &[]); } - if !st.para.is_empty() && st.kind != StyleKind::Character { - w.open("w:pPr", &[]); - props::ppr_inner(w, &st.para, false, None); - w.close("w:pPr"); - } - if props::has_rpr(&st.chr) && st.kind != StyleKind::Numbering { - w.open("w:rPr", &[]); - props::rpr_inner(w, &st.chr); - w.close("w:rPr"); - } + style_property_xml(wr, w, st); if let Some(t) = &st.table { if t.borders.is_some() || t.cell_margins.is_some() || t.band_size.is_some() || t.col_band_size.is_some() { w.open("w:tblPr", &[]); @@ -179,6 +180,37 @@ fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) { w.close("w:style"); } +fn style_property_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style) { + let para_change = st.para_change.as_deref().filter(|ch| ch.old.formatting() != st.para.formatting()); + if (!st.para.is_empty() || para_change.is_some()) && st.kind != StyleKind::Character { + w.open("w:pPr", &[]); + props::ppr_inner(w, &st.para, false, None); + if let Some(ch) = para_change { + let a = wr.change_attrs(ch.rev); + open_change(w, "w:pPrChange", &a); + w.open("w:pPr", &[]); + props::ppr_inner(w, &ch.old, false, None); + w.close("w:pPr"); + w.close("w:pPrChange"); + } + w.close("w:pPr"); + } + let run_change = st.chr_change.as_deref().filter(|ch| ch.old.formatting() != st.chr.formatting()); + if (props::has_rpr(&st.chr) || run_change.is_some()) && st.kind != StyleKind::Numbering { + w.open("w:rPr", &[]); + props::rpr_inner(w, &st.chr); + if let Some(ch) = run_change { + let a = wr.change_attrs(ch.rev); + open_change(w, "w:rPrChange", &a); + w.open("w:rPr", &[]); + props::rpr_inner(w, &ch.old); + w.close("w:rPr"); + w.close("w:rPrChange"); + } + w.close("w:rPr"); + } +} + pub(super) fn numbering_xml(doc: &Document) -> Vec { let mut w = W::new(); let ns = xml::body_ns(); diff --git a/crates/docx/tests/it/bidi.rs b/crates/docx/tests/it/bidi.rs index 3df1c04c90..bea7e21315 100644 --- a/crates/docx/tests/it/bidi.rs +++ b/crates/docx/tests/it/bidi.rs @@ -175,3 +175,155 @@ fn rtl_tables_and_sections_round_trip() { assert_eq!(again, vec![true, false]); assert!(r.last_section.rtl && r.last_section.columns.count == 2); } + +/// A package whose body is `body` and whose styles part holds `styles`. +fn docx_with_styles(body: &str, styles: &str) -> Vec { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let root = r#""#; + let rels = r#""#; + let doc = format!(r#"{body}"#); + let st = format!(r#"{styles}"#); + zip(&[ + ("_rels/.rels", root.as_bytes()), + ("word/_rels/document.xml.rels", rels.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/styles.xml", st.as_bytes()), + ]) +} + +/// Thai text draws in the complex-script formatting only where Word draws it so (measured in Word +/// for Windows; run defaults Angsana New 22 pt, complex script Tahoma 11 pt bold). Without +/// `w:cs` or `w:rtl` on the run, its paragraph style or the run defaults, Thai text measures as +/// Angsana New 22 pt, whatever its language, `w:hint` or character style. +#[test] +fn thai_text_takes_the_complex_script_formatting_only_in_a_complex_script_run() { + let thai = "ทดสอบ ภาษาไทย"; + let defaults = |extra: &str| { + format!( + r#"{extra} + + + + + + +"# + ) + }; + let latin = ("Angsana New", 22.0, false); + let complex = ("Tahoma", 11.0, true); + let run = |rpr: &str| format!(r#"{rpr}{thai}"#); + let styled = |p: &str, rpr: &str| { + format!(r#"{rpr}{thai}"#) + }; + let in_table = |style: &str| { + format!( + r#"{}"#, + run("") + ) + }; + let cs_off = r#""#; + let cases: Vec<(&str, String, String, (&str, f32, bool))> = vec![ + ("plain", defaults(""), run(""), latin), + ("bidi language", defaults(""), run(r#""#), latin), + ("hint", defaults(""), run(r#""#), latin), + ("character style", defaults(""), run(r#""#), latin), + ("character style rtl", defaults(""), run(r#""#), latin), + ("run cs", defaults(""), run(""), complex), + ("run rtl", defaults(""), run(""), complex), + ("paragraph style", defaults(""), styled("CsPara", ""), complex), + ("paragraph style, run cs off", defaults(""), styled("CsPara", r#""#), latin), + ("run defaults", defaults(""), run(""), complex), + // A character style's `w:cs w:val="0"` doesn't turn the paragraph style's or the run + // defaults' off either. + ("paragraph style, character style cs off", defaults(""), styled("CsPara", cs_off), complex), + ("run defaults, character style cs off", defaults(""), run(cs_off), complex), + // A table style's `w:cs` counts, and its sizes are the run's. + ("table style", defaults(""), in_table("CsTable"), complex), + ("table style sizes", defaults(""), in_table("SizeTable"), ("Angsana New", 15.0, false)), + ]; + let check = |d: &Document, name: &str, want: (&str, f32, bool), when: &str| { + let (p, table) = match &*d.body[0] { + craft_wordmodel::Block::Table(t) => { + (t.rows[0].cells[0].blocks[0].as_para().unwrap(), d.styles.table_cells_chr(t).map(|c| c[0][0].clone())) + } + b => (b.as_para().unwrap(), None), + }; + let rc = d.styles.resolve_char_in(p.props.style.as_deref(), table.as_ref(), &p.runs[0].props); + for ch in p.text.chars() { + let drawn = if rc.uses_complex(ch) { rc.complex() } else { rc.clone() }; + assert_eq!((drawn.font.as_str(), drawn.size, drawn.bold), want, "{name} {when}: {ch:?}"); + } + let c = &p.runs[0].props; + assert_eq!((c.font_cs.as_deref(), c.size_cs, c.bold_cs), (None, None, None), "{name} {when}: nothing is pinned"); + }; + for (name, styles, body, want) in &cases { + let d = craft_docx::read(&docx_with_styles(body, styles)).unwrap(); + check(&d, name, *want, "read"); + let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + check(&again, name, *want, "after a save"); + } + // Latin text and right-to-left text are left as they were. + let body = r#"Latin onlyسلام"#; + let d = craft_docx::read(&docx_with_styles(body, &defaults(""))).unwrap(); + for p in paras(&d) { + assert_eq!(p.runs[0].props.cs, None, "{}", p.text); + } + // Latin text follows the same rule (measured): a character style's `w:cs` or `w:rtl` leaves it in the + // run's own formatting, a character style's `w:cs w:val="0"` under a paragraph style's + // `w:cs` in the complex-script formatting. + let latin_in = + |p: &str, rpr: &str| format!(r#"{rpr}Latin"#); + let body = + latin_in("Normal", r#""#) + &latin_in("CsPara", cs_off) + &latin_in("Normal", r#""#); + let d = craft_docx::read(&docx_with_styles(&body, &defaults(""))).unwrap(); + let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + for (d, when) in [(&d, "read"), (&again, "after a save")] { + let drawn: Vec<_> = paras(d) + .iter() + .map(|p| { + let rc = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props); + let c = if rc.uses_complex('L') { rc.complex() } else { rc }; + (c.font, c.size) + }) + .collect(); + assert_eq!(drawn, [("Angsana New".to_string(), 22.0), ("Tahoma".to_string(), 11.0), ("Angsana New".to_string(), 22.0)], "{when}"); + } +} + +/// Measured in Word for Windows: Thai text as a field's result follows the same rule as ordinary +/// text, also when the reader keeps the field as one object with its result. +#[test] +fn a_fields_thai_result_takes_the_complex_script_formatting_only_in_a_complex_script_run() { + let styles = r#" +"#; + let field = |rpr: &str| { + let r = |inner: &str| format!("{rpr}{inner}"); + format!( + "{}{}{}{}{}", + r(r#""#), + r(r#" QUOTE "x" "#), + r(r#""#), + r("ทดสอบ"), + r(r#""#) + ) + }; + let drawn = |d: &Document| { + let p = paras(d)[0]; + let at = p.text.find(craft_wordmodel::para::OBJ).expect("the field is one object"); + let run = p.runs.iter().scan(0, |end, r| { + let start = *end; + *end += r.len; + Some((start, r)) + }); + let (_, run) = run.into_iter().find(|(start, r)| *start <= at && at < start + r.len).unwrap(); + let rc = d.styles.resolve_char(p.props.style.as_deref(), &run.props); + if rc.uses_complex('ท') { (rc.font_cs.clone(), rc.size_cs) } else { (rc.font.clone(), rc.size) } + }; + for (what, rpr, want) in [("nothing", "", ("Angsana New", 10.0)), ("w:cs", "", ("Tahoma", 20.0))] { + let d = craft_docx::read(&docx_with_styles(&field(rpr), styles)).unwrap(); + assert_eq!(drawn(&d), (want.0.to_string(), want.1), "a run with {what}: read"); + let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + assert_eq!(drawn(&again), (want.0.to_string(), want.1), "a run with {what}: after a save"); + } +} diff --git a/crates/docx/tests/it/cell_margin_inheritance.rs b/crates/docx/tests/it/cell_margin_inheritance.rs index f4d8de5a50..83aafc7d0a 100644 --- a/crates/docx/tests/it/cell_margin_inheritance.rs +++ b/crates/docx/tests/it/cell_margin_inheritance.rs @@ -28,3 +28,73 @@ fn partial_margin_stays_partial() { assert!(!margins.contains(") -> Vec { + const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + let mut add = |name: &str, xml: &str| { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(xml.as_bytes()).unwrap(); + }; + add("word/document.xml", &format!(r#"{body}"#)); + if let Some(styles) = styles { + add("word/styles.xml", &format!(r#"{styles}"#)); + add( + "word/_rels/document.xml.rels", + r#""#, + ); + } + zip.finish().unwrap().into_inner() +} + +/// Without a default table style (no styles part, or none marked `w:default`) Word gives a table +/// no cell margins: a cell that sets only its right margin has none on its other sides. +#[test] +fn no_default_table_style_means_no_cell_margins() { + let body = r#""#; + let normal_table = r#""#; + let margins = |styles: Option<&str>| { + let doc = craft_docx::read(&package(body, styles)).unwrap(); + let table = doc.body[0].as_table().unwrap(); + (table.props.cell_margins, table.rows[0].cells[0].props.resolved_margins(table.props.cell_margins.unwrap_or([0.0, 5.4, 0.0, 5.4]))) + }; + assert_eq!(margins(None), (Some([0.0; 4]), [0.0, 0.0, 0.0, 5.4])); + assert_eq!(margins(Some(r#""#)), (Some([0.0; 4]), [0.0, 0.0, 0.0, 5.4])); + // With Word's usual Normal Table the table keeps no margins of its own (the defaults apply). + assert_eq!(margins(Some(normal_table)).0, None); + // A style defined twice is its last definition: a default one redefined as not default leaves none. + let redefined = format!(r#"{normal_table}"#); + assert_eq!(margins(Some(&redefined)).0, Some([0.0; 4])); + // A custom default table style marked `on` is a default too, also after saving and reopening. + let plain = r#""#; + let doc = craft_docx::read(&package(body, Some(plain))).unwrap(); + assert_eq!(doc.body[0].as_table().unwrap().props.cell_margins, None); + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened.body[0].as_table().unwrap().props.cell_margins, None); + // A table that sets only some sides keeps them; the sides it omits are 0. + let partial = body.replace("", r#""#); + let doc = craft_docx::read(&package(&partial, None)).unwrap(); + assert_eq!(doc.body[0].as_table().unwrap().props.cell_margins, Some([0.0, 7.2, 0.0, 0.0])); + // Rejecting a tracked change to the table's properties brings back the same zero margins. + let tracked = body.replace( + "", + r#""#, + ); + let doc = craft_docx::read(&package(&tracked, None)).unwrap(); + let change = doc.body[0].as_table().unwrap().props.fmt_change.as_deref().expect("a tracked table change"); + assert_eq!(change.old.cell_margins, Some([0.0; 4])); + // A table whose own style gives margins keeps them. + let styled = body.replace("", r#""#); + let boxed = r#""#; + let doc = craft_docx::read(&package(&styled, Some(boxed))).unwrap(); + assert_eq!(doc.body[0].as_table().unwrap().props.cell_margins, None); + // The zeros survive saving, which writes a default Normal Table. + let doc = craft_docx::read(&package(body, None)).unwrap(); + let bytes = craft_docx::write(&doc).unwrap(); + let mut xml = String::new(); + zip::ZipArchive::new(Cursor::new(bytes.clone())).unwrap().by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap(); + assert!(xml.contains(""), "{xml}"); + let reopened = craft_docx::read(&bytes).unwrap(); + assert_eq!(reopened.body[0].as_table().unwrap().props.cell_margins, Some([0.0; 4])); +} diff --git a/crates/docx/tests/it/note_comments.rs b/crates/docx/tests/it/note_comments.rs index d333c6adb9..749f658971 100644 --- a/crates/docx/tests/it/note_comments.rs +++ b/crates/docx/tests/it/note_comments.rs @@ -17,6 +17,10 @@ fn note(tag: &str, mark: &str, comment: u32, text: &str) -> String { } fn read_doc() -> Document { + read_doc_with_note_relationships(true) +} + +fn read_doc_with_note_relationships(with_note_relationships: bool) -> Document { let doc = format!( r#"Body"# ); @@ -25,10 +29,15 @@ fn read_doc() -> Document { let comments = format!( r#"On the footnoteOn the endnote"# ); + let doc_rels = if with_note_relationships { + DOC_RELS + } else { + r#""# + }; let bytes = zip(&[ ("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes()), - ("word/_rels/document.xml.rels", DOC_RELS.as_bytes()), + ("word/_rels/document.xml.rels", doc_rels.as_bytes()), ("word/footnotes.xml", footnotes.as_bytes()), ("word/endnotes.xml", endnotes.as_bytes()), ("word/comments.xml", comments.as_bytes()), @@ -36,6 +45,26 @@ fn read_doc() -> Document { craft_docx::read(&bytes).unwrap() } +#[test] +fn conventional_note_parts_are_read_without_relationships() { + let d = read_doc_with_note_relationships(false); + let body = d.body[0].as_para().unwrap(); + let refs: Vec<(NoteKind, u32)> = body + .objects + .iter() + .filter_map(|o| match o { + InlineObject::NoteRef { kind, id, .. } => Some((*kind, *id)), + _ => None, + }) + .collect(); + assert_eq!(refs.iter().map(|(kind, _)| *kind).collect::>(), [NoteKind::Footnote, NoteKind::Endnote]); + for ((kind, id), wanted) in refs.into_iter().zip(["Foot.", "End."]) { + let part = d.parts.get(&id).unwrap_or_else(|| panic!("missing {kind:?} part {id}")); + let text = part.blocks[0].as_para().unwrap().plain_text(); + assert!(text.contains(wanted), "{kind:?}: {text:?}"); + } +} + /// comments.xml has to be read before the notes: a note's `w:commentRangeStart` resolves its id /// against the comments already read, and was dropped when the notes came first. #[test] diff --git a/crates/docx/tests/it/passthrough.rs b/crates/docx/tests/it/passthrough.rs index f59131e17a..9d3176a76c 100644 --- a/crates/docx/tests/it/passthrough.rs +++ b/crates/docx/tests/it/passthrough.rs @@ -320,6 +320,34 @@ fn list_identities_survive_and_a_copied_definition_gets_none() { assert_eq!(n.matches("1F2E3D4C").count(), 1, "{n}"); } +#[test] +fn malformed_numbering_levels_are_skipped_instead_of_becoming_level_zero() { + let numbering = r#""#; + let body = r#"default levelvalid levelnegative levelout of rangeoverflow"#; + let bytes = package(body, &[("rId1", &format!("{REL}/numbering"), "numbering.xml")], &[], &[("word/numbering.xml", numbering)]); + let doc = craft_docx::read(&bytes).unwrap(); + let paragraphs: Vec<_> = doc + .body + .iter() + .filter_map(|block| match &**block { + craft_wordmodel::Block::Para(p) => Some(p), + _ => None, + }) + .collect(); + assert_eq!(paragraphs.len(), 5); + assert!(doc.numbering.level_is_defined(1, 0)); + assert!(!doc.numbering.level_is_defined(1, 2), "effective defaults remain distinguishable from source definitions"); + assert!(doc.numbering.level(1, 2).is_some(), "Word's effective default level remains available"); + assert_eq!(paragraphs[0].props.numbering.map(|n| (n.num, n.level)), Some((1, 0)), "an omitted level defaults to zero"); + assert_eq!(paragraphs[1].props.numbering.map(|n| (n.num, n.level)), Some((1, 2)), "a valid level is preserved"); + for p in ¶graphs[2..] { + assert_eq!(p.props.numbering, None, "malformed explicit level is not treated as a real list: {}", p.text); + } + let level_zero = doc.numbering.level(1, 0).expect("the valid level zero"); + assert_eq!(level_zero.format, craft_wordmodel::section::NumFormat::Decimal); + assert_eq!(level_zero.start, 1, "invalid level overrides do not affect level zero"); +} + #[test] fn extended_properties_are_kept_without_words_counts_and_personal_ones_follow_the_privacy_setting() { let app = r#"4210740000250000Microsoft Office Word020001700falseMFirmafalse290000falsehttps://example.com/false16.0000"#; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 0ee2451801..8f3bbdd0bd 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -269,6 +269,7 @@ fn styles_and_lists_round_trip() { locked: true, default: false, table: None, + ..Default::default() }); Arc::make_mut(&mut d.styles).upsert(Style { id: "MyStyleChar".into(), diff --git a/crates/docx/tests/it/undefined_style.rs b/crates/docx/tests/it/undefined_style.rs index e1a2611cb5..a00ac43233 100644 --- a/crates/docx/tests/it/undefined_style.rs +++ b/crates/docx/tests/it/undefined_style.rs @@ -3,12 +3,20 @@ //! `` without defining Footer. use craft_wordmodel::props::LineSpacing; use craft_wordmodel::{Block, Document, PartKind}; -use std::io::Write; +use std::io::{Read, Write}; const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; fn package(normal_id: &str) -> Vec { + package_with_default(normal_id, true) +} + +fn package_with_default(normal_id: &str, is_default: bool) -> Vec { + package_with_body_default(normal_id, is_default, false) +} + +fn package_with_body_default(normal_id: &str, is_default: bool, has_body_default: bool) -> Vec { let root = r#""#; let doc = format!( r#"bodynormal"# @@ -16,8 +24,11 @@ fn package(normal_id: &str) -> Vec { let footer = format!( r#"1"# ); + let default_attr = if is_default { r#" w:default="1""# } else { "" }; + let body_style = + if has_body_default { r#""# } else { "" }; let styles = format!( - r#""# + r#"{body_style}"# ); let rels = r#""#; let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); @@ -34,6 +45,27 @@ fn package(normal_id: &str) -> Vec { zw.finish().unwrap().into_inner() } +#[test] +fn an_explicit_normal_style_is_the_default_even_without_w_default() { + let doc = craft_docx::read(&package_with_default("Normal", false)).unwrap(); + let normal = doc.styles.get("Normal").expect("the explicit Normal style"); + assert!(normal.default, "Word treats the explicitly declared built-in Normal style as the default"); +} + +#[test] +fn an_explicit_body_default_on_prevents_normal_inference() { + let doc = craft_docx::read(&package_with_body_default("Normal", false, true)).unwrap(); + assert!(doc.styles.styles.iter().any(|style| style.id == "Body" && style.default)); + assert!(!doc.styles.styles.iter().any(|style| style.id == "Normal" && style.default)); + let saved = craft_docx::write(&doc).unwrap(); + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(saved)).unwrap(); + let mut file = archive.by_name("word/styles.xml").unwrap(); + let mut styles = String::new(); + file.read_to_string(&mut styles).unwrap(); + assert!(styles.contains(r#"w:styleId="Normal" w:default="0""#) || styles.contains(r#"w:default="0" w:styleId="Normal""#)); + assert!(styles.contains(r#"w:styleId="Body" w:default="1""#) || styles.contains(r#"w:default="1" w:styleId="Body""#)); +} + fn footer_para(d: &Document) -> &craft_wordmodel::Paragraph { let part = d.parts.values().find(|p| p.kind == PartKind::Footer).expect("a footer"); match part.blocks.first().map(|b| &**b) { diff --git a/crates/dwg/README.md b/crates/dwg/README.md index ed52bdcfc5..80088a89e6 100644 --- a/crates/dwg/README.md +++ b/crates/dwg/README.md @@ -11,7 +11,9 @@ allocation failure inside the decoder. On native applications, call `use_own_wor startup and call `serve_if_asked()` before normal argument handling. Subsequent `decode` and `encode_*` calls then run in a child process with a 30-minute timeout; a crash or stack overflow is contained to that child. The worker has no operating-system memory limit yet. Without a -configured worker, conversions run in the current process. +configured worker, conversions are refused rather than run in the current process: call +`allow_in_process()` only for input that is known to be trusted (tests, or bytes this process +produced itself). Coordinates, once a worker is configured but cannot start, also fail closed. The bridge is not built for `wasm32` or FreeBSD/aarch64. Those targets retain the public API and return a clear unsupported-build error. The `acadrust` 0.6.6 dependency is used unmodified under diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 2db7afeaea..05c1a673c3 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -21,6 +21,11 @@ //! These bound the input- and output-size variants. A small file that declares a huge internal //! table or section can still make the dependency allocate before any size is known, so the app //! runs both directions in a child process ([`worker`]): what that kills is the child. +//! +//! Isolation is not optional for untrusted input. With no worker configured the conversion is +//! refused rather than run here, and a worker that cannot start is an error, so a missing worker +//! never turns into decoding a hostile file in the caller's process. [`worker::allow_in_process`] +//! is the explicit exception, for input the caller knows is trusted. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -65,7 +70,10 @@ fn mb(n: u64) -> String { #[cfg(not(no_dwg_bridge))] pub mod worker; #[cfg(not(no_dwg_bridge))] -pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_kept_noted, encode_noted, serve_if_asked, use_own_worker, use_worker}; +pub use worker::{ + WORKER_ARG, allow_in_process, crash_worker_for_test, decode, encode_as, encode_kept_noted, encode_noted, serve_if_asked, use_own_worker, + use_worker, +}; #[cfg(not(no_dwg_bridge))] mod proxy_transport; @@ -1569,6 +1577,8 @@ pub fn serve_if_asked() -> Option { #[cfg(no_dwg_bridge)] pub fn use_own_worker() {} #[cfg(no_dwg_bridge)] +pub fn allow_in_process() {} +#[cfg(no_dwg_bridge)] pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { dwg_to_dxf_noted(bytes, limits) } diff --git a/crates/dwg/src/worker.rs b/crates/dwg/src/worker.rs index 0c273257bd..1d16f5701b 100644 --- a/crates/dwg/src/worker.rs +++ b/crates/dwg/src/worker.rs @@ -6,9 +6,11 @@ //! that reads one request from standard input and writes one reply to standard output. A file that //! kills the worker then costs that one open or save, and every other open drawing stays safe. //! -//! Without a worker (libraries, tests, a build that can't start one) [`decode`] and [`encode_as`] -//! run in the calling process, as they always did. There's no memory limit on the worker yet: that -//! takes per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate. +//! Without a worker [`decode`] and [`encode_as`] refuse rather than run the conversion in the +//! calling process, because the third-party code is the part that can end a process. +//! [`allow_in_process`] is the explicit exception, for input the caller knows is trusted (tests, or +//! bytes this process produced itself). There's no memory limit on the worker yet: that takes +//! per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate. //! //! A reply comes from a process that just handled a possibly hostile file, so it is parsed as //! untrusted input. @@ -18,6 +20,7 @@ use std::io::{Read, Write}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{RecvTimeoutError, channel}; use std::time::Duration; @@ -38,6 +41,9 @@ const MAX_NOTES_BYTES: u64 = 64 << 20; const MAX_DWG_REPLY: u64 = 2 << 30; /// Most bytes one request holds: the largest input, whichever the direction, and its header. const MAX_REQUEST: u64 = (2 << 30) + 256; +/// What a conversion says when it has no worker and is not allowed to run here. +const NO_WORKER: &str = "DWG: no worker is configured, so this file was not converted; \ + call use_worker or use_own_worker at startup, or allow_in_process for input that is trusted"; struct Worker { program: PathBuf, @@ -45,6 +51,8 @@ struct Worker { } static WORKER: Mutex> = Mutex::new(None); +/// Whether this process may run the conversion itself, set only by [`allow_in_process`]. +static IN_PROCESS: AtomicBool = AtomicBool::new(false); /// Start `program args` as the worker from now on. `program` must call [`serve_if_asked`]. pub fn use_worker(program: PathBuf, args: Vec) { @@ -62,12 +70,27 @@ pub fn use_own_worker() { } } +/// Let [`decode`] and [`encode_as`] run the conversion in this process when no worker is set. +/// +/// This opts out of the isolation the crate exists for: the third-party code allocates from sizes +/// a hostile file declares, and a failed allocation ends the process. Call it for input the caller +/// knows is trusted (tests, or bytes this process produced), never for a file that arrived from +/// outside. +pub fn allow_in_process() { + IN_PROCESS.store(true, Ordering::Relaxed); +} + +fn in_process_allowed() -> bool { + IN_PROCESS.load(Ordering::Relaxed) +} + /// Serve one request and return the exit code if this process was started as a worker. pub fn serve_if_asked() -> Option { (std::env::args_os().nth(1)? == WORKER_ARG).then(|| serve(std::io::stdin().lock(), std::io::stdout().lock())) } -/// [`super::dwg_to_dxf_noted`] in the worker, when there is one. +/// [`super::dwg_to_dxf_noted`] in the worker. With no worker configured this is refused unless +/// [`allow_in_process`] was called; a configured worker that cannot start is an error. pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { // Before starting a process, and so the same limit holds with or without one. if bytes.len() > limits.max_dwg_bytes { @@ -76,17 +99,19 @@ pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), St let reply_limit = (limits.max_dxf_bytes as u64).saturating_add(MAX_NOTES_BYTES); match call(&request(DECODE, limits, ""), bytes, reply_limit, "reading this file") { Some(reply) => reply?, - None => super::dwg_to_dxf_noted(bytes, limits), + None if in_process_allowed() => super::dwg_to_dxf_noted(bytes, limits), + None => Err(NO_WORKER.to_string()), } } -/// [`super::dxf_to_dwg_as`] in the worker, when there is one. +/// [`super::dxf_to_dwg_as`] in the worker. Refused without a worker unless [`allow_in_process`] +/// was called. pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { encode_noted(dxf, version).map(|(dwg, _)| dwg) } -/// [`super::dxf_to_dwg_noted`] in the worker, when there is one. What the writer left out comes -/// back as notes of `TYPEcount`. +/// [`super::dxf_to_dwg_noted`] in the worker. What the writer left out comes back as notes of +/// `TYPEcount`. pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { encode_kept_noted(dxf, version, None) } @@ -103,7 +128,8 @@ pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Resul push_str(&mut header, kept.unwrap_or("")); match call(&header, dxf, MAX_DWG_REPLY, "writing this file") { Some(reply) => reply?.map(|(dwg, notes)| (dwg, unwritten_from(¬es))), - None => encode_here(dxf, version, kept), + None if in_process_allowed() => encode_here(dxf, version, kept), + None => Err(NO_WORKER.to_string()), } } @@ -147,8 +173,9 @@ fn push_str(r: &mut Vec, text: &str) { type Reply = Result<(Vec, Vec), String>; -/// Run one request in a worker. `None`: none could be started, so the caller does the work. -/// `Err`: the worker went wrong, and `doing` says at what, for the user. +/// Run one request in a worker. `None`: no worker is configured, so the caller decides what to do +/// (convert here only with [`allow_in_process`], or refuse). `Err`: a configured worker could not +/// start or went wrong, and `doing` says at what, for the user. fn call(header: &[u8], payload: &[u8], reply_limit: u64, doing: &str) -> Option> { let mut command = { let worker = WORKER.lock().ok()?; @@ -167,14 +194,15 @@ fn call(header: &[u8], payload: &[u8], reply_limit: u64, doing: &str) -> Option< let mut child = match command.spawn() { Ok(c) => c, Err(e) => { + // A worker is configured but cannot run: never fall back to decoding here. log::warn!("DWG worker: can't start it: {e}"); - return None; + return Some(Err(format!("the DWG worker could not start ({e}); nothing else is affected"))); } }; let (Some(mut to_child), Some(from_child)) = (child.stdin.take(), child.stdout.take()) else { let _ = child.kill(); let _ = child.wait(); - return None; + return Some(Err("the DWG worker could not start (no pipes); nothing else is affected".to_string())); }; let received = std::thread::scope(|scope| { // Written beside the read: a worker that replies before it has read everything, or dies, @@ -367,6 +395,25 @@ mod tests { } } + /// A conversion is refused rather than run here, and a worker that cannot start is an error: + /// neither case may turn into decoding a (possibly hostile) file in this process. + #[test] + fn a_conversion_is_refused_without_a_worker_and_never_falls_back_to_this_process() { + // No worker is configured and nothing opted in. + assert_eq!(decode(b"AC1032", Limits::DEFAULT).unwrap_err(), NO_WORKER); + assert_eq!(encode_as(b"not a dxf", "AC1032").unwrap_err(), NO_WORKER); + // Trusted input may run here, and the reader still reports a file it cannot read. + allow_in_process(); + assert!(in_process_allowed()); + assert!(decode(b"AC1032", Limits::DEFAULT).is_err()); + assert!(encode_as(b"not a dxf", "AC1032").is_err()); + // A configured worker that cannot start is an error even after the opt-in: the conversion + // never runs here instead. + use_worker(PathBuf::from("/nonexistent/craft-dwg-worker"), Vec::new()); + assert!(decode(b"AC1032", Limits::DEFAULT).unwrap_err().contains("could not start")); + assert!(encode_as(b"not a dxf", "AC1032").unwrap_err().contains("could not start")); + } + #[test] fn serving_reports_a_decode_failure_as_a_reply() { let mut request = self::request(DECODE, Limits::DEFAULT, ""); diff --git a/crates/eps/README.md b/crates/eps/README.md index f2abd0b2c8..25c8a7eda3 100644 --- a/crates/eps/README.md +++ b/crates/eps/README.md @@ -8,8 +8,10 @@ nothing. |---|---| | `sniff`, `is_eps` | EPS (binary header, or `%!PS-Adobe-… EPSF-…`), plain PostScript or PDF, and whether it is an Illustrator file: PostScript-based (`%AI…` comments, or Illustrator as `%%Creator`) or PDF-based (the `AIPrivateData` / `AIPDFPrivateData` keys near the start or end of the PDF, a hint only) | | `sections` | The parts behind the binary header ("DOS EPS"): the PostScript, the TIFF preview, the Windows metafile preview. A header that points outside the file is an error | +| `postscript_section` | The PostScript program alone; a damaged preview does not prevent a reader from using a valid program section | | `wrap` | PostScript and its previews behind a binary header, as `sections` reads them back | | `Comments::read` | `%%BoundingBox` and `%%HiResBoundingBox` (the first in the header; `(atend)` taken from the trailer, outside embedded documents), `%%Pages`, `%%LanguageLevel`, `%%Creator`, `%%Title` | +| `Comments::read_with_header_limit` | The same comments with a caller-selected header scan limit capped at 256 KiB; `read` defaults to 64 KiB | | `epsi` | The device-independent preview (`%%BeginPreview`, 1, 2, 4 or 8 bits) as an 8-bit grey bitmap | | `ascii85::encode`, `ascii85::decode` | The ASCII85 data encoding; lines never start with `%`, decoding is bounded | diff --git a/crates/eps/src/container.rs b/crates/eps/src/container.rs index ba721f5c2c..245252b838 100644 --- a/crates/eps/src/container.rs +++ b/crates/eps/src/container.rs @@ -27,6 +27,27 @@ pub struct Sections<'a> { pub metafile: Option<&'a [u8]>, } +fn word(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(4).ok_or(Error::OutsideFile)?; + let b = bytes.get(at..end).and_then(|b| <[u8; 4]>::try_from(b).ok()).ok_or(Error::OutsideFile)?; + usize::try_from(u32::from_le_bytes(b)).map_err(|_| Error::OutsideFile) +} + +fn part(bytes: &[u8], at: usize) -> Result<&[u8], Error> { + let len_at = at.checked_add(4).ok_or(Error::OutsideFile)?; + let (start, len) = (word(bytes, at)?, word(bytes, len_at)?); + start.checked_add(len).and_then(|end| bytes.get(start..end)).ok_or(Error::OutsideFile) +} + +/// The PostScript program in an EPS, ignoring preview ranges in its binary header. +/// +/// This is useful to readers that execute only PostScript and historically accepted a valid +/// program section even when a separate preview range was damaged. Use [`sections`] when every +/// declared section must be validated. +pub fn postscript_section(bytes: &[u8]) -> Result<&[u8], Error> { + if bytes.starts_with(&DOS_MAGIC) { part(bytes, 4) } else { Ok(bytes) } +} + /// The sections of an EPS file: its PostScript and previews behind a binary header, or the whole /// file as PostScript. A header that points outside the file is an error, whichever section it /// is: such a file is cut short or not an EPS. @@ -34,17 +55,12 @@ pub fn sections(bytes: &[u8]) -> Result, Error> { if !bytes.starts_with(&DOS_MAGIC) { return Ok(Sections { postscript: bytes, tiff: None, metafile: None }); } - let word = |at: usize| -> Result { - let b = bytes.get(at..at.saturating_add(4)).and_then(|b| <[u8; 4]>::try_from(b).ok()).ok_or(Error::OutsideFile)?; - usize::try_from(u32::from_le_bytes(b)).map_err(|_| Error::OutsideFile) - }; - let part = |at: usize| -> Result<&[u8], Error> { - let (start, len) = (word(at)?, word(at + 4)?); - start.checked_add(len).and_then(|end| bytes.get(start..end)).ok_or(Error::OutsideFile) - }; // A preview with no offset or no length is absent. - let preview = |at: usize| -> Result, Error> { if word(at)? == 0 || word(at + 4)? == 0 { Ok(None) } else { part(at).map(Some) } }; - Ok(Sections { postscript: part(4)?, metafile: preview(12)?, tiff: preview(20)? }) + let preview = |at: usize| -> Result, Error> { + let len_at = at.checked_add(4).ok_or(Error::OutsideFile)?; + if word(bytes, at)? == 0 || word(bytes, len_at)? == 0 { Ok(None) } else { part(bytes, at).map(Some) } + }; + Ok(Sections { postscript: postscript_section(bytes)?, metafile: preview(12)?, tiff: preview(20)? }) } /// `postscript` behind a binary header, followed by its previews. With neither preview the diff --git a/crates/eps/src/dsc.rs b/crates/eps/src/dsc.rs index 835f9b23f8..2334e1d901 100644 --- a/crates/eps/src/dsc.rs +++ b/crates/eps/src/dsc.rs @@ -2,6 +2,8 @@ /// Bytes of a file's start read for its header comments. pub const MAX_HEADER: usize = 64 << 10; +/// Largest header scan available for readers preserving a wider historical bound. +pub const MAX_EXTENDED_HEADER: usize = 256 << 10; /// Bytes of a file's end read for comments its header defers there with `(atend)`. pub const MAX_TRAILER: usize = 64 << 10; @@ -34,7 +36,17 @@ impl Comments { /// A bounding box the header defers with `(atend)` is the last one of the trailer, outside /// any document the file embeds. pub fn read(ps: &[u8]) -> Self { - let head = String::from_utf8_lossy(ps.get(..MAX_HEADER).unwrap_or(ps)); + Self::read_with_header_limit(ps, MAX_HEADER) + } + + /// Read comments with a caller-selected scan limit for the header. + /// + /// The limit is capped at [`MAX_EXTENDED_HEADER`], and the trailer remains capped at + /// [`MAX_TRAILER`]. This lets readers preserve a previously supported wider scan without + /// making header or trailer work unbounded. + pub fn read_with_header_limit(ps: &[u8], header_limit: usize) -> Self { + let header_limit = header_limit.min(MAX_EXTENDED_HEADER).min(ps.len()); + let head = String::from_utf8_lossy(&ps[..header_limit]); let mut c = Comments::default(); let (mut box_atend, mut hires_atend) = (false, false); // Lines may end in `\r` alone (classic Mac files). diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index c3878830bf..c9a2574f57 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -25,8 +25,8 @@ pub mod postscript; mod preview; mod rectangles; -pub use container::{DOS_HEADER, DOS_MAGIC, Sections, sections, wrap}; -pub use dsc::{Comments, MAX_HEADER, MAX_TRAILER}; +pub use container::{DOS_HEADER, DOS_MAGIC, Sections, postscript_section, sections, wrap}; +pub use dsc::{Comments, MAX_EXTENDED_HEADER, MAX_HEADER, MAX_TRAILER}; pub use embedded::{EmbeddedFontProgram, embedded_font_programs}; pub use preview::{Bitmap, MAX_EPSI, epsi}; pub use rectangles::{MAX_SIMPLE_RECTANGLE_SAVE_DEPTH, MAX_SIMPLE_RECTANGLE_TOKENS, MAX_SIMPLE_RECTANGLES, Rectangle, simple_rectangles}; diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 7ac4c84cac..7a26ed09af 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -29,6 +29,24 @@ fn sections_of_plain_and_binary_files() { assert_eq!(sections(&file), Ok(Sections { postscript: EPS, tiff: Some(b"TIFF"), metafile: Some(b"WMF") })); } +#[test] +fn postscript_section_survives_a_damaged_preview_range() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n"; + let mut bytes = wrap(ps, Some(b"tiff"), None).unwrap(); + bytes[20..24].copy_from_slice(&u32::MAX.to_le_bytes()); + bytes[24..28].copy_from_slice(&1u32.to_le_bytes()); + assert_eq!(postscript_section(&bytes), Ok(ps.as_slice())); + assert_eq!(sections(&bytes), Err(Error::OutsideFile)); +} + +#[test] +fn extended_comment_scan_keeps_its_upper_bound() { + let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + ps.resize(ps.len() + MAX_EXTENDED_HEADER + 1, b' '); + ps.extend_from_slice(b"\n%%BoundingBox: 0 0 20 10\n%%EndComments\n"); + assert_eq!(Comments::read_with_header_limit(&ps, usize::MAX).page_box(), None); +} + #[test] fn a_header_that_points_outside_the_file_is_refused() { let file = dos(EPS, b"WMF", b"TIFF"); diff --git a/crates/fig/src/archive.rs b/crates/fig/src/archive.rs index e408ddbe7c..e083aa1dc7 100644 --- a/crates/fig/src/archive.rs +++ b/crates/fig/src/archive.rs @@ -12,8 +12,10 @@ use crate::{Error, corrupt}; const MAX_META: u64 = 1 << 20; /// Largest file [`write_archive`] writes (the canvas and the images together). const MAX_FILE: u64 = 2 * 1024 * 1024 * 1024; -/// Most entries an archive may declare; checked before the archive is indexed. -pub const MAX_ENTRIES: u64 = 1_000_000; +/// Most entries an archive may declare; checked before the archive is indexed. The archive holds one +/// entry per image, so 100 000 leaves room for far more than a `.fig` file carries, and a header +/// count can no longer make the index alone cost a hundred megabytes. +pub const MAX_ENTRIES: u64 = 100_000; /// What one open may read from `images/`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/gif/src/write.rs b/crates/gif/src/write.rs index bc8a4be976..259aa78f16 100644 --- a/crates/gif/src/write.rs +++ b/crates/gif/src/write.rs @@ -194,6 +194,45 @@ pub fn animation(width: u32, height: u32, frames: &[RgbaFrame<'_>], options: Opt writer.finish() } +/// Encode a single pre-quantized indexed-color frame as a GIF89a image. +/// +/// `palette` holds 1 to 256 RGB triplets; `indices` is `width * height` row-major palette indices. +/// When `interlaced` is true, rows are reordered into GIF's 4-pass interlaced order before writing. +pub fn encode_indexed( + width: u32, + height: u32, + palette: &[[u8; 3]], + indices: &[u8], + transparent: Option, + interlaced: bool, +) -> Result, Error> { + let (w, h) = dimensions(width, height)?; + let expected = usize::from(w) * usize::from(h); + if indices.len() != expected { + return Err(Error::FrameLength { index: 0, actual: indices.len(), expected }); + } + if palette.is_empty() || palette.len() > 256 { + return Err(Error::Encode("GIF palette must hold 1 to 256 entries".into())); + } + let flat_palette: Vec = palette.iter().flat_map(|c| *c).collect(); + let buffer = if interlaced { std::borrow::Cow::Owned(interlace(indices, usize::from(w))) } else { std::borrow::Cow::Borrowed(indices) }; + let mut enc = gif::Encoder::new(Vec::new(), w, h, &flat_palette).map_err(Error::from)?; + let frame = gif::Frame { width: w, height: h, buffer, transparent, interlaced, ..gif::Frame::default() }; + enc.write_frame(&frame).map_err(Error::from)?; + enc.into_inner().map_err(Error::from) +} + +/// The rows of a `width`-wide image in GIF's interlaced order: every 8th row from 0, every 8th +/// from 4, every 4th from 2, then every 2nd from 1. +fn interlace(px: &[u8], width: usize) -> Vec { + let rows: Vec<&[u8]> = px.chunks(width.max(1)).collect(); + [(0, 8), (4, 8), (2, 4), (1, 2)] + .into_iter() + .flat_map(|(start, step)| rows.iter().skip(start).step_by(step)) + .flat_map(|r| r.iter().copied()) + .collect() +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] @@ -288,4 +327,17 @@ mod tests { assert_eq!(decoded.frames[0].rgba, red); assert_eq!(decoded.frames[1].rgba, blue); } + + #[test] + fn encode_indexed_validates_and_writes_gif() { + let palette = [[255, 0, 0], [0, 255, 0]]; + let indices = [0u8, 1, 1, 0, 0, 1, 1, 0, 0]; + let bytes = super::encode_indexed(3, 3, &palette, &indices, Some(1), true).unwrap(); + let info = crate::scan(&bytes, 4).unwrap(); + assert_eq!((info.width, info.height), (3, 3)); + assert_eq!(info.frames.len(), 1); + assert_eq!(info.frames[0].transparent, Some(1)); + assert!(super::encode_indexed(2, 2, &[], &[0; 4], None, false).is_err()); + assert!(super::encode_indexed(2, 2, &palette, &[0; 3], None, false).is_err()); + } } diff --git a/crates/hdr/src/lib.rs b/crates/hdr/src/lib.rs index 9d7d3272c3..d462323062 100644 --- a/crates/hdr/src/lib.rs +++ b/crates/hdr/src/lib.rs @@ -11,7 +11,9 @@ //! //! Input is treated as hostile: the header length and the picture size are capped by [`Limits`], //! and every scan line is validated before the float picture is allocated, so a short file cannot -//! ask for a large allocation. +//! ask for a large allocation. Whatever the limits, no buffer is requested past the target's +//! largest allocation (`isize::MAX` bytes), so raised limits on a 32-bit target such as `wasm32` +//! give [`Error::LimitExceeded`] instead of a panic. #[cfg(test)] mod tests; @@ -42,6 +44,7 @@ pub type Result = std::result::Result; #[non_exhaustive] pub struct Limits { /// Most pixels (width × height) a picture may have; each takes 12 bytes decoded. Default 2^26. + /// A picture over the target's largest allocation is refused at any setting. pub max_pixels: u64, /// Longest header read, in bytes (real ones are a few hundred). Default 64 KiB. pub max_header: usize, @@ -62,6 +65,27 @@ pub struct Picture { pub rgb: Vec, } +/// The largest allocation in bytes that a `Vec` or `String` can make on the target. +const MAX_ALLOC_BYTES: u64 = isize::MAX as u64; + +/// Bytes taken by `count` elements of `element_bytes` each, or `None` when the count overflows `u64`. +fn checked_byte_len(count: u64, element_bytes: usize) -> Option { + count.checked_mul(element_bytes as u64) +} + +/// `count` as a length when `count` elements of `element_bytes` each fit in `max_alloc_bytes`. +fn alloc_len(count: u64, element_bytes: usize, max_alloc_bytes: u64) -> Option { + checked_byte_len(count, element_bytes).filter(|&bytes| bytes <= max_alloc_bytes).and_then(|_| usize::try_from(count).ok()) +} + +/// Bytes of `String::from_utf8_lossy(bytes)`: each invalid sequence becomes one U+FFFD (3 bytes). +fn lossy_len(bytes: &[u8]) -> Option { + bytes.utf8_chunks().try_fold(0u64, |n, chunk| { + let invalid = if chunk.invalid().is_empty() { 0 } else { '\u{FFFD}'.len_utf8() }; + n.checked_add(chunk.valid().len() as u64)?.checked_add(invalid as u64) + }) +} + /// Whether `bytes` starts like a Radiance picture. pub fn sniff(bytes: &[u8]) -> bool { bytes.starts_with(b"#?RADIANCE") || bytes.starts_with(b"#?RGBE") @@ -158,6 +182,11 @@ fn scanline(b: &[u8], pos: &mut usize, line: &mut [[u8; 4]]) -> Result<()> { /// Decodes a Radiance picture to linear float RGB, top row first. pub fn decode(b: &[u8], limits: &Limits) -> Result { + decode_within(b, limits, MAX_ALLOC_BYTES) +} + +/// [`decode`] with `max_alloc_bytes` as the largest allocation the target allows. +fn decode_within(b: &[u8], limits: &Limits, max_alloc_bytes: u64) -> Result { if !sniff(b) { return Err(Error::NotHdr); } @@ -166,7 +195,11 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { let line = |pos: &mut usize| -> Result { let rest = b.get(*pos..).ok_or(Error::Malformed("truncated header"))?; let end = rest.iter().take(limits.max_header).position(|&c| c == b'\n').ok_or(Error::Malformed("truncated header"))?; - let s = String::from_utf8_lossy(rest.get(..end).unwrap_or_default()).trim_end_matches('\r').to_string(); + let raw = rest.get(..end).unwrap_or_default(); + if lossy_len(raw).is_none_or(|n| n > max_alloc_bytes) { + return Err(Error::LimitExceeded("header length")); + } + let s = String::from_utf8_lossy(raw).trim_end_matches('\r').to_string(); *pos += end + 1; Ok(s) }; @@ -188,8 +221,9 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { } let res = line(&mut pos)?; let bad = Error::Malformed("bad resolution line"); - let t: Vec<&str> = res.split_whitespace().collect(); - let &[a1, n1, a2, n2] = t.as_slice().first_chunk::<4>().ok_or(bad.clone())?; + // Tokens after the fourth are ignored, so they are not collected. + let mut t = res.split_whitespace(); + let (Some(a1), Some(n1), Some(a2), Some(n2)) = (t.next(), t.next(), t.next(), t.next()) else { return Err(bad) }; let ((x1, p1), (x2, p2)) = (axis(a1).ok_or(bad.clone())?, axis(a2).ok_or(bad.clone())?); if x1 == x2 { return Err(Error::Malformed("resolution line names one axis twice")); @@ -205,6 +239,10 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { if pixels > limits.max_pixels { return Err(Error::LimitExceeded("pixel count")); } + // One scan line of RGBE pixels and the float picture, each within the target's largest allocation. + let scan_len = alloc_len(u64::from(if x1 { height } else { width }), size_of::<[u8; 4]>(), max_alloc_bytes); + let rgb_len = pixels.checked_mul(3).and_then(|floats| alloc_len(floats, size_of::(), max_alloc_bytes)); + let (Some(scan_len), Some(total)) = (scan_len, rgb_len) else { return Err(Error::LimitExceeded("pixel count")) }; // A scan line takes at least a few bits of file, so a header cannot ask for more than the data has. if (b.len().saturating_sub(pos) as u64).saturating_mul(4096) < pixels { return Err(Error::Malformed("truncated pixel data")); @@ -212,12 +250,11 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { // Validate every encoded scan line before allocating the float picture: a short file could // otherwise ask for the whole limit of zeroed pixels and only then fail on its first line. let pixel_data = pos; - let mut scan = vec![[0u8; 4]; n2]; + let mut scan = vec![[0u8; 4]; scan_len]; for _ in 0..n1 { scanline(b, &mut pos, &mut scan)?; } - let total = w.checked_mul(h).and_then(|n| n.checked_mul(3)).ok_or(Error::LimitExceeded("pixel count"))?; let mut rgb = vec![0f32; total]; pos = pixel_data; for i in 0..n1 { diff --git a/crates/hdr/src/tests.rs b/crates/hdr/src/tests.rs index 7e40454b12..576a8db3f9 100644 --- a/crates/hdr/src/tests.rs +++ b/crates/hdr/src/tests.rs @@ -142,3 +142,57 @@ fn limits_are_checked_before_allocating() { assert_eq!(decode(&long, &Limits { max_header: 8, ..Limits::default() }), Err(Error::Malformed("truncated header"))); assert_eq!((Limits::default().max_pixels, Limits::default().max_header), (1 << 26, 64 << 10)); } + +/// `isize::MAX` on a 32-bit target such as `wasm32`. +const BOUND_32: u64 = i32::MAX as u64; + +#[test] +fn buffer_lengths_respect_target_isize_bound() { + // A scan line of RGBE pixels, 4 bytes each. + assert_eq!(alloc_len(536_870_911, 4, BOUND_32), Some(536_870_911)); + assert_eq!(alloc_len(536_870_912, 4, BOUND_32), None); + assert_eq!(alloc_len(u64::from(u32::MAX), 4, BOUND_32), None); + // The float picture: 3 floats of 4 bytes a pixel. + assert_eq!(alloc_len(178_956_970 * 3, 4, BOUND_32), Some(178_956_970 * 3)); + assert_eq!(alloc_len(178_956_971 * 3, 4, BOUND_32), None); + // The default pixel limit fits a 32-bit target. + assert_eq!(alloc_len(Limits::default().max_pixels * 3, 4, BOUND_32), Some(3 << 26)); + assert_eq!(checked_byte_len(u64::MAX, 4), None); + assert_eq!(alloc_len(u64::MAX, 1, MAX_ALLOC_BYTES), None); +} + +#[test] +fn raised_pixel_limit_stops_at_the_target_bound() { + let open = Limits { max_pixels: u64::MAX, ..Limits::default() }; + // 2 × 2 needs an 8-byte scan line and a 48-byte float picture. + let ok = file("-Y 2 +X 2", &[0; 16]); + assert!(decode_within(&ok, &open, 48).is_ok()); + assert_eq!(decode_within(&ok, &open, 47), Err(Error::LimitExceeded("pixel count"))); + // A 1 × 536,870,912 picture is past the 32-bit bound in both buffers; refused before + // anything is allocated, ahead of the scan-line validation. + let wide = file("-Y 1 +X 536870912", &[0; 131_072]); + assert_eq!(decode_within(&wide, &open, BOUND_32), Err(Error::LimitExceeded("pixel count"))); + // 178,956,971 one-pixel scan lines fit the scan buffer but not the float picture. + let tall = file("-Y 178956971 +X 1", &[0; 43_692]); + assert_eq!(decode_within(&tall, &open, BOUND_32), Err(Error::LimitExceeded("pixel count"))); +} + +#[test] +fn header_lines_are_measured_after_lossy_conversion() { + // `#` and ten bytes that are not UTF-8: 11 bytes in the file, 31 as text. + let mut f = b"#?RADIANCE\n#".to_vec(); + f.extend_from_slice(&[0xff; 10]); + f.extend_from_slice(b"\n\n-Y 1 +X 1\n\0\0\0\0"); + assert_eq!(lossy_len(&f[11..22]), Some(31)); + assert!(decode_within(&f, &Limits::default(), 31).is_ok()); + assert_eq!(decode_within(&f, &Limits::default(), 30), Err(Error::LimitExceeded("header length"))); + assert_eq!(lossy_len(b"ok \xe2\x82"), Some(6)); + assert_eq!(lossy_len(b""), Some(0)); +} + +#[test] +fn resolution_tokens_after_the_fourth_are_ignored() { + let f = dec(&file("-Y 1 +X 1 a b c d e f", &[0; 4])).unwrap(); + assert_eq!((f.width, f.height), (1, 1)); + assert_eq!(dec(&file("-Y 1 +X", &[0; 4])), Err(Error::Malformed("bad resolution line"))); +} diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs index 07405a9593..3b2cf45f72 100644 --- a/crates/idml/src/lib.rs +++ b/crates/idml/src/lib.rs @@ -39,7 +39,10 @@ pub mod value; pub use craft_xml::{El, Local, Node}; pub use package::{Document, Limits, Package, write_package}; -pub use part::{CONTAINER_XML, Props, designmap_xml, parse_part, part_root, part_xml, prop, with_props, xml_limits}; +pub use part::{ + CONTAINER_XML, Props, designmap_include, designmap_root, designmap_xml, designmap_xml_with_pi, parse_part, part_root, part_xml, prop, with_props, + xml_limits, +}; /// The IDML package mimetype (content of the first, stored `mimetype` entry). pub const MIMETYPE: &str = "application/vnd.adobe.indesign-idml-package"; @@ -48,6 +51,14 @@ pub const DOM_VERSION: &str = "16.0"; /// The namespace of the `idPkg` prefix. pub const PACKAGING_NS: &str = "http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"; +/// Writes the bounded XMP metadata packet used by an IDML package. Dates are already normalized +/// ISO-8601 values supplied by the caller; this function owns the XML vocabulary and envelope. +pub fn xmp_metadata(create_date: &str, modify_date: &str) -> String { + format!( + "\n\n \n \n {create_date}\n {modify_date}\n \n \n\n" + ) +} + /// Why a package was not read or not written. #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum Error { diff --git a/crates/idml/src/model/document.rs b/crates/idml/src/model/document.rs new file mode 100644 index 0000000000..830b95a3f3 --- /dev/null +++ b/crates/idml/src/model/document.rs @@ -0,0 +1,525 @@ +//! The `Document` tree: root values and included designmap nodes in source order. + +use craft_xml::El; + +use super::{AlternatingFillValues, AlternatingStrokeValues, Spread, Story, StrokeValues, Values}; + +/// One IDML table-of-contents style entry before document style names are resolved. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TocStyleEntryValues { + pub style: Option, + pub level: Option, + pub page_number_position: Option, + pub separator: Option, + pub entry_style: Option, + pub page_number_style: Option, + pub separator_style: Option, + pub sort: Option, +} + +/// An IDML table-of-contents style and its entry grammar. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TocStyleValues { + pub self_id: Option, + pub title: Option, + pub title_style: Option, + pub create_bookmarks: Option, + pub entries: Vec, +} + +/// Date-based IDML text variable kinds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextDateKind { + Creation, + Modification, + Output, +} + +/// Semantically classified `TextVariable` definitions before caller model mapping. +#[derive(Clone, Debug, PartialEq)] +pub enum TextVariableKind { + CustomText { text: String }, + LastPageNumber { section: bool }, + ChapterNumber, + FileName { extension: bool }, + Date { kind: TextDateKind, format: String }, + RunningHeader { style: String, character: bool, last_on_page: bool }, + CrossReference { page_number: bool }, + Imported { variable_type: String, settings_element: String, settings: Vec<(String, String)> }, +} + +/// Parsed values from an IDML `TextVariable` definition. +#[derive(Clone, Debug, PartialEq)] +pub struct TextVariableValues { + pub self_id: Option, + pub name: String, + pub before: String, + pub after: String, + pub kind: TextVariableKind, +} + +/// A recognized IDML cross-reference format building block. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CrossReferenceBuildingBlock { + CustomText(String), + FullParagraph, + ParagraphText, + ParagraphNumber, + PageNumber, + BookmarkName, + ChapterNumber, + FileName, + PartialParagraph { delimiter: String, include_delimiter: bool }, +} + +/// Parsed IDML cross-reference format definition. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CrossReferenceFormatValues { + pub self_id: Option, + pub name: String, + pub blocks: Vec, +} + +impl CrossReferenceFormatValues { + /// Reads a `CrossReferenceFormat` and recognizes its building-block grammar. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let mut result = + Self { self_id: values.self_id().map(str::to_owned), name: values.get("Name").unwrap_or("Format").to_owned(), blocks: Vec::new() }; + for block in el.elements().filter(|child| child.local() == "BuildingBlock") { + let values = Values::of(block); + let text = |key: &str| values.get(key).filter(|value| *value != "$ID/").unwrap_or("").to_owned(); + let parsed = match values.get("BlockType").unwrap_or("") { + "CustomStringBuildingBlock" => Some(CrossReferenceBuildingBlock::CustomText(text("CustomText"))), + "FullParagraphBuildingBlock" => Some(CrossReferenceBuildingBlock::FullParagraph), + "ParagraphTextBuildingBlock" => Some(CrossReferenceBuildingBlock::ParagraphText), + "ParagraphNumberBuildingBlock" => Some(CrossReferenceBuildingBlock::ParagraphNumber), + "PageNumberBuildingBlock" => Some(CrossReferenceBuildingBlock::PageNumber), + "BookmarkNameBuildingBlock" => Some(CrossReferenceBuildingBlock::BookmarkName), + "ChapterNumberBuildingBlock" => Some(CrossReferenceBuildingBlock::ChapterNumber), + "FileNameBuildingBlock" => Some(CrossReferenceBuildingBlock::FileName), + "PartialParagraphBuildingBlock" => Some(CrossReferenceBuildingBlock::PartialParagraph { + delimiter: text("AppliedDelimiter"), + include_delimiter: values.get("IncludeDelimiter") == Some("true"), + }), + _ => None, + }; + if let Some(parsed) = parsed { + result.blocks.push(parsed); + } + } + result + } + + /// Builds an IDML cross-reference format from DesignCraft's stored token definition. + pub fn to_el(self_id: &str, name: &str, definition: &str) -> El { + let mut root = El::new("CrossReferenceFormat").with_attr("Self", self_id).with_attr("Name", name).with_attr("AppliedCharacterStyle", "n"); + let mut index = 0; + let mut block = |root: &mut El, kind: &str, text: &str, delimiter: &str, include: bool| { + root.push( + El::new("BuildingBlock") + .with_attr("Self", format!("{self_id}BuildingBlock{index}")) + .with_attr("BlockType", kind) + .with_attr("AppliedCharacterStyle", "n") + .with_attr("CustomText", if text.is_empty() { "$ID/" } else { text }) + .with_attr("AppliedDelimiter", if delimiter.is_empty() { "$ID/" } else { delimiter }) + .with_attr("IncludeDelimiter", if include { "true" } else { "false" }), + ); + index += 1; + }; + let mut rest = definition; + while let Some(start) = rest.find('<') { + let Some(end) = rest[start..].find('>') else { break }; + if start > 0 { + block(&mut root, "CustomStringBuildingBlock", &rest[..start], "", false); + } + let tag = rest[start + 1..start + end].trim().trim_end_matches('/').trim(); + let attr = + |key: &str| tag.find(&format!("{key}=\"")).and_then(|position| tag[position + key.len() + 2..].split('"').next()).unwrap_or(""); + match tag.split_whitespace().next().unwrap_or("") { + "fullPara" => block(&mut root, "FullParagraphBuildingBlock", "", "", false), + "paraText" => block(&mut root, "ParagraphTextBuildingBlock", "", "", false), + "paraNum" => block(&mut root, "ParagraphNumberBuildingBlock", "", "", false), + "pageNum" => block(&mut root, "PageNumberBuildingBlock", "", "", false), + "txtAnchrName" => block(&mut root, "BookmarkNameBuildingBlock", "", "", false), + "chapNum" => block(&mut root, "ChapterNumberBuildingBlock", "", "", false), + "fileName" => block(&mut root, "FileNameBuildingBlock", "", "", false), + "partialPara" => block(&mut root, "PartialParagraphBuildingBlock", "", attr("delim"), attr("includeDelim") == "true"), + _ => block(&mut root, "CustomStringBuildingBlock", &rest[start..start + end + 1], "", false), + } + rest = &rest[start + end + 1..]; + } + if !rest.is_empty() { + block(&mut root, "CustomStringBuildingBlock", rest, "", false); + } + root + } +} + +/// Parsed EPUB document-splitting preference. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EpubSplitValues { + pub break_document: bool, + pub paragraph_style: Option, +} + +/// Parsed IDML condition metadata. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConditionValues { + pub self_id: Option, + pub name: Option, + pub indicator_rgb: Option<[u8; 3]>, + pub visible: bool, +} + +impl ConditionValues { + /// Reads condition fields and its optional three-channel indicator color. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let rgb: Vec = values + .get("IndicatorColor") + .unwrap_or("") + .split_whitespace() + .filter_map(|value| value.parse::().ok()) + .map(|value| value.clamp(0.0, 255.0) as u8) + .collect(); + Self { + self_id: values.self_id().map(str::to_owned), + name: values.get("Name").map(str::to_owned), + indicator_rgb: (rgb.len() == 3).then(|| [rgb[0], rgb[1], rgb[2]]), + visible: values.get("Visible") != Some("false"), + } + } +} + +/// Parsed IDML numbering-list metadata. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NumberingListValues { + pub name: String, + pub continue_across_stories: bool, +} + +/// Parsed cell-style assignments that are independent of DesignCraft's style resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CellStyleValues { + pub self_id: Option, + pub name: Option, + pub based_on: Option, + pub fill: Option, + pub fill_tint: Option, + pub insets: [Option; 4], + pub vertical_justification: Option, + pub first_baseline: Option, + pub first_baseline_min: Option, + pub paragraph_style: Option, + pub edge_strokes: [StrokeValues; 4], +} + +impl CellStyleValues { + /// Reads the cell-style value assignments and supports the older inset property names. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let inset = |modern, legacy| values.num(modern).or_else(|| values.num(legacy)).map(|v| v.max(0.0)); + Self { + self_id: values.self_id().map(str::to_owned), + name: values.name().map(str::to_owned), + based_on: values.prop("BasedOn"), + fill: values.prop("FillColor"), + fill_tint: values.num("FillTint"), + insets: [ + inset("TextTopInset", "TopInset"), + inset("TextLeftInset", "LeftInset"), + inset("TextBottomInset", "BottomInset"), + inset("TextRightInset", "RightInset"), + ], + vertical_justification: values.get("VerticalJustification").map(str::to_owned), + first_baseline: values.get("FirstBaselineOffset").map(str::to_owned), + first_baseline_min: values.num("MinimumFirstBaselineOffset").filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 8640.0)), + paragraph_style: values.get("AppliedParagraphStyle").map(str::to_owned), + edge_strokes: ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].map(|edge| values.stroke_values(edge)), + } + } +} + +/// Parsed table-style assignments that are independent of DesignCraft's style resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableStyleValues { + pub name: Option, + pub based_on: Option, + pub header_cell_style: Option, + pub body_cell_style: Option, + pub footer_cell_style: Option, + pub left_column_cell_style: Option, + pub right_column_cell_style: Option, + pub header_same_as_body: Option, + pub footer_same_as_body: Option, + pub left_column_same_as_body: Option, + pub right_column_same_as_body: Option, + pub space_before: Option, + pub space_after: Option, + pub border_strokes: [StrokeValues; 4], + pub row_fills: AlternatingFillValues, + pub column_fills: AlternatingFillValues, + pub row_strokes: AlternatingStrokeValues, + pub column_strokes: AlternatingStrokeValues, +} + +impl TableStyleValues { + /// Reads table-style regions, inheritance, spacing, and region reuse values. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + name: values.name().map(str::to_owned), + based_on: values.prop("BasedOn"), + header_cell_style: values.get("HeaderRegionCellStyle").map(str::to_owned), + body_cell_style: values.get("BodyRegionCellStyle").map(str::to_owned), + footer_cell_style: values.get("FooterRegionCellStyle").map(str::to_owned), + left_column_cell_style: values.get("LeftColumnRegionCellStyle").map(str::to_owned), + right_column_cell_style: values.get("RightColumnRegionCellStyle").map(str::to_owned), + header_same_as_body: values.boolean("HeaderRegionSameAsBodyRegion"), + footer_same_as_body: values.boolean("FooterRegionSameAsBodyRegion"), + left_column_same_as_body: values.boolean("LeftColumnRegionSameAsBodyRegion"), + right_column_same_as_body: values.boolean("RightColumnRegionSameAsBodyRegion"), + space_before: values.num("SpaceBefore"), + space_after: values.num("SpaceAfter"), + border_strokes: ["TopBorder", "LeftBorder", "BottomBorder", "RightBorder"].map(|border| values.stroke_values(border)), + row_fills: values.alternating_fill_values("Row"), + column_fills: values.alternating_fill_values("Column"), + row_strokes: values.alternating_stroke_values("Row"), + column_strokes: values.alternating_stroke_values("Column"), + } + } +} + +impl NumberingListValues { + /// Reads a `NumberingList` element. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + name: values.get("Name").unwrap_or("").to_owned(), + continue_across_stories: values.boolean("ContinueNumbersAcrossStories") == Some(true), + } + } +} + +impl EpubSplitValues { + /// Reads an `EPubExportPreference` element. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { break_document: values.boolean("BreakDocument") == Some(true), paragraph_style: values.get("ParagraphStyleName").map(str::to_owned) } + } +} + +impl TextVariableValues { + /// Reads a `TextVariable` and its preference record. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let preference = el.elements().find(|child| child.name.ends_with("Preference")); + let attr = |key: &str| preference.and_then(|child| child.attr(key)).unwrap_or(""); + let variable_type = values.get("VariableType").unwrap_or(""); + let date = |kind| TextVariableKind::Date { kind, format: if attr("Format").is_empty() { "MM/dd/yy".into() } else { attr("Format").into() } }; + let kind = match variable_type { + "CustomTextType" => TextVariableKind::CustomText { text: attr("Contents").into() }, + "LastPageNumberType" => TextVariableKind::LastPageNumber { section: attr("Scope") == "SectionScope" }, + "ChapterNumberType" => TextVariableKind::ChapterNumber, + "FileNameType" if attr("IncludePath") != "true" => TextVariableKind::FileName { extension: attr("IncludeExtension") == "true" }, + "CreationDateType" => date(TextDateKind::Creation), + "ModificationDateType" => date(TextDateKind::Modification), + "OutputDateType" => date(TextDateKind::Output), + "MatchParagraphStyleType" | "MatchCharacterStyleType" => { + let character = variable_type == "MatchCharacterStyleType"; + let style = attr(if character { "AppliedCharacterStyle" } else { "AppliedParagraphStyle" }); + if style.is_empty() { + TextVariableKind::Imported { + variable_type: variable_type.into(), + settings_element: preference.map(|child| child.name.clone()).unwrap_or_default(), + settings: preference.map(|child| child.attrs.clone()).unwrap_or_default(), + } + } else { + TextVariableKind::RunningHeader { style: style.into(), character, last_on_page: attr("SearchStrategy") == "LastOnPage" } + } + } + _ if variable_type.starts_with("Xref") => TextVariableKind::CrossReference { page_number: variable_type == "XrefPageNumberType" }, + _ => TextVariableKind::Imported { + variable_type: variable_type.into(), + settings_element: preference.map(|child| child.name.clone()).unwrap_or_default(), + settings: preference.map(|child| child.attrs.clone()).unwrap_or_default(), + }, + }; + let text = |key: &str| preference.and_then(|child| child.attr(key)).or_else(|| values.get(key)).unwrap_or("").to_owned(); + Self { + self_id: values.self_id().map(str::to_owned), + name: values.get("Name").unwrap_or("").to_owned(), + before: text("TextBefore"), + after: text("TextAfter"), + kind, + } + } +} + +impl TocStyleValues { + /// Reads a `TOCStyle` element and its bounded `TOCStyleEntry` children. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let mut result = Self { + self_id: values.self_id().map(str::to_owned), + title: values.get("Title").map(str::to_owned), + title_style: values.get("TitleStyle").map(str::to_owned), + create_bookmarks: values.get("CreateBookmarks").or_else(|| values.get("CreatePdfBookmarks")).map(|value| value == "true"), + entries: Vec::new(), + }; + result.entries.extend(el.elements().filter(|entry| entry.local() == "TOCStyleEntry").take(64).map(|entry| { + let values = Values::of(entry); + TocStyleEntryValues { + style: values.get("Name").map(str::to_owned), + level: values.get("Level").and_then(|value| value.trim().parse().ok()), + page_number_position: values.get("PageNumberPosition").map(str::to_owned), + separator: values.get("Separator").map(str::to_owned), + entry_style: values.prop("FormatStyle"), + page_number_style: values.prop("PageNumberStyle"), + separator_style: values.prop("SeparatorStyle"), + sort: values.get("Sort").map(|value| value.trim() == "true"), + } + })); + result + } +} + +/// The top-level IDML elements consumed by document importers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TopLevelKind { + DocumentPreference, + TransparencyPreference, + TextPreference, + MarginPreference, + ViewPreference, + GridPreference, + PasteboardPreference, + CompositeFont, + KinsokuTable, + MojikumiTable, + FootnoteOption, + EpubExportPreference, + Layer, + CrossReferenceFormat, + Index, + TextVariable, + Story, + Hyperlink, + HyperlinkUrlDestination, + HyperlinkPageDestination, + HyperlinkPageItemSource, + HyperlinkOtherDestination, + MasterSpread, + Spread, + Section, + TocStyle, + Condition, + NumberingList, + StyleGroup, + Other, +} + +/// One included node in `designmap.xml`, classified by the shared IDML grammar. +#[derive(Clone, Debug, PartialEq)] +pub struct TopLevelNode { + pub kind: TopLevelKind, + data: TopLevelData, +} + +#[derive(Clone, Debug, PartialEq)] +enum TopLevelData { + Story(Story), + Spread(Spread), + Raw(El), +} + +impl TopLevelNode { + fn from_el(el: El) -> TopLevelNode { + let kind = top_level_kind(el.local()); + let data = match kind { + TopLevelKind::Story => TopLevelData::Story(Story::from_el(&el)), + TopLevelKind::Spread | TopLevelKind::MasterSpread => TopLevelData::Spread(Spread::from_el(&el)), + _ => TopLevelData::Raw(el), + }; + TopLevelNode { kind, data } + } + + /// The typed story or spread tree when this is one of those parts. + pub fn story(&self) -> Option<&Story> { + if let TopLevelData::Story(story) = &self.data { Some(story) } else { None } + } + + pub fn spread(&self) -> Option<&Spread> { + if let TopLevelData::Spread(spread) = &self.data { Some(spread) } else { None } + } + + /// The original element, reconstructed from the typed story/spread model where applicable. + pub fn to_el(&self) -> El { + match &self.data { + TopLevelData::Story(story) => story.to_el(), + TopLevelData::Spread(spread) => spread.to_el(), + TopLevelData::Raw(el) => el.clone(), + } + } + + pub fn values(&self) -> Values { + Values::of(&self.to_el()) + } +} + +/// A neutral view of an IDML package's designmap and included top-level parts. +#[derive(Clone, Debug, PartialEq)] +pub struct ModelDocument { + pub root: Values, + pub top: Vec, + pub warnings: Vec, + pub metadata: Option, +} + +impl ModelDocument { + /// Converts the shared bounded package reader's parsed document into typed document nodes. + pub fn from_package(document: crate::Document) -> ModelDocument { + ModelDocument { + root: Values::of(&document.root), + top: document.top.into_iter().map(TopLevelNode::from_el).collect(), + warnings: document.warnings, + metadata: document.metadata, + } + } +} + +fn top_level_kind(name: &str) -> TopLevelKind { + match name { + "DocumentPreference" => TopLevelKind::DocumentPreference, + "TransparencyPreference" => TopLevelKind::TransparencyPreference, + "TextPreference" => TopLevelKind::TextPreference, + "MarginPreference" => TopLevelKind::MarginPreference, + "ViewPreference" => TopLevelKind::ViewPreference, + "GridPreference" => TopLevelKind::GridPreference, + "PasteboardPreference" => TopLevelKind::PasteboardPreference, + "CompositeFont" => TopLevelKind::CompositeFont, + "KinsokuTable" => TopLevelKind::KinsokuTable, + "MojikumiTable" => TopLevelKind::MojikumiTable, + "FootnoteOption" => TopLevelKind::FootnoteOption, + "EPubExportPreference" => TopLevelKind::EpubExportPreference, + "Layer" => TopLevelKind::Layer, + "CrossReferenceFormat" => TopLevelKind::CrossReferenceFormat, + "Index" => TopLevelKind::Index, + "TextVariable" => TopLevelKind::TextVariable, + "Story" => TopLevelKind::Story, + "Hyperlink" => TopLevelKind::Hyperlink, + "HyperlinkURLDestination" => TopLevelKind::HyperlinkUrlDestination, + "HyperlinkPageDestination" => TopLevelKind::HyperlinkPageDestination, + "HyperlinkPageItemSource" => TopLevelKind::HyperlinkPageItemSource, + "MasterSpread" => TopLevelKind::MasterSpread, + "Spread" => TopLevelKind::Spread, + "Section" => TopLevelKind::Section, + "TOCStyle" => TopLevelKind::TocStyle, + "Condition" => TopLevelKind::Condition, + "NumberingList" => TopLevelKind::NumberingList, + name if name.starts_with("Root") && name.ends_with("StyleGroup") => TopLevelKind::StyleGroup, + name if name.starts_with("Hyperlink") && name.ends_with("Destination") => TopLevelKind::HyperlinkOtherDestination, + _ => TopLevelKind::Other, + } +} diff --git a/crates/idml/src/model/effects.rs b/crates/idml/src/model/effects.rs new file mode 100644 index 0000000000..8f5fa95305 --- /dev/null +++ b/crates/idml/src/model/effects.rs @@ -0,0 +1,404 @@ +//! The IDML transparency/effect settings found on page items and object styles. + +use craft_xml::{El, Local, Node}; + +use super::Values; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DropShadowValues { + pub mode: Option, + pub x_offset: Option, + pub y_offset: Option, + pub color: Option, + pub opacity: Option, + pub size: Option, + pub spread: Option, + pub blend_mode: Option, +} + +impl DropShadowValues { + pub fn to_el(&self) -> El { + let mut element = El::new("DropShadowSetting"); + if let Some(value) = &self.mode { + element.set_attr("Mode", value); + } + for (key, value) in + [("XOffset", self.x_offset), ("YOffset", self.y_offset), ("Size", self.size), ("Spread", self.spread), ("Opacity", self.opacity)] + { + if let Some(value) = value { + element.set_attr(key, crate::value::num(value)); + } + } + if let Some(value) = &self.blend_mode { + element.set_attr("BlendMode", value); + } + if let Some(value) = &self.color { + element.set_attr("EffectColor", value); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FeatherValues { + pub mode: Option, + pub width: Option, + pub choke_amount: Option, + pub corner_type: Option, +} + +impl FeatherValues { + pub fn to_el(&self) -> El { + let mut element = El::new("FeatherSetting"); + if let Some(value) = &self.mode { + element.set_attr("Mode", value); + } + for (key, value) in [("Width", self.width), ("ChokeAmount", self.choke_amount)] { + if let Some(value) = value { + element.set_attr(key, crate::value::num(value)); + } + } + if let Some(value) = &self.corner_type { + element.set_attr("CornerType", value); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct OpacityStopValues { + pub location: Option, + pub opacity: Option, +} + +impl OpacityStopValues { + pub fn to_el(&self, self_id: &str, midpoint: bool) -> El { + let mut element = El::new("OpacityGradientStop").with_attr("Self", self_id); + if let Some(value) = self.opacity { + element.set_attr("Opacity", crate::value::num(value)); + } + if let Some(value) = self.location { + element.set_attr("Location", crate::value::num(value)); + } + if midpoint { + element.set_attr("Midpoint", "50"); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GradientFeatherValues { + pub applied: bool, + pub radial: bool, + pub angle: Option, + pub length: Option, + pub start: Option<[f64; 2]>, + pub stops: Vec, +} + +impl GradientFeatherValues { + pub fn to_el(&self, id_prefix: &str) -> El { + let mut element = + El::new("GradientFeatherSetting").with_attr("Applied", "true").with_attr("Type", if self.radial { "Radial" } else { "Linear" }); + if let Some(value) = self.angle { + element.set_attr("Angle", crate::value::num(value)); + } + if let Some(value) = self.length { + element.set_attr("Length", crate::value::num(value)); + } + if let Some([x, y]) = self.start { + element.set_attr("GradientStart", format!("{} {}", crate::value::num(x), crate::value::num(y))); + } + for (index, stop) in self.stops.iter().enumerate() { + let stop_id = format!("{id_prefix}TransparencySetting1GradientFeatherSetting1OpacityGradientStop{index}"); + element.push(stop.to_el(&stop_id, index > 0)); + } + element + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DirectionalFeatherValues { + pub applied: bool, + pub widths: [Option; 4], +} + +impl DirectionalFeatherValues { + pub fn to_el(&self) -> El { + let mut element = El::new("DirectionalFeatherSetting").with_attr("Applied", "true"); + for (key, value) in + [("LeftWidth", self.widths[1]), ("RightWidth", self.widths[3]), ("TopWidth", self.widths[0]), ("BottomWidth", self.widths[2])] + { + if let Some(value) = value { + element.set_attr(key, crate::value::num(value)); + } + } + element + } +} + +/// A typed view of an IDML `TransparencySetting` and its effect elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TransparencySetting { + pub blend_mode: Option, + pub opacity: Option, + pub drop_shadow: Option, + pub feather: Option, + pub gradient_feather: Option, + pub directional_feather: Option, +} + +impl TransparencySetting { + pub fn to_el(&self, id_prefix: &str) -> El { + let mut element = El::new("TransparencySetting"); + if self.blend_mode.is_some() || self.opacity.is_some() { + let mut blending = El::new("BlendingSetting"); + if let Some(value) = &self.blend_mode { + blending.set_attr("BlendMode", value); + } + if let Some(value) = self.opacity { + blending.set_attr("Opacity", crate::value::num(value)); + } + element.push(blending); + } + if let Some(effect) = &self.drop_shadow { + element.push(effect.to_el()); + } + if let Some(effect) = &self.feather { + element.push(effect.to_el()); + } + if let Some(effect) = &self.directional_feather { + element.push(effect.to_el()); + } + if let Some(effect) = &self.gradient_feather { + element.push(effect.to_el(id_prefix)); + } + element + } + + pub fn from_el(el: &El) -> Self { + let child = |name: &str| el.child(Local(name)); + let blending = child("BlendingSetting").map(Values::of); + let drop_shadow = child("DropShadowSetting").map(|el| { + let values = Values::of(el); + DropShadowValues { + mode: values.get("Mode").map(str::to_owned), + x_offset: values.num("XOffset"), + y_offset: values.num("YOffset"), + color: values.get("EffectColor").map(str::to_owned), + opacity: values.num("Opacity"), + size: values.num("Size"), + spread: values.num("Spread"), + blend_mode: values.get("BlendMode").map(str::to_owned), + } + }); + let feather = child("FeatherSetting").map(|el| { + let values = Values::of(el); + FeatherValues { + mode: values.get("Mode").map(str::to_owned), + width: values.num("Width"), + choke_amount: values.num("ChokeAmount"), + corner_type: values.get("CornerType").map(str::to_owned), + } + }); + let gradient_feather = child("GradientFeatherSetting").map(|el| { + let values = Values::of(el); + let start = values + .prop("GradientStart") + .and_then(|value| value.split_whitespace().map(|part| part.parse::().ok().filter(|n| n.is_finite())).collect::>>()) + .and_then(|parts| <[f64; 2]>::try_from(parts).ok()); + GradientFeatherValues { + applied: values.boolean("Applied") == Some(true), + radial: values.get("Type") == Some("Radial"), + angle: values.num("Angle"), + length: values.num("Length"), + start, + stops: el + .elements() + .filter(|stop| stop.local() == "OpacityGradientStop") + .map(|stop| { + let values = Values::of(stop); + OpacityStopValues { location: values.num("Location"), opacity: values.num("Opacity") } + }) + .collect(), + } + }); + let directional_feather = child("DirectionalFeatherSetting").map(|el| { + let values = Values::of(el); + DirectionalFeatherValues { + applied: values.boolean("Applied") == Some(true), + widths: [values.num("TopWidth"), values.num("LeftWidth"), values.num("BottomWidth"), values.num("RightWidth")], + } + }); + Self { + blend_mode: blending.as_ref().and_then(|values| values.get("BlendMode").map(str::to_owned)), + opacity: blending.as_ref().and_then(|values| values.num("Opacity")), + drop_shadow, + feather, + gradient_feather, + directional_feather, + } + } +} + +/// Resolved object-style chain used to inherit item-level IDML settings. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ObjectStyleStack { + chain: Vec, +} + +impl ObjectStyleStack { + /// Resolves a style reference and its `BasedOn` chain (nearest first, cycle-safe, max 16). + pub fn from_styles(styles: &[El], reference: Option<&str>, include_none: bool) -> Self { + let find = |reference: &str| { + styles.iter().find(|style| Values::of(style).self_id() == Some(reference)).or_else(|| { + let normalized = if reference.starts_with("ObjectStyle/") { + reference.to_owned() + } else { + format!("ObjectStyle/{}", crate::value::escape_id(reference.trim())) + }; + styles.iter().find(|style| Values::of(style).self_id() == Some(normalized.as_str())) + }) + }; + let mut chain = Vec::new(); + let mut next = reference.map(str::to_owned); + while let Some(id) = next { + let Some(style) = find(&id) else { break }; + let self_id = Values::of(style).self_id().map(str::to_owned); + if chain.len() >= 16 || self_id.as_deref().is_some_and(|id| chain.iter().any(|entry: &El| Values::of(entry).self_id() == Some(id))) { + break; + } + chain.push(style.clone()); + next = Values::of(style).prop("BasedOn").map(|base| { + let base = base.trim(); + if base.starts_with("ObjectStyle/") { base.to_owned() } else { format!("ObjectStyle/{}", crate::value::escape_id(base)) } + }); + } + if include_none + && !chain.iter().any(|style| Values::of(style).self_id() == Some("ObjectStyle/$ID/[None]")) + && let Some(none) = find("ObjectStyle/$ID/[None]") + { + chain.push(none.clone()); + } + Self { chain } + } + + /// The resolved style elements, nearest first. + pub fn styles(&self) -> &[El] { + &self.chain + } + + /// Merges an item's child over the corresponding elements in the resolved style chain. + pub fn merged_child(&self, item: &El, name: &str) -> Option { + let category = match name { + "TransparencySetting" => Some("ObjectStyleObjectEffectsCategorySettings"), + "StrokeTransparencySetting" => Some("ObjectStyleStrokeEffectsCategorySettings"), + "FillTransparencySetting" => Some("ObjectStyleFillEffectsCategorySettings"), + "ContentTransparencySetting" => Some("ObjectStyleContentEffectsCategorySettings"), + _ => None, + }; + let enabled = |effect: &str| { + let (Some(category), Some(flag)) = (category, effect_flag(effect)) else { return true }; + self.chain.iter().find_map(|style| style.child(Local(category)).and_then(|c| Values::of(c).get(flag).map(str::to_owned))).as_deref() + != Some("false") + }; + let mut result = None; + for style in self.chain.iter().rev() { + let Some(child) = style.child(Local(name)) else { continue }; + let mut child = child.clone(); + child.children.retain(|node| !matches!(node, Node::El(element) if !enabled(element.local()))); + match &mut result { + Some(current) => overlay(current, &child, 0), + None => result = Some(child), + } + } + if let Some(child) = item.child(Local(name)) { + match &mut result { + Some(current) => overlay(current, child, 0), + None => result = Some(child.clone()), + } + } + result + } + + /// Returns the drop-shadow and feather records enabled by the style's effect category. + pub fn enabled_shadow_feather(&self) -> Option { + let category = self.chain.iter().find_map(|style| style.child(Local("ObjectStyleObjectEffectsCategorySettings"))); + let setting = |name: &str| self.chain.iter().find_map(|style| style.child(Local("TransparencySetting"))?.child(Local(name)).cloned()); + let mut result = El::new("TransparencySetting"); + let mut any = false; + for (name, flag) in [("DropShadowSetting", "EnableDropShadow"), ("FeatherSetting", "EnableFeather")] { + let element = setting(name); + let on = match category { + Some(category) => Values::of(category).get(flag) == Some("true"), + None => element.as_ref().and_then(|element| Values::of(element).get("Mode").map(str::to_owned)).is_some_and(|mode| mode != "None"), + }; + any |= on; + if let (true, Some(element)) = (on, element) { + result.push(element); + } + } + any.then_some(result) + } +} + +fn effect_flag(effect: &str) -> Option<&'static str> { + Some(match effect { + "BlendingSetting" => "EnableTransparency", + "DropShadowSetting" => "EnableDropShadow", + "FeatherSetting" => "EnableFeather", + "InnerShadowSetting" => "EnableInnerShadow", + "OuterGlowSetting" => "EnableOuterGlow", + "InnerGlowSetting" => "EnableInnerGlow", + "BevelAndEmbossSetting" => "EnableBevelEmboss", + "SatinSetting" => "EnableSatin", + "DirectionalFeatherSetting" => "EnableDirectionalFeather", + "GradientFeatherSetting" => "EnableGradientFeather", + _ => return None, + }) +} + +fn overlay(base: &mut El, top: &El, depth: usize) { + if depth > 32 { + *base = top.clone(); + return; + } + for (key, value) in &top.attrs { + base.set_attr(key, value); + if let Some(Node::El(properties)) = base.children.iter_mut().find(|node| matches!(node, Node::El(el) if el.local() == "Properties")) { + properties.children.retain(|node| !matches!(node, Node::El(el) if el.local() == key)); + } + } + if let Some(properties) = top.child(Local("Properties")) { + let names: Vec<&str> = properties.elements().map(El::local).collect(); + base.attrs.retain(|(key, _)| !names.contains(&key.as_str())); + } + let has_text = top.children.iter().any(|node| matches!(node, Node::Text(text) | Node::CData(text) if !text.trim().is_empty())); + if has_text { + base.children.retain(|node| !matches!(node, Node::Text(_) | Node::CData(_))); + } + let mut seen: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for node in &top.children { + match node { + Node::El(child) => { + let index = seen.entry(child.local()).or_insert(0); + let slot = base + .children + .iter_mut() + .filter_map(|node| match node { + Node::El(el) if el.local() == child.local() => Some(el), + _ => None, + }) + .nth(*index); + *index += 1; + match slot { + Some(slot) => overlay(slot, child, depth + 1), + None => base.children.push(node.clone()), + } + } + Node::Text(_) | Node::CData(_) if has_text => base.children.push(node.clone()), + Node::Text(_) | Node::CData(_) | Node::Comment(_) | Node::Pi { .. } => {} + } + } +} diff --git a/crates/idml/src/model/geometry.rs b/crates/idml/src/model/geometry.rs index 02b00ddaf7..8047742916 100644 --- a/crates/idml/src/model/geometry.rs +++ b/crates/idml/src/model/geometry.rs @@ -5,6 +5,19 @@ use craft_xml::{El, Local}; use crate::value::{nums, point_str}; +/// Why a bounded path geometry was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum PathGeometryError { + #[error("too many points")] + TooManyPoints, + #[error("point without an anchor")] + MissingAnchor, + #[error("malformed point")] + MalformedPoint, + #[error("non-finite point")] + NonFinitePoint, +} + /// Most points one geometry keeps by default; points past it are dropped. pub const MAX_PATH_POINTS: usize = 1_000_000; @@ -84,6 +97,45 @@ impl PathGeometry { PathGeometry { paths } } + /// Parse a path geometry without silently discarding malformed points, keeping at most + /// `max` point elements. Missing direction handles default to the anchor. + pub fn try_from_el_capped(pg: &El, max: usize) -> Result { + let point = |value: Option<&str>, required: bool| -> Result, PathGeometryError> { + let Some(value) = value else { + return if required { Err(PathGeometryError::MissingAnchor) } else { Ok(None) }; + }; + let mut nums = value.split_whitespace(); + let Some(x) = nums.next().and_then(|n| n.parse::().ok()) else { return Err(PathGeometryError::MalformedPoint) }; + let Some(y) = nums.next().and_then(|n| n.parse::().ok()) else { return Err(PathGeometryError::MalformedPoint) }; + if nums.next().is_some() { + return Err(PathGeometryError::MalformedPoint); + } + if !(x.is_finite() && y.is_finite()) { + return Err(PathGeometryError::NonFinitePoint); + } + Ok(Some([x, y])) + }; + let mut count = 0usize; + let mut paths = Vec::new(); + for geometry in pg.children(Local("GeometryPathType")) { + let mut points = Vec::new(); + if let Some(array) = geometry.child(Local("PathPointArray")) { + for el in array.children(Local("PathPointType")) { + count = count.saturating_add(1); + if count > max { + return Err(PathGeometryError::TooManyPoints); + } + let anchor = point(el.attr("Anchor"), true)?.ok_or(PathGeometryError::MissingAnchor)?; + let left = point(el.attr("LeftDirection"), false)?.unwrap_or(anchor); + let right = point(el.attr("RightDirection"), false)?.unwrap_or(anchor); + points.push(PathPoint { anchor, left, right }); + } + } + paths.push(SubPath { open: geometry.attr("PathOpen") == Some("true"), points }); + } + Ok(PathGeometry { paths }) + } + /// The `PathGeometry` element. pub fn to_el(&self) -> El { let mut pg = El::new("PathGeometry"); diff --git a/crates/idml/src/model/mod.rs b/crates/idml/src/model/mod.rs index 049f10175f..a4560b22e8 100644 --- a/crates/idml/src/model/mod.rs +++ b/crates/idml/src/model/mod.rs @@ -12,20 +12,44 @@ //! Nodes are built from the elements [`crate::Package::document`] gives ([`Spread::from_el`], //! [`spreads`]) and written back with `to_el`, then [`crate::part_xml`]. +mod document; +mod effects; mod geometry; +mod preferences; mod resources; mod spread; mod story; -pub use geometry::{MAX_PATH_POINTS, PathGeometry, PathPoint, SubPath}; -pub use resources::{ - ColorGroup, ColorSpace, GradientStop, StrokeStyle, StrokeStyleKind, Style, StyleGroup, StyleKind, StyleNode, Swatch, SwatchKind, color_groups, - named, preference, stroke_styles, style_groups, swatches, -}; -pub use spread::{Graphic, GraphicChild, GraphicKind, Guide, ItemChild, ItemKind, Link, Page, PageChild, PageItem, Spread, SpreadChild, spreads}; -pub use story::{Ace, CONTAINERS, Cell, Container, ContentPart, Range, Story, Table, TableChild, TextNode, stories}; - use craft_xml::{El, Local, Node}; +pub use document::{ + CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, ModelDocument, NumberingListValues, + TableStyleValues, TextDateKind, TextVariableKind, TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode, +}; +pub use effects::{ + DirectionalFeatherValues, DropShadowValues, FeatherValues, GradientFeatherValues, ObjectStyleStack, OpacityStopValues, TransparencySetting, +}; +pub use geometry::{MAX_PATH_POINTS, PathGeometry, PathGeometryError, PathPoint, SubPath}; +pub use preferences::{DocumentPreferences, FootnotePreferences, GridPreferences, TextFramePreferences}; +pub use resources::{ + CharacterAppearanceValues, CharacterSpecialValues, CharacterTypographyValues, CjkCharacterValues, CjkParagraphValues, ColorDefinition, + ColorGroup, ColorGroupDefinition, ColorGroupMember, ColorSpace, CompositeFontDefinition, CompositeFontEntryDefinition, EpubExportTagMap, + FontDefinition, FontFamilyDefinition, FontsPart, GradientDefinition, GradientStop, GradientStopDefinition, GradientStopValue, GraphicPart, + GrepStyleValue, Ink, InkDefinition, MojikumiRow, NestedLineStyleValue, NestedStyleValue, NestedStyleValues, ObjectStyleValues, + OpenTypeFeatureValues, ParagraphAlignmentValues, ParagraphBoxValues, ParagraphFlowValues, ParagraphListValues, ParagraphSpanValues, RubyValues, + StrokeDefinition, StrokeStyle, StrokeStyleKind, Style, StyleGroup, StyleGroupWriter, StyleKind, StyleNode, Swatch, SwatchKind, TabStopValues, + TextDecorationValues, TintDefinition, color_groups, inks, named, preference, stroke_styles, style_groups, swatches, +}; +pub use spread::{ + BaselineFrameGridOption, BaselineFrameGridRelative, ClippingPathValues, FrameFittingOption, Graphic, GraphicChild, GraphicKind, + GraphicLayerOptions, Guide, ItemChild, ItemKind, Link, MarginPreference, Page, PageChild, PageItem, PdfAttribute, Spread, SpreadChild, TextPath, + TextWrapPreference, spreads, +}; +pub use story::{ + Ace, AnchoredObjectSetting, AnchoredObjectValues, CONTAINERS, Cell, CellOptions, Container, ContainerKind, ContentPart, CrossReferenceSource, + IndexCrossReferenceValues, IndexDocument, IndexReference, IndexTopicPath, IndexValues, PageReference, Range, SavedCrossReference, + SavedCrossReferencePart, Story, StoryAnchor, StoryPreference, Table, TableChild, TableColumn, TableLayout, TableRow, TextNode, TrackedChangeKind, + stories, +}; use crate::value::{matrix, nums}; @@ -43,6 +67,157 @@ pub struct Values { pub properties: Vec, } +/// Raw IDML stroke values before the caller maps swatches and stroke styles into its model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StrokeValues { + pub weight: Option, + pub color: Option, + pub tint: Option, + pub kind: Option, + pub alignment: Option, + pub cap: Option, + pub join: Option, + pub miter_limit: Option, + pub start: Option, + pub end: Option, + pub gap_color: Option, + pub gap_tint: Option, + pub overprint: Option, + pub gap_overprint: Option, +} + +impl StrokeValues { + /// Reads stroke properties from elements in precedence order (item first, then nearer styles). + pub fn from_elements(elements: &[&El]) -> StrokeValues { + let mut result = StrokeValues::default(); + for el in elements { + let values = Values::of(el); + let num_attr = |key: &str| values.get(key).and_then(|value| value.parse::().ok()).filter(|value| value.is_finite()); + let bool_attr = |key: &str| match values.get(key) { + Some("true") => Some(true), + Some("false") => Some(false), + _ => None, + }; + if result.weight.is_none() { + result.weight = num_attr("StrokeWeight"); + } + if result.color.is_none() { + result.color = values.get("StrokeColor").map(str::to_owned); + } + if result.tint.is_none() { + result.tint = num_attr("StrokeTint"); + } + if result.kind.is_none() { + result.kind = values.get("StrokeType").map(str::to_owned); + } + if result.alignment.is_none() { + result.alignment = values.get("StrokeAlignment").map(str::to_owned); + } + if result.cap.is_none() { + result.cap = values.get("EndCap").map(str::to_owned); + } + if result.join.is_none() { + result.join = values.get("EndJoin").map(str::to_owned); + } + if result.miter_limit.is_none() { + result.miter_limit = num_attr("MiterLimit"); + } + if result.start.is_none() { + result.start = values.get("LeftLineEnd").map(str::to_owned); + } + if result.end.is_none() { + result.end = values.get("RightLineEnd").map(str::to_owned); + } + if result.gap_color.is_none() { + result.gap_color = values.get("GapColor").map(str::to_owned); + } + if result.gap_tint.is_none() { + result.gap_tint = num_attr("GapTint"); + } + if result.overprint.is_none() { + result.overprint = bool_attr("OverprintStroke"); + } + if result.gap_overprint.is_none() { + result.gap_overprint = bool_attr("OverprintGap"); + } + } + result + } +} + +/// Raw fill properties before a caller resolves swatch names to its own colour model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FillValues { + pub color: Option, + pub tint: Option, + pub overprint: Option, +} + +impl FillValues { + /// Reads fill attributes in precedence order (item first, then nearer styles). + pub fn from_elements(elements: &[&El]) -> FillValues { + let mut result = FillValues::default(); + for el in elements { + let values = Values::of(el); + if result.color.is_none() { + result.color = values.get("FillColor").map(str::to_owned); + } + if result.tint.is_none() { + result.tint = values.get("FillTint").and_then(|value| value.parse::().ok()); + } + if result.overprint.is_none() { + result.overprint = match values.get("OverprintFill") { + Some("true") => Some(true), + Some("false") => Some(false), + _ => None, + }; + } + } + result + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AlternatingFillValues { + pub first_count: Option, + pub first_color: Option, + pub first_tint: Option, + pub next_count: Option, + pub next_color: Option, + pub next_tint: Option, + pub skip_first: Option, + pub skip_last: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AlternatingStrokeValues { + pub first_count: Option, + pub next_count: Option, + pub first: StrokeValues, + pub next: StrokeValues, + pub skip_first: Option, + pub skip_last: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableOptions { + pub direction: Option, + pub header_rows: Option, + pub footer_rows: Option, + pub applied_style: Option, + pub space_before: Option, + pub space_after: Option, + pub repeat_header: bool, + pub repeat_footer: bool, + pub borders: [StrokeValues; 4], +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CornerValues { + pub option: Option, + pub radius: Option, +} + impl Values { /// The attributes and `` of `el`. pub fn of(el: &El) -> Values { @@ -104,6 +279,13 @@ impl Values { self.prop(key).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) } + /// A two-number value (for properties such as `GradientFillStart`), bounded to three tokens. + pub fn pair(&self, key: &str) -> Option<[f64; 2]> { + let source = self.prop(key)?; + let values: Vec = source.split_whitespace().take(3).filter_map(|v| v.parse::().ok()).collect(); + <[f64; 2]>::try_from(values).ok().filter(|v| v.iter().all(|n| n.is_finite())) + } + /// `true` or `false`; anything else counts as absent. pub fn boolean(&self, key: &str) -> Option { match self.prop(key)?.trim() { @@ -154,6 +336,77 @@ impl Values { } el } + + /// Read an IDML stroke attribute family such as `TopEdgeStrokeWeight` or + /// `StartRowStrokeColor`. + pub fn stroke_values(&self, prefix: &str) -> StrokeValues { + StrokeValues { + weight: self.num(&format!("{prefix}StrokeWeight")).map(|v| v.max(0.0)), + color: self.value(&format!("{prefix}StrokeColor")), + tint: self.num(&format!("{prefix}StrokeTint")), + kind: self.value(&format!("{prefix}StrokeType")), + gap_color: self.value(&format!("{prefix}StrokeGapColor")), + gap_tint: self.num(&format!("{prefix}StrokeGapTint")), + ..StrokeValues::default() + } + } + + pub fn alternating_fill_values(&self, kind: &str) -> AlternatingFillValues { + let num = |key: &str| self.num(key).map(|v| v.max(0.0)); + AlternatingFillValues { + first_count: num(&format!("Start{kind}FillCount")), + first_color: self.value(&format!("Start{kind}FillColor")), + first_tint: self.num(&format!("Start{kind}FillTint")), + next_count: num(&format!("End{kind}FillCount")), + next_color: self.value(&format!("End{kind}FillColor")), + next_tint: self.num(&format!("End{kind}FillTint")), + skip_first: num(&format!("SkipFirstAlternatingFill{kind}s")), + skip_last: num(&format!("SkipLastAlternatingFill{kind}s")), + } + } + + pub fn alternating_stroke_values(&self, kind: &str) -> AlternatingStrokeValues { + let num = |key: &str| self.num(key).map(|v| v.max(0.0)); + let mut next = self.stroke_values(&format!("End{kind}")); + // IDML writes this one table-column value as LineStyle rather than StrokeType. + if kind == "Column" { + next.kind = self.value("EndColumnLineStyle").or(next.kind); + } + AlternatingStrokeValues { + first_count: num(&format!("Start{kind}StrokeCount")), + next_count: num(&format!("End{kind}StrokeCount")), + first: self.stroke_values(&format!("Start{kind}")), + next, + skip_first: num(&format!("SkipFirstAlternatingStroke{kind}s")), + skip_last: num(&format!("SkipLastAlternatingStroke{kind}s")), + } + } + + pub fn table_options(&self) -> TableOptions { + TableOptions { + direction: self.value("TableDirection"), + header_rows: self.num("HeaderRowCount"), + footer_rows: self.num("FooterRowCount"), + applied_style: self.value("AppliedTableStyle"), + space_before: self.num("SpaceBefore"), + space_after: self.num("SpaceAfter"), + repeat_header: self.get("HeaderBehavior") != Some("RepeatOnce"), + repeat_footer: self.get("FooterBehavior") != Some("RepeatOnce"), + borders: [ + self.stroke_values("TopBorder"), + self.stroke_values("LeftBorder"), + self.stroke_values("BottomBorder"), + self.stroke_values("RightBorder"), + ], + } + } + + pub fn corner_values(&self, corner: &str) -> CornerValues { + CornerValues { + option: self.value(&format!("{corner}CornerOption")).or_else(|| self.value("CornerOption")), + radius: self.num(&format!("{corner}CornerRadius")).or_else(|| self.num("CornerRadius")), + } + } } /// `el` without its indentation: the whitespace-only text between the children of an element diff --git a/crates/idml/src/model/preferences.rs b/crates/idml/src/model/preferences.rs new file mode 100644 index 0000000000..b32317cbda --- /dev/null +++ b/crates/idml/src/model/preferences.rs @@ -0,0 +1,420 @@ +//! Typed views of IDML's reusable text-frame preference grammar. + +use craft_xml::El; + +use super::Values; + +/// Parsed values from IDML `DocumentPreference` elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DocumentPreferences { + pub overprint_black: Option, + pub page_width: Option, + pub page_height: Option, + pub facing_pages: Option, + pub page_binding: Option, + pub bleed: [Option; 4], + pub slug: [Option; 4], + pub intent: Option, + pub primary_text_frame: Option, + pub column_guides_locked: Option, +} + +impl DocumentPreferences { + /// Reads the document-level page, bleed, slug, and intent values. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + overprint_black: values.get("OverprintBlack").map(|value| value != "false"), + page_width: values.num("PageWidth"), + page_height: values.num("PageHeight"), + facing_pages: values.boolean("FacingPages"), + page_binding: values.prop("PageBinding"), + bleed: [ + values.num("DocumentBleedTopOffset"), + values.num("DocumentBleedBottomOffset"), + values.num("DocumentBleedInsideOrLeftOffset"), + values.num("DocumentBleedOutsideOrRightOffset"), + ], + slug: [ + values.num("SlugTopOffset"), + values.num("SlugBottomOffset"), + values.num("SlugInsideOrLeftOffset"), + values.num("SlugRightOrOutsideOffset"), + ], + intent: values.prop("Intent"), + primary_text_frame: values.boolean("CreatePrimaryTextFrame"), + column_guides_locked: values.boolean("ColumnGuideLocked"), + } + } + + /// Full canonical attributes for an exported IDML `DocumentPreference`. + pub fn to_export_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [("PageHeight", self.page_height), ("PageWidth", self.page_width)] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + attrs.push(("PagesPerDocument".into(), "1".into())); + if let Some(value) = self.facing_pages { + attrs.push(("FacingPages".into(), if value { "true" } else { "false" }.into())); + } + for (key, value) in [ + ("DocumentBleedTopOffset", self.bleed[0]), + ("DocumentBleedBottomOffset", self.bleed[1]), + ("DocumentBleedInsideOrLeftOffset", self.bleed[2]), + ("DocumentBleedOutsideOrRightOffset", self.bleed[3]), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if self.bleed.iter().all(Option::is_some) { + attrs.push(( + "DocumentBleedUniformSize".into(), + bool_string(self.bleed.iter().flatten().all(|value| *value == self.bleed[0].unwrap_or_default())), + )); + } + for (key, value) in [ + ("SlugTopOffset", self.slug[0]), + ("SlugBottomOffset", self.slug[1]), + ("SlugInsideOrLeftOffset", self.slug[2]), + ("SlugRightOrOutsideOffset", self.slug[3]), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if self.slug.iter().all(Option::is_some) { + attrs.push(( + "DocumentSlugUniformSize".into(), + bool_string(self.slug.iter().flatten().all(|value| *value == self.slug[0].unwrap_or_default())), + )); + } + attrs.push(("PreserveLayoutWhenShuffling".into(), "true".into())); + attrs.push(("AllowPageShuffle".into(), "true".into())); + if let Some(value) = self.overprint_black { + attrs.push(("OverprintBlack".into(), bool_string(value))); + } + if let Some(value) = &self.page_binding { + attrs.push(("PageBinding".into(), value.clone())); + } + attrs.push(("ColumnDirection".into(), "Horizontal".into())); + if let Some(value) = &self.intent { + attrs.push(("Intent".into(), value.clone())); + } + if let Some(value) = self.primary_text_frame { + attrs.push(("CreatePrimaryTextFrame".into(), bool_string(value))); + } + if let Some(value) = self.column_guides_locked { + attrs.push(("ColumnGuideLocked".into(), bool_string(value))); + } + if let Some(value) = self.primary_text_frame { + attrs.push(("MasterTextFrame".into(), bool_string(value))); + } + attrs.push(("SnippetImportUsesOriginalLocation".into(), "false".into())); + attrs + } +} + +/// Parsed document and baseline-grid preference values. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GridPreferences { + pub baseline_start: Option, + pub baseline_division: Option, + pub baseline_view_threshold: Option, + pub baseline_relative_option: Option, + pub horizontal_division: Option, + pub vertical_division: Option, + pub horizontal_subdivision: Option, + pub vertical_subdivision: Option, + pub grids_in_back: Option, +} + +/// Parsed values from IDML `FootnoteOption` elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FootnotePreferences { + pub start_at: Option, + pub prefix: Option, + pub suffix: Option, + pub paragraph_style: Option, + pub marker_style: Option, + pub separator: Option, + pub space_between: Option, + pub space_before: Option, + pub first_baseline: Option, + pub first_baseline_minimum: Option, + pub span_columns: Option, + pub rule_on: Option, + pub rule_weight: Option, + pub rule_tint: Option, + pub rule_left_indent: Option, + pub rule_width: Option, + pub rule_offset: Option, + pub rule_color: Option, + pub numbering_style: Option, + pub restart_numbering: Option, + pub show_prefix_suffix: Option, + pub marker_positioning: Option, +} + +impl FootnotePreferences { + /// Reads footnote preference attributes and properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + start_at: values.num("StartAt"), + prefix: values.get("Prefix").map(str::to_owned), + suffix: values.get("Suffix").map(str::to_owned), + paragraph_style: values.get("FootnoteTextStyle").map(str::to_owned), + marker_style: values.get("FootnoteMarkerStyle").map(str::to_owned), + separator: values.get("SeparatorText").map(str::to_owned), + space_between: values.num("SpaceBetween"), + space_before: values.num("Spacer"), + first_baseline: values.prop("FootnoteFirstBaselineOffset"), + first_baseline_minimum: values.num("FootnoteMinimumFirstBaselineOffset"), + span_columns: values.boolean("EnableStraddling"), + rule_on: values.boolean("RuleOn"), + rule_weight: values.num("RuleLineWeight"), + rule_tint: values.num("RuleTint"), + rule_left_indent: values.num("RuleLeftIndent"), + rule_width: values.num("RuleWidth"), + rule_offset: values.num("RuleOffset"), + rule_color: values.prop("RuleColor"), + numbering_style: values.prop("FootnoteNumberingStyle"), + restart_numbering: values.prop("RestartNumbering"), + show_prefix_suffix: values.prop("ShowPrefixSuffix"), + marker_positioning: values.prop("MarkerPositioning"), + } + } + + /// Writes one canonical IDML `FootnoteOption` using caller-resolved style, colour, and enum + /// references. + pub fn to_el(&self) -> El { + let mut el = El::new("FootnoteOption") + .with_attr("StartAt", crate::value::num(self.start_at.unwrap_or(1.0))) + .with_attr("Prefix", self.prefix.as_deref().unwrap_or("")) + .with_attr("Suffix", self.suffix.as_deref().unwrap_or("")) + .with_attr("FootnoteTextStyle", self.paragraph_style.as_deref().unwrap_or("$ID/NormalParagraphStyle")) + .with_attr("FootnoteMarkerStyle", self.marker_style.as_deref().unwrap_or("$ID/[None]")) + .with_attr("SeparatorText", self.separator.as_deref().unwrap_or("")) + .with_attr("SpaceBetween", crate::value::num(self.space_between.unwrap_or(0.0))) + .with_attr("Spacer", crate::value::num(self.space_before.unwrap_or(0.0))) + .with_attr("FootnoteFirstBaselineOffset", self.first_baseline.as_deref().unwrap_or("Ascent")) + .with_attr("FootnoteMinimumFirstBaselineOffset", crate::value::num(self.first_baseline_minimum.unwrap_or(0.0))) + .with_attr("EnableStraddling", bool_text(self.span_columns.unwrap_or(false))) + .with_attr("RuleOn", bool_text(self.rule_on.unwrap_or(true))) + .with_attr("RuleLineWeight", crate::value::num(self.rule_weight.unwrap_or(1.0))) + .with_attr("RuleTint", crate::value::num(self.rule_tint.unwrap_or(1.0))) + .with_attr("RuleLeftIndent", crate::value::num(self.rule_left_indent.unwrap_or(0.0))) + .with_attr("RuleWidth", crate::value::num(self.rule_width.unwrap_or(72.0))) + .with_attr("RuleOffset", crate::value::num(self.rule_offset.unwrap_or(0.0))); + let mut properties = El::new("Properties"); + for (name, value) in [ + ("FootnoteNumberingStyle", self.numbering_style.as_deref().unwrap_or("Arabic")), + ("RestartNumbering", self.restart_numbering.as_deref().unwrap_or("DontRestart")), + ("ShowPrefixSuffix", self.show_prefix_suffix.as_deref().unwrap_or("NoPrefixSuffix")), + ("MarkerPositioning", self.marker_positioning.as_deref().unwrap_or("Superscript")), + ] { + properties.push(El::new(name).with_attr("type", "enumeration").with_text(value)); + } + properties.push(El::new("RuleColor").with_attr("type", "object").with_text(self.rule_color.as_deref().unwrap_or("Swatch/Black"))); + el.push(properties); + el + } +} + +impl GridPreferences { + /// Reads baseline and document-grid values. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + baseline_start: values.num("BaselineStart"), + baseline_division: values.num("BaselineDivision"), + baseline_view_threshold: values.num("BaselineViewThreshold"), + baseline_relative_option: values.prop("BaselineGridRelativeOption"), + horizontal_division: values.num("HorizontalGridlineDivision"), + vertical_division: values.num("VerticalGridlineDivision"), + horizontal_subdivision: values.num("HorizontalGridSubdivision"), + vertical_subdivision: values.num("VerticalGridSubdivision"), + grids_in_back: values.boolean("GridsInBack"), + } + } + + /// IDML attributes represented by this grid preference record. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [ + ("HorizontalGridlineDivision", self.horizontal_division), + ("VerticalGridlineDivision", self.vertical_division), + ("HorizontalGridSubdivision", self.horizontal_subdivision), + ("VerticalGridSubdivision", self.vertical_subdivision), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if let Some(value) = self.grids_in_back { + attrs.push(("GridsInBack".into(), if value { "true" } else { "false" }.into())); + } + for (key, value) in [ + ("BaselineStart", self.baseline_start), + ("BaselineDivision", self.baseline_division), + ("BaselineViewThreshold", self.baseline_view_threshold), + ] { + if let Some(value) = value { + attrs.push((key.into(), crate::value::num(value))); + } + } + if let Some(value) = self.baseline_relative_option.as_deref() { + attrs.push(("BaselineGridRelativeOption".into(), value.into())); + } + attrs + } +} + +fn bool_string(value: bool) -> String { + if value { "true" } else { "false" }.into() +} + +/// Parsed `TextFramePreference` values in nearest-to-farthest precedence order. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TextFramePreferences { + pub column_count: Option, + pub column_gutter: Option, + pub fixed_column_width: Option, + pub fixed_width: bool, + pub flexible_width: bool, + pub balance_columns: bool, + pub inset: Option<[f64; 4]>, + pub vertical_justification: Option, + pub vertical_threshold: Option, + pub first_baseline: Option, + pub minimum_first_baseline: Option, + pub ignore_wrap: bool, + pub auto_sizing_type: Option, + pub auto_sizing_reference: Option, + pub use_minimum_height: bool, + pub minimum_height: Option, + pub use_minimum_width: bool, + pub minimum_width: Option, + pub no_line_breaks: bool, + pub column_rule_override: bool, + pub column_rule_width: Option, + pub column_rule_tint: Option, + pub column_rule_offset: Option, + pub column_rule_top_inset: Option, + pub column_rule_bottom_inset: Option, +} + +impl TextFramePreferences { + /// Reads preference levels nearest first. A malformed explicit value still masks an inherited + /// one, matching IDML's item-over-object-style precedence. + pub fn from_elements(elements: &[&El]) -> Self { + let prop = |key: &str| elements.iter().find_map(|el| Values::of(el).prop(key)); + let num = |key: &str| prop(key).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()); + let boolean = |key: &str| matches!(prop(key).as_deref().map(str::trim), Some("true")); + Self { + column_count: num("TextColumnCount"), + column_gutter: num("TextColumnGutter"), + fixed_column_width: num("TextColumnFixedWidth"), + fixed_width: boolean("UseFixedColumnWidth"), + flexible_width: boolean("UseFlexibleColumnWidth"), + balance_columns: boolean("VerticalBalanceColumns"), + inset: inset(elements), + vertical_justification: prop("VerticalJustification"), + vertical_threshold: num("VerticalThreshold"), + first_baseline: prop("FirstBaselineOffset"), + minimum_first_baseline: num("MinimumFirstBaselineOffset"), + ignore_wrap: boolean("IgnoreWrap"), + auto_sizing_type: prop("AutoSizingType"), + auto_sizing_reference: prop("AutoSizingReferencePoint"), + use_minimum_height: boolean("UseMinimumHeightForAutoSizing"), + minimum_height: num("MinimumHeightForAutoSizing"), + use_minimum_width: boolean("UseMinimumWidthForAutoSizing"), + minimum_width: num("MinimumWidthForAutoSizing"), + no_line_breaks: boolean("UseNoLineBreaksForAutoSizing"), + column_rule_override: boolean("ColumnRuleOverride"), + column_rule_width: num("ColumnRuleStrokeWidth"), + column_rule_tint: num("ColumnRuleStrokeTint"), + column_rule_offset: num("ColumnRuleOffset"), + column_rule_top_inset: num("ColumnRuleTopInset"), + column_rule_bottom_inset: num("ColumnRuleBottomInset"), + } + } + + /// Writes one IDML `TextFramePreference`, including its inset list and column-rule + /// properties. Enumeration strings are supplied by the caller because they are model policy. + pub fn to_el(&self, column_rule_color: &str) -> El { + use crate::value::num; + + let mut inset = El::new("InsetSpacing").with_attr("type", "list"); + for value in self.inset.unwrap_or([0.0; 4]) { + inset.push(El::new("ListItem").with_attr("type", "unit").with_text(num(value))); + } + let el = El::new("TextFramePreference") + .with_attr("TextColumnCount", num(self.column_count.unwrap_or(1.0).max(1.0))) + .with_attr("TextColumnGutter", num(self.column_gutter.unwrap_or(0.0))) + .with_attr("UseFixedColumnWidth", bool_text(self.fixed_width)) + .with_attr("UseFlexibleColumnWidth", bool_text(self.flexible_width)) + .with_attr("VerticalBalanceColumns", bool_text(self.balance_columns)) + .with_attr("FirstBaselineOffset", self.first_baseline.as_deref().unwrap_or("Ascent")) + .with_attr("MinimumFirstBaselineOffset", num(self.minimum_first_baseline.unwrap_or(0.0))) + .with_attr("VerticalJustification", self.vertical_justification.as_deref().unwrap_or("TopAlign")) + .with_attr("VerticalThreshold", num(self.vertical_threshold.unwrap_or(0.0))) + .with_attr("IgnoreWrap", bool_text(self.ignore_wrap)) + .with_attr("AutoSizingType", self.auto_sizing_type.as_deref().unwrap_or("Off")) + .with_attr("AutoSizingReferencePoint", self.auto_sizing_reference.as_deref().unwrap_or("CenterPoint")) + .with_attr("UseMinimumHeightForAutoSizing", bool_text(self.use_minimum_height)) + .with_attr("MinimumHeightForAutoSizing", num(self.minimum_height.unwrap_or(0.0))) + .with_attr("UseMinimumWidthForAutoSizing", bool_text(self.use_minimum_width)) + .with_attr("MinimumWidthForAutoSizing", num(self.minimum_width.unwrap_or(0.0))) + .with_attr("UseNoLineBreaksForAutoSizing", bool_text(self.no_line_breaks)); + let el = if let Some(width) = self.fixed_column_width.filter(|width| *width > 0.0) { + el.with_attr("TextColumnFixedWidth", num(width)) + } else { + el + }; + let el = el + .with_attr("ColumnRuleOverride", bool_text(self.column_rule_override)) + .with_attr("ColumnRuleStrokeWidth", num(self.column_rule_width.unwrap_or(0.0))) + .with_attr("ColumnRuleStrokeColor", column_rule_color) + .with_attr("ColumnRuleStrokeTint", num(self.column_rule_tint.unwrap_or(0.0))) + .with_attr("ColumnRuleOffset", num(self.column_rule_offset.unwrap_or(0.0))) + .with_attr("ColumnRuleTopInset", num(self.column_rule_top_inset.unwrap_or(0.0))) + .with_attr("ColumnRuleBottomInset", num(self.column_rule_bottom_inset.unwrap_or(0.0))) + .with_attr("ColumnRuleInsetChainOverride", bool_text(self.column_rule_top_inset == self.column_rule_bottom_inset)); + el.with_child(El::new("Properties").with_child(inset)) + } +} + +fn bool_text(value: bool) -> &'static str { + if value { "true" } else { "false" } +} + +fn inset(elements: &[&El]) -> Option<[f64; 4]> { + let element = elements.iter().find(|el| Values::of(el).prop("InsetSpacing").is_some())?; + let values = Values::of(element); + let number = |s: &str| s.trim().parse::().ok().filter(|v| v.is_finite()); + let Some(property) = values.prop_el("InsetSpacing") else { + return values.get("InsetSpacing").and_then(number).map(|v| [v; 4]); + }; + let items: Vec<_> = property.elements().collect(); + if property.attr("type") == Some("list") || items.iter().any(|item| item.local() == "ListItem") { + if items.len() != 4 { + return None; + } + let mut result = [0.0; 4]; + for (slot, item) in result.iter_mut().zip(items) { + if item.local() != "ListItem" || item.elements().next().is_some() { + return None; + } + *slot = number(&item.deep_text())?; + } + Some(result) + } else if items.is_empty() { + number(&property.deep_text()).map(|v| [v; 4]) + } else { + None + } +} diff --git a/crates/idml/src/model/resources.rs b/crates/idml/src/model/resources.rs index 6a66f6f914..11a76b1865 100644 --- a/crates/idml/src/model/resources.rs +++ b/crates/idml/src/model/resources.rs @@ -11,6 +11,1193 @@ fn others(el: &El) -> impl Iterator { el.elements().filter(|e| !e.is(Local("Properties"))) } +/// Raw bullet and numbering properties on an IDML paragraph style or range. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphListValues { + pub applied_list: Option, + pub list_type: Option, + pub numbering_format: Option, + pub expression: Option, + pub separator: Option, + pub bullet_type: Option, + pub bullet_value: Option, + pub balance_ragged: Option, + pub level: Option, + pub bullet_character_style: Option, + pub numbering_character_style: Option, + pub bullet_alignment: Option, + pub numbering_alignment: Option, + pub restart_numbers: Option, + pub restart_after_level: Option, + pub restart_after_specific_level: bool, + pub numbering_continue: Option, + pub numbering_start_at: Option, + pub bullet_font: Option, + pub bullet_font_style: Option, +} + +/// Paragraph border and shading values after the caller resolves model colours and enums. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphBoxValues { + pub shading_on: Option, + pub shading_color: Option, + pub shading_tint: Option, + pub shading_offsets: Option<[f64; 4]>, + pub shading_overprint: Option, + pub border_on: Option, + pub border_color: Option, + pub border_tint: Option, + pub border_weights: Option<[f64; 4]>, + pub border_offsets: Option<[f64; 4]>, + pub border_type: Option, + pub border_cap: Option, + pub border_join: Option, + pub border_corners: Option<[(String, f64); 4]>, + pub border_width: Option, + pub border_top: Option, + pub border_bottom: Option, + pub border_display_if_splits: Option, + pub border_merge: Option, + pub border_gap_color: Option, + pub border_gap_tint: Option, + pub border_overprint: Option, + pub border_gap_overprint: Option, + pub shading_width: Option, + pub shading_top: Option, + pub shading_bottom: Option, + pub shading_clip: Option, + pub shading_nonprinting: Option, + pub shading_corners: Option<[(String, f64); 4]>, +} + +/// CJK paragraph composition settings read from an IDML style or text range. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CjkParagraphValues { + pub kinsoku_hang: Option, + pub mojikumi: Option, + pub kinsoku_type: Option, + pub bunri_kinshi: Option, + pub rensuuji: Option, + pub treat_ideographic_space_as_space: Option, + pub kinsoku_set: Option, + pub auto_tcy: Option, + pub auto_tcy_include_roman: Option, + pub rotate_single_byte_characters: Option, + pub allow_arbitrary_hyphenation: Option, + pub grid_gyoudori: Option, + pub paragraph_gyoudori: Option, +} + +impl CjkParagraphValues { + /// Reads CJK paragraph composition properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let bounded_count = |key: &str| values.num(key).map(|value| value.clamp(0.0, 1000.0)); + Self { + kinsoku_hang: values.prop("KinsokuHangType"), + mojikumi: values.prop("Mojikumi"), + kinsoku_type: values.prop("KinsokuType"), + bunri_kinshi: values.boolean("BunriKinshi"), + rensuuji: values.boolean("Rensuuji"), + treat_ideographic_space_as_space: values.boolean("TreatIdeographicSpaceAsSpace"), + kinsoku_set: values.prop("KinsokuSet"), + auto_tcy: bounded_count("AutoTcy"), + auto_tcy_include_roman: values.boolean("AutoTcyIncludeRoman"), + rotate_single_byte_characters: values.boolean("RotateSingleByteCharacters"), + allow_arbitrary_hyphenation: values.boolean("AllowArbitraryHyphenation"), + grid_gyoudori: bounded_count("GridGyoudori"), + paragraph_gyoudori: values.boolean("ParagraphGyoudori"), + } + } + + /// Encodes a semantic kinsoku-set name as its IDML property value. + pub fn kinsoku_reference(name: &str) -> String { + if name.is_empty() { "Nothing".into() } else { format!("KinsokuTable/{}", crate::value::escape_id(name)) } + } + + /// Writes CJK paragraph attributes and properties. + pub fn to_parts(&self) -> (Vec<(String, String)>, Vec) { + let mut attrs = Vec::new(); + let mut properties = Vec::new(); + for (key, value) in [("KinsokuHangType", &self.kinsoku_hang), ("KinsokuType", &self.kinsoku_type)] { + if let Some(value) = value { + attrs.push((key.into(), value.clone())); + } + } + if let Some(value) = &self.mojikumi { + let kind = if value.starts_with("MojikumiTable/") { "object" } else { "enumeration" }; + properties.push(property("Mojikumi", kind, value.clone())); + } + for (key, value) in [ + ("BunriKinshi", self.bunri_kinshi), + ("Rensuuji", self.rensuuji), + ("TreatIdeographicSpaceAsSpace", self.treat_ideographic_space_as_space), + ("AutoTcyIncludeRoman", self.auto_tcy_include_roman), + ("RotateSingleByteCharacters", self.rotate_single_byte_characters), + ("AllowArbitraryHyphenation", self.allow_arbitrary_hyphenation), + ("ParagraphGyoudori", self.paragraph_gyoudori), + ] { + push_boolean(&mut attrs, key, value); + } + push_number(&mut attrs, "AutoTcy", self.auto_tcy); + push_number(&mut attrs, "GridGyoudori", self.grid_gyoudori); + if let Some(value) = &self.kinsoku_set { + properties.push(property("KinsokuSet", if value == "Nothing" { "enumeration" } else { "object" }, value.clone())); + } + (attrs, properties) + } +} + +/// Paragraph span and split-column properties read from IDML. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphSpanValues { + pub kind: Option, + pub split_column_count: Option, + pub inside_gutter: Option, + pub outside_gutter: Option, + pub space_before: Option, + pub space_after: Option, +} + +impl ParagraphSpanValues { + /// Reads paragraph span and split-column properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + kind: values.prop("SpanColumnType"), + split_column_count: values.prop("SpanSplitColumnCount").and_then(|value| value.trim().parse().ok()), + inside_gutter: values.num("SplitColumnInsideGutter"), + outside_gutter: values.num("SplitColumnOutsideGutter"), + space_before: values.num("SpanColumnMinSpaceBefore"), + space_after: values.num("SpanColumnMinSpaceAfter"), + } + } + + /// Writes paragraph span and split-column attributes and properties. + pub fn to_parts(&self) -> (Vec<(String, String)>, Vec) { + let mut attrs = Vec::new(); + let mut properties = Vec::new(); + if let Some(kind) = &self.kind { + attrs.push(("SpanColumnType".into(), kind.clone())); + } + if let Some(count) = self.split_column_count { + properties.push(if count == 0 { + property("SpanSplitColumnCount", "enumeration", "All") + } else { + property("SpanSplitColumnCount", "long", count.to_string()) + }); + } + for (key, value) in [ + ("SplitColumnInsideGutter", self.inside_gutter), + ("SplitColumnOutsideGutter", self.outside_gutter), + ("SpanColumnMinSpaceBefore", self.space_before), + ("SpanColumnMinSpaceAfter", self.space_after), + ] { + push_number(&mut attrs, key, value); + } + (attrs, properties) + } +} + +/// Paragraph alignment, spacing, drop cap, baseline grid and composer values after the caller +/// maps application semantics to IDML enumerations. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphAlignmentValues { + pub justification: Option, + pub direction: Option, + pub kashidas: Option, + pub paragraph_justification: Option, + pub paragraph_kashida_width: Option, + pub left_indent: Option, + pub right_indent: Option, + pub first_line_indent: Option, + pub last_line_indent: Option, + pub space_before: Option, + pub space_after: Option, + pub same_para_style_spacing: Option>, + pub drop_cap_lines: Option, + pub drop_cap_chars: Option, + pub dropcap_detail: Option, + pub grid_alignment: Option, + pub grid_align_first_line_only: Option, + pub composer: Option, +} + +/// Paragraph hyphenation, justification spacing and keep options after caller enum mapping. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParagraphFlowValues { + pub hyphenate: Option, + pub hyphenate_min_word: Option, + pub hyphenate_after_first: Option, + pub hyphenate_before_last: Option, + pub hyphenate_ladder_limit: Option, + pub hyphenation_zone: Option, + pub hyphenate_capitalized: Option, + pub hyphenate_last_word: Option, + pub hyphenate_across_columns: Option, + pub hyphen_weight: Option, + pub word_spacing: [Option; 3], + pub letter_spacing: [Option; 3], + pub glyph_scaling: [Option; 3], + pub auto_leading: Option, + pub single_word_justification: Option, + pub keep_with_next: Option, + pub keep_lines_together: Option, + pub ignore_edge_alignment: Option, + pub keep_all_lines_together: Option, + pub keep_first_lines: Option, + pub keep_last_lines: Option, + pub start_paragraph: Option, +} + +/// Raw IDML character typography values before the caller resolves fonts and semantic enums. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CharacterTypographyValues { + pub applied_font: Option, + pub font_style: Option, + pub point_size: Option, + pub leading: Option, + pub kerning_method: Option, + pub kerning_value: Option, + pub tracking: Option, + pub leading_aki: Option, + pub trailing_aki: Option, + pub tsume: Option, + pub jidori: Option, + pub leading_model: Option, + pub character_alignment: Option, + pub horizontal_scale: Option, + pub vertical_scale: Option, + pub baseline_shift: Option, + pub skew: Option, +} + +/// One underline or strikethrough style as written in IDML. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TextDecorationValues { + pub weight: Option, + pub offset: Option, + pub color: Option, + pub tint: Option, +} + +/// Character fill/stroke, decoration and toggle values before caller swatch resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CharacterAppearanceValues { + pub fill_color: Option, + pub fill_tint: Option, + pub stroke_color: Option, + pub stroke_tint: Option, + pub stroke_weight: Option, + pub stroke_alignment: Option, + pub underline: Option, + pub strikethrough: Option, + pub ligatures: Option, + pub underline_options: TextDecorationValues, + pub strikethrough_options: TextDecorationValues, +} + +/// Raw Ruby attributes and properties on an IDML character range or style. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RubyValues { + pub flag: Option, + pub text: Option, + pub kind: Option, + pub alignment: Option, + pub position: Option, + pub x_offset: Option, + pub y_offset: Option, + pub font: Option, + pub font_style: Option, + pub font_size: Option, + pub x_scale: Option, + pub y_scale: Option, + pub open_type_pro: Option, + pub auto_tcy_digits: Option, + pub auto_tcy_include_roman: Option, + pub auto_tcy_auto_scale: Option, + pub overhang: Option, + pub parent_overhang: Option, + pub parent_spacing: Option, + pub auto_align: Option, + pub auto_scaling: Option, + pub parent_scaling: Option, + pub fill: Option, + pub stroke: Option, + pub fill_tint: Option, + pub stroke_tint: Option, + pub stroke_weight: Option, + pub overprint_fill: Option, + pub overprint_stroke: Option, +} + +/// Raw remaining character attributes and properties before semantic enum and condition mapping. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CharacterSpecialValues { + pub capitalization: Option, + pub position: Option, + pub glyph_form: Option, + pub no_break: Option, + pub tate_chu_yoko: Option, + pub tate_chu_yoko_x_offset: Option, + pub tate_chu_yoko_y_offset: Option, + pub warichu: Option, + pub warichu_lines: Option, + pub warichu_size: Option, + pub warichu_line_spacing: Option, + pub warichu_alignment: Option, + pub warichu_chars_before_break: Option, + pub warichu_chars_after_break: Option, + pub digits: Option, + pub character_direction: Option, + pub allow_kashidas: Option, + pub diacritic_position: Option, + pub diacritic_x_offset: Option, + pub diacritic_y_offset: Option, + pub positional_form: Option, + pub applied_conditions: Option, + pub applied_language: Option, +} + +impl CharacterSpecialValues { + /// Reads remaining character ranges/style fields from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + capitalization: values.prop("Capitalization"), + position: values.prop("Position"), + glyph_form: values.prop("GlyphForm"), + no_break: values.boolean("NoBreak"), + tate_chu_yoko: values.boolean("Tatechuyoko"), + tate_chu_yoko_x_offset: values.num("TatechuyokoXOffset"), + tate_chu_yoko_y_offset: values.num("TatechuyokoYOffset"), + warichu: values.boolean("Warichu"), + warichu_lines: values.num("WarichuLines"), + warichu_size: values.num("WarichuSize"), + warichu_line_spacing: values.num("WarichuLineSpacing"), + warichu_alignment: values.prop("WarichuAlignment"), + warichu_chars_before_break: values.num("WarichuCharsBeforeBreak"), + warichu_chars_after_break: values.num("WarichuCharsAfterBreak"), + digits: values.prop("DigitsType"), + character_direction: values.prop("CharacterDirection"), + allow_kashidas: values.prop("Kashidas"), + diacritic_position: values.prop("DiacriticPosition"), + diacritic_x_offset: values.num("XOffsetDiacritic"), + diacritic_y_offset: values.num("YOffsetDiacritic"), + positional_form: values.prop("PositionalForm"), + applied_conditions: values.prop("AppliedConditions"), + applied_language: values.prop("AppliedLanguage"), + } + } +} + +impl RubyValues { + /// Reads Ruby text and formatting values from an IDML character range/style. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + flag: values.boolean("RubyFlag").or_else(|| values.num("RubyFlag").map(|value| value != 0.0)), + text: values.prop("RubyString"), + kind: values.prop("RubyType"), + alignment: values.prop("RubyAlignment"), + position: values.prop("RubyPosition"), + x_offset: values.num("RubyXOffset"), + y_offset: values.num("RubyYOffset"), + font: values.prop("RubyFont"), + font_style: values.prop("RubyFontStyle"), + font_size: values.num("RubyFontSize"), + x_scale: values.num("RubyXScale"), + y_scale: values.num("RubyYScale"), + open_type_pro: values.boolean("RubyOpenTypePro"), + auto_tcy_digits: values.num("RubyAutoTcyDigits"), + auto_tcy_include_roman: values.boolean("RubyAutoTcyIncludeRoman"), + auto_tcy_auto_scale: values.boolean("RubyAutoTcyAutoScale"), + overhang: values.boolean("RubyOverhang"), + parent_overhang: values.prop("RubyParentOverhangAmount"), + parent_spacing: values.prop("RubyParentSpacing"), + auto_align: values.boolean("RubyAutoAlign"), + auto_scaling: values.boolean("RubyAutoScaling"), + parent_scaling: values.num("RubyParentScalingPercent"), + fill: values.prop("RubyFill"), + stroke: values.prop("RubyStroke"), + fill_tint: values.num("RubyTint"), + stroke_tint: values.num("RubyStrokeTint"), + stroke_weight: values.num("RubyWeight"), + overprint_fill: values.prop("RubyOverprintFill"), + overprint_stroke: values.prop("RubyOverprintStroke"), + } + } +} + +impl CharacterAppearanceValues { + /// Reads common character fill, stroke and decoration properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let decoration = |prefix: &str| { + let number = |suffix: &str| values.num(&format!("{prefix}{suffix}")).filter(|value| *value > -9000.0); + TextDecorationValues { + weight: number("Weight"), + offset: number("Offset"), + color: values.prop(&format!("{prefix}Color")), + tint: values.num(&format!("{prefix}Tint")), + } + }; + Self { + fill_color: values.prop("FillColor"), + fill_tint: values.num("FillTint"), + stroke_color: values.prop("StrokeColor"), + stroke_tint: values.num("StrokeTint"), + stroke_weight: values.num("StrokeWeight"), + stroke_alignment: values.prop("StrokeAlignment"), + underline: values.boolean("Underline"), + strikethrough: values.boolean("StrikeThru"), + ligatures: values.boolean("Ligatures"), + underline_options: decoration("Underline"), + strikethrough_options: decoration("StrikeThru"), + } + } +} + +impl CharacterTypographyValues { + /// Reads the common typography attributes and properties from an IDML character range/style. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + applied_font: values.prop("AppliedFont"), + font_style: values.prop("FontStyle"), + point_size: values.num("PointSize"), + leading: values.prop("Leading"), + kerning_method: values.prop("KerningMethod"), + kerning_value: values.num("KerningValue"), + tracking: values.num("Tracking"), + leading_aki: values.num("LeadingAki"), + trailing_aki: values.num("TrailingAki"), + tsume: values.num("Tsume"), + jidori: values.num("Jidori"), + leading_model: values.prop("LeadingModel"), + character_alignment: values.prop("CharacterAlignment"), + horizontal_scale: values.num("HorizontalScale"), + vertical_scale: values.num("VerticalScale"), + baseline_shift: values.num("BaselineShift"), + skew: values.num("Skew"), + } + } +} + +impl ParagraphFlowValues { + /// Reads paragraph hyphenation and flow properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + hyphenate: values.boolean("Hyphenation"), + hyphenate_min_word: values.num("HyphenateWordsLongerThan"), + hyphenate_after_first: values.num("HyphenateAfterFirst"), + hyphenate_before_last: values.num("HyphenateBeforeLast"), + hyphenate_ladder_limit: values.num("HyphenateLadderLimit"), + hyphenation_zone: values.num("HyphenationZone"), + hyphenate_capitalized: values.boolean("HyphenateCapitalizedWords"), + hyphenate_last_word: values.boolean("HyphenateLastWord"), + hyphenate_across_columns: values.boolean("HyphenateAcrossColumns"), + hyphen_weight: values.num("HyphenWeight"), + word_spacing: [values.num("MinimumWordSpacing"), values.num("DesiredWordSpacing"), values.num("MaximumWordSpacing")], + letter_spacing: [values.num("MinimumLetterSpacing"), values.num("DesiredLetterSpacing"), values.num("MaximumLetterSpacing")], + glyph_scaling: [values.num("MinimumGlyphScaling"), values.num("DesiredGlyphScaling"), values.num("MaximumGlyphScaling")], + auto_leading: values.num("AutoLeading"), + single_word_justification: values.prop("SingleWordJustification"), + keep_with_next: values.num("KeepWithNext"), + keep_lines_together: values.boolean("KeepLinesTogether"), + ignore_edge_alignment: values.boolean("IgnoreEdgeAlignment"), + keep_all_lines_together: values.boolean("KeepAllLinesTogether"), + keep_first_lines: values.num("KeepFirstLines"), + keep_last_lines: values.num("KeepLastLines"), + start_paragraph: values.prop("StartParagraph"), + } + } + + /// Writes IDML attributes for paragraph hyphenation and flow. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [ + ("Hyphenation", self.hyphenate), + ("HyphenateCapitalizedWords", self.hyphenate_capitalized), + ("HyphenateLastWord", self.hyphenate_last_word), + ("HyphenateAcrossColumns", self.hyphenate_across_columns), + ("KeepLinesTogether", self.keep_lines_together), + ("IgnoreEdgeAlignment", self.ignore_edge_alignment), + ("KeepAllLinesTogether", self.keep_all_lines_together), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), if value { "true" } else { "false" }.to_string())); + } + } + for (key, value) in [ + ("HyphenateWordsLongerThan", self.hyphenate_min_word), + ("HyphenateAfterFirst", self.hyphenate_after_first), + ("HyphenateBeforeLast", self.hyphenate_before_last), + ("HyphenateLadderLimit", self.hyphenate_ladder_limit), + ("HyphenationZone", self.hyphenation_zone), + ("HyphenWeight", self.hyphen_weight), + ("MinimumWordSpacing", self.word_spacing[0]), + ("DesiredWordSpacing", self.word_spacing[1]), + ("MaximumWordSpacing", self.word_spacing[2]), + ("MinimumLetterSpacing", self.letter_spacing[0]), + ("DesiredLetterSpacing", self.letter_spacing[1]), + ("MaximumLetterSpacing", self.letter_spacing[2]), + ("MinimumGlyphScaling", self.glyph_scaling[0]), + ("DesiredGlyphScaling", self.glyph_scaling[1]), + ("MaximumGlyphScaling", self.glyph_scaling[2]), + ("AutoLeading", self.auto_leading), + ("KeepWithNext", self.keep_with_next), + ("KeepFirstLines", self.keep_first_lines), + ("KeepLastLines", self.keep_last_lines), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), crate::value::num(value))); + } + } + for (key, value) in [("SingleWordJustification", &self.single_word_justification), ("StartParagraph", &self.start_paragraph)] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + attrs + } +} + +impl ParagraphAlignmentValues { + /// Reads paragraph alignment and spacing properties from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + justification: values.prop("Justification"), + direction: values.prop("ParagraphDirection"), + kashidas: values.prop("Kashidas"), + paragraph_justification: values.prop("ParagraphJustification"), + paragraph_kashida_width: values.num("ParagraphKashidaWidth"), + left_indent: values.num("LeftIndent"), + right_indent: values.num("RightIndent"), + first_line_indent: values.num("FirstLineIndent"), + last_line_indent: values.num("LastLineIndent"), + space_before: values.num("SpaceBefore"), + space_after: values.num("SpaceAfter"), + same_para_style_spacing: values.prop("SameParaStyleSpacing").map(|value| value.trim().parse::().ok().filter(|v| v.is_finite())), + drop_cap_lines: values.num("DropCapLines"), + drop_cap_chars: values.num("DropCapCharacters"), + dropcap_detail: values.num("DropcapDetail").filter(|value| *value >= 0.0).map(|value| value as u32), + grid_alignment: values.prop("GridAlignment"), + grid_align_first_line_only: values.boolean("GridAlignFirstLineOnly"), + composer: values.prop("Composer"), + } + } + + /// Writes the IDML attributes for paragraph alignment and spacing. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + for (key, value) in [ + ("Justification", &self.justification), + ("ParagraphDirection", &self.direction), + ("Kashidas", &self.kashidas), + ("ParagraphJustification", &self.paragraph_justification), + ("GridAlignment", &self.grid_alignment), + ("Composer", &self.composer), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + for (key, value) in [ + ("ParagraphKashidaWidth", self.paragraph_kashida_width), + ("LeftIndent", self.left_indent), + ("RightIndent", self.right_indent), + ("FirstLineIndent", self.first_line_indent), + ("LastLineIndent", self.last_line_indent), + ("SpaceBefore", self.space_before), + ("SpaceAfter", self.space_after), + ("DropCapLines", self.drop_cap_lines), + ("DropCapCharacters", self.drop_cap_chars), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), crate::value::num(value))); + } + } + if let Some(value) = self.same_para_style_spacing { + attrs.push(("SameParaStyleSpacing".to_string(), value.map(crate::value::num).unwrap_or_else(|| "Nothing".to_string()))); + } + if let Some(value) = self.dropcap_detail { + attrs.push(("DropcapDetail".to_string(), value.to_string())); + } + if let Some(value) = self.grid_align_first_line_only { + attrs.push(("GridAlignFirstLineOnly".to_string(), if value { "true" } else { "false" }.to_string())); + } + attrs + } +} + +impl ParagraphBoxValues { + /// Reads paragraph border and shading values from IDML. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let sides = |prefix: &str, suffix: &str| { + let values = ["Top", "Left", "Bottom", "Right"].map(|side| values.num(&format!("{prefix}{side}{suffix}"))); + values.iter().any(Option::is_some).then(|| values.map(|value| value.unwrap_or(0.0))) + }; + let corners = |prefix: &str| { + let names = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"]; + let shapes = names.map(|corner| values.prop(&format!("{prefix}{corner}CornerOption"))); + let sizes = names.map(|corner| values.num(&format!("{prefix}{corner}CornerRadius"))); + if shapes.iter().all(Option::is_none) && sizes.iter().all(Option::is_none) { + None + } else { + Some(std::array::from_fn(|index| { + (shapes[index].clone().unwrap_or_else(|| "None".to_string()), sizes[index].map_or(12.0, |value| value.max(0.0))) + })) + } + }; + Self { + shading_on: values.boolean("ParagraphShadingOn"), + shading_color: values.prop("ParagraphShadingColor"), + shading_tint: values.num("ParagraphShadingTint"), + shading_offsets: sides("ParagraphShading", "Offset"), + shading_overprint: values.boolean("ParagraphShadingOverprint"), + border_on: values.boolean("ParagraphBorderOn"), + border_color: values.prop("ParagraphBorderColor"), + border_tint: values.num("ParagraphBorderTint"), + border_weights: sides("ParagraphBorder", "LineWeight"), + border_offsets: sides("ParagraphBorder", "Offset"), + border_type: values.prop("ParagraphBorderType"), + border_cap: values.prop("ParagraphBorderStrokeEndCap"), + border_join: values.prop("ParagraphBorderStrokeEndJoin"), + border_corners: corners("ParagraphBorder"), + border_width: values.prop("ParagraphBorderWidth"), + border_top: values.prop("ParagraphBorderTopOrigin"), + border_bottom: values.prop("ParagraphBorderBottomOrigin"), + border_display_if_splits: values.boolean("ParagraphBorderDisplayIfSplits"), + border_merge: values.boolean("MergeConsecutiveParaBorders"), + border_gap_color: values.prop("ParagraphBorderGapColor"), + border_gap_tint: values.num("ParagraphBorderGapTint"), + border_overprint: values.boolean("ParagraphBorderOverprint"), + border_gap_overprint: values.boolean("ParagraphBorderGapOverprint"), + shading_width: values.prop("ParagraphShadingWidth"), + shading_top: values.prop("ParagraphShadingTopOrigin"), + shading_bottom: values.prop("ParagraphShadingBottomOrigin"), + shading_clip: values.boolean("ParagraphShadingClipToFrame"), + shading_nonprinting: values.boolean("ParagraphShadingSuppressPrinting"), + shading_corners: corners("ParagraphShading"), + } + } + + /// Writes IDML attributes and properties for paragraph borders and shading. + pub fn to_parts(&self) -> (Vec<(String, String)>, Vec) { + use crate::value::num; + + let mut attrs = Vec::new(); + let mut props = Vec::new(); + push_boolean(&mut attrs, "ParagraphShadingOn", self.shading_on); + if let Some(color) = &self.shading_color { + props.push(property("ParagraphShadingColor", "object", color.clone())); + } + push_number(&mut attrs, "ParagraphShadingTint", self.shading_tint); + push_boolean(&mut attrs, "ParagraphShadingOverprint", self.shading_overprint); + const SIDES: [&str; 4] = ["Top", "Left", "Bottom", "Right"]; + if let Some(offsets) = self.shading_offsets { + for (side, value) in SIDES.iter().zip(offsets) { + push_number(&mut attrs, &format!("ParagraphShading{side}Offset"), Some(value)); + } + } + push_boolean(&mut attrs, "ParagraphBorderOn", self.border_on); + if let Some(color) = &self.border_color { + props.push(property("ParagraphBorderColor", "object", color.clone())); + } + push_number(&mut attrs, "ParagraphBorderTint", self.border_tint); + push_boolean(&mut attrs, "ParagraphBorderOverprint", self.border_overprint); + if let Some(weights) = self.border_weights { + for (side, value) in SIDES.iter().zip(weights) { + push_number(&mut attrs, &format!("ParagraphBorder{side}LineWeight"), Some(value)); + } + } + if let Some(offsets) = self.border_offsets { + for (side, value) in SIDES.iter().zip(offsets) { + push_number(&mut attrs, &format!("ParagraphBorder{side}Offset"), Some(value)); + } + } + if let Some(kind) = &self.border_type { + props.push(property("ParagraphBorderType", "object", kind.clone())); + } + if let Some(cap) = &self.border_cap { + attrs.push(("ParagraphBorderStrokeEndCap".into(), cap.clone())); + } + if let Some(join) = &self.border_join { + attrs.push(("ParagraphBorderStrokeEndJoin".into(), join.clone())); + } + for (prefix, corners) in [("ParagraphBorder", &self.border_corners), ("ParagraphShading", &self.shading_corners)] { + if let Some(corners) = corners { + const CORNERS: [&str; 4] = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"]; + for ((shape, radius), corner) in corners.iter().zip(CORNERS) { + attrs.push((format!("{prefix}{corner}CornerOption"), shape.clone())); + attrs.push((format!("{prefix}{corner}CornerRadius"), num(*radius))); + } + } + } + for (key, value) in [ + ("ParagraphBorderWidth", &self.border_width), + ("ParagraphBorderTopOrigin", &self.border_top), + ("ParagraphBorderBottomOrigin", &self.border_bottom), + ("ParagraphShadingWidth", &self.shading_width), + ("ParagraphShadingTopOrigin", &self.shading_top), + ("ParagraphShadingBottomOrigin", &self.shading_bottom), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + push_boolean(&mut attrs, "ParagraphBorderDisplayIfSplits", self.border_display_if_splits); + push_boolean(&mut attrs, "MergeConsecutiveParaBorders", self.border_merge); + if let Some(color) = &self.border_gap_color { + props.push(property("ParagraphBorderGapColor", "object", color.clone())); + } + push_number(&mut attrs, "ParagraphBorderGapTint", self.border_gap_tint); + push_boolean(&mut attrs, "ParagraphBorderGapOverprint", self.border_gap_overprint); + push_boolean(&mut attrs, "ParagraphShadingClipToFrame", self.shading_clip); + push_boolean(&mut attrs, "ParagraphShadingSuppressPrinting", self.shading_nonprinting); + (attrs, props) + } +} + +fn push_boolean(attrs: &mut Vec<(String, String)>, key: &str, value: Option) { + if let Some(value) = value { + attrs.push((key.to_string(), if value { "true" } else { "false" }.to_string())); + } +} + +fn push_number(attrs: &mut Vec<(String, String)>, key: &str, value: Option) { + if let Some(value) = value { + attrs.push((key.to_string(), crate::value::num(value))); + } +} + +impl ParagraphListValues { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let restart = values.prop_el("NumberingRestartPolicies"); + let restart_after_level = restart.map(|policy| policy.attr("LowerLevel").and_then(|value| value.trim().parse::().ok()).unwrap_or(0)); + let restart_after_specific_level = restart.is_some_and(|policy| policy.attr("RestartPolicy").map(str::trim) == Some("SpecificPreviousLevel")); + let bullet = values.prop_el("BulletChar"); + Self { + applied_list: values.prop("AppliedNumberingList"), + list_type: values.prop("BulletsAndNumberingListType"), + numbering_format: values.prop("NumberingFormat"), + expression: values.prop("NumberingExpression"), + separator: values.prop("BulletsTextAfter"), + bullet_type: bullet.and_then(|value| value.attr("BulletCharacterType")).map(str::to_owned), + bullet_value: bullet.and_then(|value| value.attr("BulletCharacterValue")).map(str::to_owned), + balance_ragged: values.prop("BalanceRaggedLines"), + level: values.num("NumberingLevel"), + bullet_character_style: values.prop("BulletsCharacterStyle"), + numbering_character_style: values.prop("NumberingCharacterStyle"), + bullet_alignment: values.prop("BulletsAlignment"), + numbering_alignment: values.prop("NumberingAlignment"), + restart_numbers: values.boolean("NumberingApplyRestartPolicy"), + restart_after_level, + restart_after_specific_level, + numbering_continue: values.boolean("NumberingContinue"), + numbering_start_at: values.num("NumberingStartAt"), + bullet_font: values.prop("BulletsFont"), + bullet_font_style: values.prop("BulletsFontStyle"), + } + } + + /// Encodes a semantic paragraph-list name as its IDML object reference. + pub fn numbering_list_reference(name: &str) -> String { + if name.is_empty() { "NumberingList/$ID/[Default]".into() } else { format!("NumberingList/{}", crate::value::escape_id(name)) } + } + + /// IDML attributes represented by a paragraph's list settings. + pub fn to_attrs(&self) -> Vec<(String, String)> { + let mut attrs = Vec::new(); + if let Some(value) = &self.applied_list { + attrs.push(("AppliedNumberingList".into(), value.clone())); + } + if let Some(value) = self.numbering_continue { + attrs.push(("NumberingContinue".into(), if value { "true" } else { "false" }.into())); + } + push_number(&mut attrs, "NumberingStartAt", self.numbering_start_at); + for (key, value) in [ + ("BulletsAndNumberingListType", &self.list_type), + ("NumberingExpression", &self.expression), + ("BulletsTextAfter", &self.separator), + ("NumberingLevel", &self.level.map(crate::value::num)), + ("BulletsAlignment", &self.bullet_alignment), + ("NumberingAlignment", &self.numbering_alignment), + ("NumberingApplyRestartPolicy", &self.restart_numbers.map(|value| if value { "true".to_string() } else { "false".to_string() })), + ] { + if let Some(value) = value { + attrs.push((key.to_string(), value.clone())); + } + } + attrs + } + + /// IDML property elements represented by a paragraph's list settings. + pub fn to_els(&self) -> Vec { + let mut properties = Vec::new(); + if let Some(format) = &self.numbering_format { + properties.push(property("NumberingFormat", "string", format.clone())); + } + if let (Some(kind), Some(value)) = (&self.bullet_type, &self.bullet_value) { + properties.push(El::new("BulletChar").with_attr("BulletCharacterType", kind).with_attr("BulletCharacterValue", value)); + } + if let Some(balance) = &self.balance_ragged { + properties.push(property("BalanceRaggedLines", "enumeration", balance.clone())); + } + for (name, style) in [("BulletsCharacterStyle", &self.bullet_character_style), ("NumberingCharacterStyle", &self.numbering_character_style)] { + if let Some(style) = style { + properties.push(property(name, "object", style.clone())); + } + } + if let Some(level) = self.restart_after_level { + let mut restart = El::new("NumberingRestartPolicies") + .with_attr("RestartPolicy", if self.restart_after_specific_level { "SpecificPreviousLevel" } else { "AnyPreviousLevel" }) + .with_attr("LowerLevel", level.to_string()); + restart.set_attr("UpperLevel", level.to_string()); + properties.push(restart); + } + if let Some(font) = &self.bullet_font { + properties.push(property("BulletsFont", "string", if font.is_empty() { "$ID/".into() } else { font.clone() })); + } + if let Some(style) = self.bullet_font_style.as_ref().filter(|style| !style.is_empty()) { + properties.push(property("BulletsFontStyle", "string", style.clone())); + } + properties + } +} + +/// One IDML nested paragraph style entry, before the caller resolves its character style. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NestedStyleValue { + pub character_style: String, + pub inclusive: bool, + pub repetition: u32, + pub delimiter_type: String, + pub delimiter: String, +} + +/// One IDML nested line style entry. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NestedLineStyleValue { + pub character_style: String, + pub line_count: u32, +} + +/// One IDML GREP style entry. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct GrepStyleValue { + pub character_style: String, + pub expression: String, +} + +/// Nested style lists stored on an IDML paragraph style or text range. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NestedStyleValues { + pub nested: Option>, + pub lines: Option>, + pub grep: Option>, +} + +impl NestedStyleValues { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let text = |item: &El, name: &str| item.find(name).map(El::deep_text).unwrap_or_default(); + let nested = values.prop_el("AllNestedStyles").map(|list| { + list.find_all("ListItem") + .map(|item| { + let delimiter = item.find("Delimiter"); + NestedStyleValue { + character_style: text(item, "AppliedCharacterStyle"), + inclusive: text(item, "Inclusive").trim() != "false", + repetition: text(item, "Repetition").trim().parse().unwrap_or(1), + delimiter_type: delimiter.and_then(|el| el.attr("type")).unwrap_or("enumeration").to_owned(), + delimiter: text(item, "Delimiter"), + } + }) + .collect() + }); + let lines = values.prop_el("AllNestedLineStyles").map(|list| { + list.find_all("ListItem") + .map(|item| NestedLineStyleValue { + character_style: text(item, "AppliedCharacterStyle"), + line_count: text(item, "LineCount").trim().parse().unwrap_or(1), + }) + .collect() + }); + let grep = values.prop_el("AllGREPStyles").map(|list| { + list.find_all("ListItem") + .map(|item| GrepStyleValue { character_style: text(item, "AppliedCharacterStyle"), expression: text(item, "GrepExpression") }) + .collect() + }); + Self { nested, lines, grep } + } + + /// Writes the nested style property lists. The caller resolves semantic style references and + /// delimiter enums into the IDML values held in this model. + pub fn to_els(&self) -> Vec { + let mut properties = Vec::new(); + if let Some(entries) = &self.nested { + let mut list = El::new("AllNestedStyles").with_attr("type", "list"); + for entry in entries { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("AppliedCharacterStyle", "object", entry.character_style.clone())) + .with_child(property("Delimiter", &entry.delimiter_type, entry.delimiter.clone())) + .with_child(property("Repetition", "long", entry.repetition.to_string())) + .with_child(property("Inclusive", "boolean", if entry.inclusive { "true" } else { "false" })), + ); + } + properties.push(list); + } + if let Some(entries) = &self.lines { + let mut list = El::new("AllNestedLineStyles").with_attr("type", "list"); + for entry in entries { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("AppliedCharacterStyle", "object", entry.character_style.clone())) + .with_child(property("LineCount", "long", entry.line_count.to_string())), + ); + } + properties.push(list); + } + if let Some(entries) = &self.grep { + let mut list = El::new("AllGREPStyles").with_attr("type", "list"); + for entry in entries { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("AppliedCharacterStyle", "object", entry.character_style.clone())) + .with_child(property("GrepExpression", "string", entry.expression.clone())), + ); + } + properties.push(list); + } + properties + } +} + +fn property(name: &str, kind: &str, value: impl Into) -> El { + El::new(name).with_attr("type", kind).with_text(value) +} + +/// OpenType feature tags represented by IDML character attributes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OpenTypeFeatureValues { + pub features: Vec, + pub present: bool, +} + +impl OpenTypeFeatureValues { + /// Reads IDML OTF toggle, figure style and stylistic-set attributes into feature tags. + pub fn from_el(el: &El) -> Self { + const TOGGLES: &[(&str, &str)] = &[ + ("dlig", "OTFDiscretionaryLigature"), + ("frac", "OTFFraction"), + ("ordn", "OTFOrdinal"), + ("swsh", "OTFSwash"), + ("titl", "OTFTitling"), + ("calt", "OTFContextualAlternate"), + ("zero", "OTFSlashedZero"), + ("palt", "OTFProportionalMetrics"), + ("hkna", "OTFHVKana"), + ("locl", "OTFLocale"), + ("mark", "OTFMark"), + ("hist", "OTFHistorical"), + ("salt", "OTFStylisticAlternate"), + ("jalt", "OTFJustificationAlternate"), + ("ital", "OTFRomanItalics"), + ]; + let values = Values::of(el); + let mut result = Self::default(); + for (tag, attribute) in TOGGLES { + let Some(on) = values.boolean(attribute) else { continue }; + let default_on = matches!(*tag, "calt" | "liga" | "locl" | "mark"); + result.features.retain(|feature| feature != tag && feature.strip_prefix('-') != Some(*tag)); + if on != default_on { + result.features.push(if on { (*tag).to_owned() } else { format!("-{tag}") }); + } + result.present = true; + } + if let Some(style) = values.value("OTFFigureStyle") { + let tags: &[&str] = match style.as_str() { + "TabularLining" => &["tnum", "lnum"], + "ProportionalOldstyle" => &["pnum", "onum"], + "ProportionalLining" => &["pnum", "lnum"], + "TabularOldstyle" => &["tnum", "onum"], + "Default" => &[], + _ => &[], + }; + if matches!(style.as_str(), "TabularLining" | "ProportionalOldstyle" | "ProportionalLining" | "TabularOldstyle" | "Default") { + result.features.retain(|feature| !matches!(feature.as_str(), "tnum" | "pnum" | "lnum" | "onum")); + result.features.extend(tags.iter().map(|tag| (*tag).to_owned())); + result.present = true; + } + } + if let Some(mask) = values.num("OTFStylisticSets") { + let mask = mask.max(0.0) as u32; + result.features.retain(|feature| !(feature.len() == 4 && feature.starts_with("ss") && feature[2..].parse::().is_ok())); + result.features.extend((1..=20).filter(|number| mask & (1 << (number - 1)) != 0).map(|number| format!("ss{number:02}"))); + result.present = true; + } + result + } +} + +/// Raw character-level Japanese composition and emphasis properties from an IDML text range. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CjkCharacterValues { + pub kenten_kind: Option, + pub kenten_custom_character: Option, + pub kenten_font: Option, + pub kenten_font_style: Option, + pub kenten_size: Option, + pub kenten_x_scale: Option, + pub kenten_y_scale: Option, + pub kenten_distance: Option, + pub kenten_position: Option, + pub kenten_alignment: Option, + pub kenten_character_set: Option, + pub kenten_fill_color: Option, + pub kenten_stroke_color: Option, + pub kenten_fill_tint: Option, + pub kenten_stroke_tint: Option, + pub kenten_stroke_weight: Option, + pub kenten_overprint_fill: Option, + pub kenten_overprint_stroke: Option, + pub shatai_magnification: Option, + pub shatai_angle: Option, + pub shatai_adjust_rotation: Option, + pub shatai_adjust_tsume: Option, +} + +impl CjkCharacterValues { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + kenten_kind: values.get("KentenKind").map(str::to_owned), + kenten_custom_character: values.prop("KentenCustomCharacter"), + kenten_font: values.prop("KentenFont"), + kenten_font_style: values.prop("KentenFontStyle"), + kenten_size: values.num("KentenFontSize"), + kenten_x_scale: values.num("KentenXScale"), + kenten_y_scale: values.num("KentenYScale"), + kenten_distance: values.num("KentenPlacement"), + kenten_position: values.prop("KentenPosition"), + kenten_alignment: values.prop("KentenAlignment"), + kenten_character_set: values.prop("KentenCharacterSet"), + kenten_fill_color: values.prop("KentenFillColor"), + kenten_stroke_color: values.prop("KentenStrokeColor"), + kenten_fill_tint: values.num("KentenTint"), + kenten_stroke_tint: values.num("KentenStrokeTint"), + kenten_stroke_weight: values.num("KentenWeight"), + kenten_overprint_fill: values.prop("KentenOverprintFill"), + kenten_overprint_stroke: values.prop("KentenOverprintStroke"), + shatai_magnification: values.num("ShataiMagnification"), + shatai_angle: values.num("ShataiDegreeAngle"), + shatai_adjust_rotation: values.boolean("ShataiAdjustRotation"), + shatai_adjust_tsume: values.boolean("ShataiAdjustTsume"), + } + } +} + +/// Numeric and boolean values in an IDML `MojikumiTable` row. +#[derive(Clone, Debug, PartialEq)] +pub struct MojikumiRow { + pub target_class: i16, + pub side_class: i16, + pub after: bool, + pub minimum: f64, + pub desired: f64, + pub maximum: f64, + pub priority: i16, + pub does_not_float: bool, +} + +impl MojikumiRow { + /// Parses the IDML mojikumi row attributes with bounded integer and finite-number checks. + pub fn from_el(el: &El) -> Result { + let values = Values::of(el); + let number = |key: &str| -> Result { + let Some(raw) = values.get(key) else { return Ok(0.0) }; + raw.trim().parse::().ok().filter(|value| value.is_finite()).ok_or_else(|| format!("Mojikumi row has invalid {key}")) + }; + let integer = |key: &str| -> Result { + let value = number(key)?; + if value.fract() != 0.0 || value < f64::from(i16::MIN) || value > f64::from(i16::MAX) { + return Err(format!("Mojikumi {key} must be an in-range integer")); + } + Ok(value as i16) + }; + let boolean = |key: &str| -> Result { + match values.get(key).map(str::trim) { + None | Some("false") => Ok(false), + Some("true") => Ok(true), + _ => Err(format!("Mojikumi row has invalid {key}")), + } + }; + Ok(Self { + target_class: integer("TargetMojikumiClass")?, + side_class: integer("SideMojikumiClass")?, + after: boolean("SideIsAfterTarget")?, + minimum: number("Minimum")?, + desired: number("Desired")?, + maximum: number("Maximum")?, + priority: integer("CompressionPriority")?, + does_not_float: boolean("AkiDoesNotFloat")?, + }) + } +} + +/// One IDML tab stop, before the caller maps alignment names into its text model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TabStopValues { + pub position: f64, + pub alignment: String, + pub leader: String, + pub alignment_character: String, +} + +impl TabStopValues { + /// Reads `ListItem` records in a `TabList` property. Invalid or non-finite positions use 0, + /// matching IDML import fallback behavior; semantic sanitization belongs to the caller. + pub fn from_list(list: &El) -> Vec { + list.children("ListItem") + .map(|item| { + let text = |name: &str| item.child_text(name).map(|value| value.into_owned()); + Self { + position: text("Position").and_then(|value| value.trim().parse::().ok()).filter(|value| value.is_finite()).unwrap_or(0.0), + alignment: text("Alignment").unwrap_or_default(), + leader: text("Leader").unwrap_or_default(), + alignment_character: text("AlignmentCharacter").unwrap_or_default(), + } + }) + .collect() + } + + /// Writes tab-stop records in a `TabList` property. + pub fn to_list(stops: &[Self]) -> El { + let mut list = El::new("TabList").with_attr("type", "list"); + for stop in stops { + list.push( + El::new("ListItem") + .with_attr("type", "record") + .with_child(property("Alignment", "enumeration", stop.alignment.clone())) + .with_child(property("AlignmentCharacter", "string", stop.alignment_character.clone())) + .with_child(property("Leader", "string", stop.leader.clone())) + .with_child(property("Position", "unit", crate::value::num(stop.position))), + ); + } + list + } +} + /// What a style styles. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StyleKind { @@ -73,6 +1260,65 @@ pub struct StyleGroup { pub children: Vec, } +/// Builds the nested style-folder tree written under an IDML root style group. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StyleGroupWriter { + kind: Option, + root_self_id: String, + styles: Vec, + groups: Vec<(String, StyleGroupWriter)>, +} + +impl StyleGroupWriter { + pub fn new(kind: StyleKind, root_self_id: impl Into) -> Self { + Self { kind: Some(kind), root_self_id: root_self_id.into(), ..Self::default() } + } + + /// Adds a style at its slash-separated folder path. Built-in names in brackets remain at + /// the root, and folder nesting is capped at 32 levels. + pub fn insert(&mut self, name: &str, style: El) { + let builtin = name.starts_with('['); + let mut segments: Vec<&str> = if builtin { vec![name] } else { name.split('/').collect() }; + segments.pop(); + let mut group = self; + for segment in segments.into_iter().take(32) { + let index = match group.groups.iter().position(|(name, _)| name == segment) { + Some(index) => index, + None => { + group.groups.push((segment.to_string(), StyleGroupWriter { kind: group.kind, ..Self::default() })); + group.groups.len() - 1 + } + }; + group = &mut group.groups[index].1; + } + group.styles.push(style); + } + + /// The complete root style group and its nested groups. + pub fn to_el(self) -> El { + let Some(kind) = self.kind else { + return El::new("RootStyleGroup"); + }; + let root_self_id = self.root_self_id.clone(); + self.emit(kind.root(), &root_self_id, kind.group(), "") + } + + fn emit(self, root_name: &str, self_id: &str, group_name: &str, path: &str) -> El { + let mut element = El::new(root_name).with_attr("Self", self_id); + for style in self.styles { + element.push(style); + } + for (name, group) in self.groups { + let full = if path.is_empty() { name.clone() } else { format!("{path}:{name}") }; + let nested = group.emit(group_name, &format!("{group_name}/{}", crate::value::escape_id(&full)), group_name, &full); + let mut nested = nested; + nested.set_attr("Name", name); + element.push(nested); + } + element + } +} + /// A child of a style group, in document order. #[derive(Clone, Debug, PartialEq)] pub enum StyleNode { @@ -81,6 +1327,38 @@ pub enum StyleNode { Other(El), } +/// EPUB export tagging stored on a style in IDML. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EpubExportTagMap { + pub tag: String, + pub class: String, + pub split_document: bool, +} + +impl EpubExportTagMap { + /// Reads an EPUB `StyleExportTagMap`; other export types are not this record. + pub fn from_el(el: &El) -> Option { + let values = Values::of(el); + (el.local() == "StyleExportTagMap" && values.get("ExportType") == Some("EPUB")).then(|| Self { + tag: values.get("ExportTag").unwrap_or("").to_owned(), + class: values.get("ExportClass").unwrap_or("").to_owned(), + split_document: values.get("SplitDocument") == Some("true"), + }) + } + + /// Writes the EPUB tag map with its caller-assigned IDML `Self` identifier. + pub fn to_el(&self, self_id: &str) -> El { + El::new("StyleExportTagMap") + .with_attr("Self", self_id) + .with_attr("ExportType", "EPUB") + .with_attr("ExportTag", &self.tag) + .with_attr("ExportClass", &self.class) + .with_attr("ExportAttributes", "") + .with_attr("SplitDocument", if self.split_document { "true" } else { "false" }) + .with_attr("EmitCss", "true") + } +} + /// A style, its values as written: `Name`, `Self`, `Properties/BasedOn`, its attributes; and its /// other children (an object style's `TextFramePreference`, effect settings, …). #[derive(Clone, Debug, PartialEq)] @@ -90,6 +1368,44 @@ pub struct Style { pub rest: Vec, } +/// Parsed assignments on an IDML object style before application style-reference resolution. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ObjectStyleValues { + pub name: Option, + pub based_on: Option, + pub fill_enabled: bool, + pub fill_color: Option, + pub fill_tint: Option, + pub stroke_enabled: bool, + pub paragraph_style_enabled: bool, + pub paragraph_style: Option, + pub text_frame_general_options: bool, + pub text_frame_preference: Option, +} + +impl ObjectStyleValues { + /// Reads object-style enable flags and the values controlled by those flags. + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let enabled = |flag: &str, attribute: &str| match values.get(flag) { + Some(value) => value == "true", + None => values.get(attribute).is_some(), + }; + Self { + name: values.name().map(str::to_owned), + based_on: values.prop("BasedOn"), + fill_enabled: enabled("EnableFill", "FillColor"), + fill_color: values.get("FillColor").map(str::to_owned), + fill_tint: values.num("FillTint"), + stroke_enabled: enabled("EnableStroke", "StrokeColor"), + paragraph_style_enabled: enabled("EnableParagraphStyle", "AppliedParagraphStyle"), + paragraph_style: values.get("AppliedParagraphStyle").map(str::to_owned), + text_frame_general_options: values.get("EnableTextFrameGeneralOptions") == Some("true"), + text_frame_preference: el.child(Local("TextFramePreference")).cloned(), + } + } +} + impl StyleGroup { /// The root group `el`; `None` when `el` is no root style group. pub fn from_el(el: &El) -> Option { @@ -238,6 +1554,14 @@ pub struct GradientStop { pub midpoint: f64, } +/// A `GradientStop` in source order, including optional values as written. +#[derive(Clone, Debug, PartialEq)] +pub struct GradientStopValue { + pub color: Option, + pub location: Option, + pub midpoint: Option, +} + impl Swatch { pub fn to_el(&self) -> El { let mut el = self.values.element(self.kind.name()); @@ -296,6 +1620,22 @@ impl Swatch { }) .collect() } + + /// Every gradient stop in source order, retaining absent or malformed optional values. + pub fn stops_in_order(&self) -> Vec { + self.rest + .iter() + .filter(|e| e.local() == "GradientStop") + .map(|e| { + let values = Values::of(e); + GradientStopValue { + color: values.get("StopColor").map(str::to_string), + location: values.num("Location"), + midpoint: values.num("Midpoint"), + } + }) + .collect() + } } /// The swatches among `top`, in order. @@ -364,6 +1704,360 @@ pub struct ColorGroup { pub rest: Vec, } +/// An Ink Manager entry, preserving its source values. +#[derive(Clone, Debug, PartialEq)] +pub struct Ink { + pub values: Values, +} + +/// A neutral colour definition for writing `Graphic.xml`. +/// +/// The caller supplies colour-space values as IDML's serialized value list; this type owns the +/// element and attribute grammar so applications do not need to emit `Color` XML themselves. +#[derive(Clone, Debug, PartialEq)] +pub struct ColorDefinition { + pub self_id: String, + pub name: String, + pub model: String, + pub space: String, + pub value: String, + pub override_kind: String, + pub editable: bool, + pub removable: bool, + pub visible: bool, +} + +impl ColorDefinition { + pub fn to_el(&self) -> El { + El::new("Color") + .with_attr("Self", &self.self_id) + .with_attr("Model", &self.model) + .with_attr("Space", &self.space) + .with_attr("ColorValue", &self.value) + .with_attr("ColorOverride", &self.override_kind) + .with_attr("AlternateSpace", "NoAlternateColor") + .with_attr("AlternateColorValue", "") + .with_attr("Name", &self.name) + .with_attr("ColorEditable", self.editable) + .with_attr("ColorRemovable", self.removable) + .with_attr("Visible", self.visible) + .with_attr("SwatchCreatorID", "7937") + } +} + +/// A neutral `Ink` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct InkDefinition { + pub self_id: String, + pub name: String, + pub alias: Option, + pub angle: String, + pub convert_to_process: bool, + pub frequency: String, + pub neutral_density: String, + pub trap_order: usize, + pub ink_type: String, +} + +impl InkDefinition { + fn to_el(&self) -> El { + let mut el = El::new("Ink") + .with_attr("Self", &self.self_id) + .with_attr("Name", &self.name) + .with_attr("Angle", &self.angle) + .with_attr("ConvertToProcess", self.convert_to_process) + .with_attr("Frequency", &self.frequency) + .with_attr("NeutralDensity", &self.neutral_density) + .with_attr("PrintInk", "true") + .with_attr("TrapOrder", self.trap_order) + .with_attr("InkType", &self.ink_type); + if let Some(alias) = &self.alias { + el.set_attr("AliasInkName", alias); + } + el + } +} + +/// A neutral `Tint` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct TintDefinition { + pub self_id: String, + pub value: String, + pub base_color: String, + pub name: String, +} + +impl TintDefinition { + fn to_el(&self) -> El { + El::new("Tint") + .with_attr("Self", &self.self_id) + .with_attr("TintValue", &self.value) + .with_attr("BaseColor", &self.base_color) + .with_attr("Name", &self.name) + .with_attr("ColorOverride", "Normal") + .with_attr("AlternateSpace", "NoAlternateColor") + .with_attr("AlternateColorValue", "") + .with_attr("ColorEditable", "true") + .with_attr("ColorRemovable", "true") + .with_attr("Visible", "true") + .with_attr("SwatchCreatorID", "7937") + } +} + +/// A stop in a neutral `Gradient` definition. +#[derive(Clone, Debug, PartialEq)] +pub struct GradientStopDefinition { + pub self_id: String, + pub color_id: String, + pub location: String, + pub midpoint: Option, +} + +/// A neutral `Gradient` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct GradientDefinition { + pub self_id: String, + pub name: String, + pub radial: bool, + pub stops: Vec, +} + +impl GradientDefinition { + fn to_el(&self) -> El { + let mut el = El::new("Gradient") + .with_attr("Self", &self.self_id) + .with_attr("Type", if self.radial { "Radial" } else { "Linear" }) + .with_attr("Name", &self.name) + .with_attr("ColorEditable", "true") + .with_attr("ColorRemovable", "true") + .with_attr("Visible", "true") + .with_attr("SwatchCreatorID", "7937"); + for stop in &self.stops { + let mut child = + El::new("GradientStop").with_attr("Self", &stop.self_id).with_attr("StopColor", &stop.color_id).with_attr("Location", &stop.location); + if let Some(midpoint) = &stop.midpoint { + child.set_attr("Midpoint", midpoint); + } + el.push(child); + } + el + } +} + +/// A member reference in a neutral `ColorGroup` definition. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ColorGroupMember { + pub self_id: String, + pub swatch_id: String, +} + +/// A neutral `ColorGroup` definition in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ColorGroupDefinition { + pub self_id: String, + pub name: String, + pub members: Vec, +} + +impl ColorGroupDefinition { + fn to_el(&self) -> El { + let mut el = El::new("ColorGroup").with_attr("Self", &self.self_id).with_attr("Name", &self.name).with_attr("IsRootColorGroup", "false"); + for member in &self.members { + el.push(El::new("ColorGroupSwatch").with_attr("Self", &member.self_id).with_attr("SwatchItemRef", &member.swatch_id)); + } + el + } +} + +/// A custom stroke style in `Graphic.xml`. +#[derive(Clone, Debug, PartialEq)] +pub enum StrokeDefinition { + Striped { self_id: String, name: String, array: String }, + Dashed { self_id: String, name: String, array: String }, + Dotted { self_id: String, name: String, array: String }, + Named { self_id: String, name: String }, +} + +impl StrokeDefinition { + fn to_el(&self) -> El { + match self { + Self::Striped { self_id, name, array } => { + El::new("StripedStrokeStyle").with_attr("StripeArray", array).with_attr("Self", self_id).with_attr("Name", name) + } + Self::Dashed { self_id, name, array } => { + El::new("DashedStrokeStyle").with_attr("DashArray", array).with_attr("Self", self_id).with_attr("Name", name) + } + Self::Dotted { self_id, name, array } => { + El::new("DottedStrokeStyle").with_attr("DotArray", array).with_attr("Self", self_id).with_attr("Name", name) + } + Self::Named { self_id, name } => El::new("StrokeStyle").with_attr("Self", self_id).with_attr("Name", name), + } + } +} + +/// Semantic values needed to write the `Graphic.xml` part. This type owns element names, +/// attributes, child ordering and the required None swatch; callers supply their mapped values. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GraphicPart { + pub colors: Vec, + pub inks: Vec, + pub tints: Vec, + pub gradients: Vec, + pub color_groups: Vec, + pub stroke_styles: Vec, +} + +impl GraphicPart { + pub fn to_el(&self) -> El { + let mut root = crate::part_root("Graphic"); + for color in &self.colors { + root.push(color.to_el()); + } + for ink in &self.inks { + root.push(ink.to_el()); + } + for tint in &self.tints { + root.push(tint.to_el()); + } + root.push( + El::new("Swatch") + .with_attr("Self", "Swatch/None") + .with_attr("Name", "None") + .with_attr("ColorEditable", "false") + .with_attr("ColorRemovable", "false") + .with_attr("Visible", "true") + .with_attr("SwatchCreatorID", "7937"), + ); + for gradient in &self.gradients { + root.push(gradient.to_el()); + } + for group in &self.color_groups { + root.push(group.to_el()); + } + for style in &self.stroke_styles { + root.push(style.to_el()); + } + root + } +} + +/// A composite-font entry, including the applied font family stored in `Properties`. +#[derive(Clone, Debug, PartialEq)] +pub struct CompositeFontEntryDefinition { + pub self_id: String, + pub name: String, + pub characters: String, + pub font_style: String, + pub relative_size: String, + pub horizontal_scale: String, + pub vertical_scale: String, + pub baseline_shift: String, + pub scale_option: bool, + pub applied_font: String, +} + +/// A composite font in `Fonts.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct CompositeFontDefinition { + pub self_id: String, + pub name: String, + pub entries: Vec, +} + +/// A font face in a family in `Fonts.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct FontDefinition { + pub self_id: String, + pub family: String, + pub name: String, + pub postscript_name: String, + pub style: String, +} + +/// A family of font faces in `Fonts.xml`. +#[derive(Clone, Debug, PartialEq)] +pub struct FontFamilyDefinition { + pub self_id: String, + pub name: String, + pub fonts: Vec, +} + +/// Neutral data for writing the complete `Fonts.xml` part. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FontsPart { + pub composites: Vec, + pub families: Vec, +} + +impl FontsPart { + pub fn to_el(&self) -> El { + let mut root = crate::part_root("Fonts"); + for composite in &self.composites { + let mut element = El::new("CompositeFont").with_attr("Self", &composite.self_id).with_attr("Name", &composite.name); + for entry in &composite.entries { + let mut node = El::new("CompositeFontEntry") + .with_attr("Self", &entry.self_id) + .with_attr("Name", &entry.name) + .with_attr("CustomCharacters", &entry.characters) + .with_attr("FontStyle", &entry.font_style) + .with_attr("RelativeSize", &entry.relative_size) + .with_attr("HorizontalScale", &entry.horizontal_scale) + .with_attr("VerticalScale", &entry.vertical_scale) + .with_attr("BaselineShift", &entry.baseline_shift) + .with_attr("ScaleOption", entry.scale_option); + let mut properties = El::new("Properties"); + properties.push(crate::prop("AppliedFont", "string", &entry.applied_font)); + node.push(properties); + element.push(node); + } + root.push(element); + } + for family in &self.families { + let mut element = El::new("FontFamily").with_attr("Self", &family.self_id).with_attr("Name", &family.name); + for font in &family.fonts { + element.push( + El::new("Font") + .with_attr("Self", &font.self_id) + .with_attr("FontFamily", &font.family) + .with_attr("Name", &font.name) + .with_attr("PostScriptName", &font.postscript_name) + .with_attr("Status", "NotAvailable") + .with_attr("FontStyleName", &font.style) + .with_attr("FontType", "OpenTypeTT") + .with_attr("WritingScript", "0") + .with_attr("FullName", &font.name) + .with_attr("FullNameNative", &font.name) + .with_attr("FontStyleNameNative", &font.style) + .with_attr("PlatformName", "$ID/") + .with_attr("Version", "$ID/") + .with_attr("TypekitID", "$ID/"), + ); + } + root.push(element); + } + root + } +} + +impl Ink { + pub fn name(&self) -> Option<&str> { + self.values.name() + } + + pub fn convert_to_process(&self) -> bool { + self.values.get("ConvertToProcess") == Some("true") + } + + pub fn alias(&self) -> Option<&str> { + self.values.get("AliasInkName") + } +} + +/// Ink Manager entries among the document's top-level elements. +pub fn inks(top: &[El]) -> Vec { + top.iter().filter(|el| el.local() == "Ink").map(|el| Ink { values: Values::of(el) }).collect() +} + impl ColorGroup { pub fn to_el(&self) -> El { let mut el = self.values.element("ColorGroup"); diff --git a/crates/idml/src/model/spread.rs b/crates/idml/src/model/spread.rs index c4d535f899..e3f317c070 100644 --- a/crates/idml/src/model/spread.rs +++ b/crates/idml/src/model/spread.rs @@ -17,6 +17,60 @@ fn with_children(mut el: El, children: impl IntoIterator) -> El { el } +/// Raw clip-path settings attached to a placed graphic, before the caller maps type and +/// coordinates into its scene model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ClippingPathValues { + pub clipping_type: Option, + pub geometry: PathGeometry, + pub invert: Option, + pub include_inside_edges: Option, + pub restrict_to_frame: Option, + pub use_high_resolution: Option, + pub threshold: Option, + pub tolerance: Option, + pub inset: Option, + pub source_name: Option, + pub index: Option, +} + +impl ClippingPathValues { + /// Reads a graphic's `ClippingPathSettings` and saved geometry, with the caller's point cap. + pub fn from_graphic(graphic: &El, max_points: usize) -> Option { + let settings = graphic.find("ClippingPathSettings")?; + let settings_values = Values::of(settings); + let graphic_values = Values::of(graphic); + let clipping_type = settings_values.get("ClippingType").map(str::to_owned); + let invert = settings_values.boolean("InvertPath"); + let include_inside_edges = settings_values.boolean("IncludeInsideEdges"); + let restrict_to_frame = settings_values.boolean("RestrictToFrame"); + let use_high_resolution = settings_values.boolean("UseHighResolutionImage"); + let threshold = settings_values.num("Threshold"); + let tolerance = settings_values.num("Tolerance"); + let inset = settings_values.num("InsetFrame"); + let source_name = settings_values.get("AppliedPathName").map(str::to_owned); + let index = settings_values.num("Index"); + let geometry = settings_values + .prop_el("ClippingPathGeometry") + .or_else(|| settings.find("ClippingPathGeometry")) + .or_else(|| graphic_values.prop_el("ClippingPathGeometry"))?; + let geometry = PathGeometry::from_el_capped(geometry, max_points); + Some(Self { + clipping_type, + geometry, + invert, + include_inside_edges, + restrict_to_frame, + use_high_resolution, + threshold, + tolerance, + inset, + source_name, + index, + }) + } +} + /// A spread (`Spread`) or a parent spread (`MasterSpread`). #[derive(Clone, Debug, Default, PartialEq)] pub struct Spread { @@ -86,6 +140,52 @@ impl Spread { pub fn parent_name(&self) -> Option<(&str, &str)> { Some((self.values.get("NamePrefix")?, self.values.get("BaseName")?)) } + + /// Parent spread's prefix, using the prefix of `Name` or `A` when absent. + pub fn parent_prefix(&self) -> String { + self.values.get("NamePrefix").map(str::to_string).unwrap_or_else(|| self.name().split('-').next().unwrap_or("A").to_string()) + } + + /// Parent spread's base name, using the suffix of `Name` or `Parent` when absent. + pub fn base_name(&self) -> String { + self.values + .get("BaseName") + .map(str::to_string) + .unwrap_or_else(|| self.name().split_once('-').map(|(_, b)| b.to_string()).unwrap_or_else(|| self.name().to_string())) + } + + pub fn name(&self) -> &str { + self.values.name().unwrap_or("Parent") + } + + /// Whether master page items are shown. + pub fn show_master_items(&self) -> bool { + self.values.boolean("ShowMasterItems") != Some(false) + } + + /// Whether page shuffle is allowed. + pub fn allow_shuffle(&self) -> bool { + self.values.boolean("AllowPageShuffle") != Some(false) + } + + /// Exact quarter-turn view rotation encoded by the spread transform, clockwise on screen. + pub fn view_rotation(&self) -> u8 { + if self.master { + return 0; + } + let [a, b, c, d, _, _] = self.values.item_transform(); + let is = |x: f64, y: f64| (x - y).abs() < 1e-6; + let quarter = |m: [f64; 4]| is(a, m[0]) && is(b, m[1]) && is(c, m[2]) && is(d, m[3]); + if quarter([0.0, 1.0, -1.0, 0.0]) { + 1 + } else if quarter([-1.0, 0.0, 0.0, -1.0]) { + 2 + } else if quarter([0.0, -1.0, 1.0, 0.0]) { + 3 + } else { + 0 + } + } } /// The spreads and parent spreads of a document, in its order. @@ -100,6 +200,44 @@ pub struct Page { pub children: Vec, } +/// Parsed layout values of an IDML `MarginPreference`. +#[derive(Clone, Debug, PartialEq)] +pub struct MarginPreference { + pub values: Values, +} + +impl MarginPreference { + pub fn from_el(el: &El) -> Self { + Self { values: Values::of(el) } + } + pub fn top(&self) -> Option { + self.values.num("Top") + } + pub fn left(&self) -> Option { + self.values.num("Left") + } + pub fn bottom(&self) -> Option { + self.values.num("Bottom") + } + pub fn right(&self) -> Option { + self.values.num("Right") + } + pub fn column_count(&self) -> Option { + self.values.num("ColumnCount") + } + pub fn column_gutter(&self) -> Option { + self.values.num("ColumnGutter") + } + + /// Parse at most `limit` whitespace-separated `ColumnsPositions` values; malformed or + /// non-finite values invalidate the list. + pub fn column_positions(&self, limit: usize) -> Option> { + let source = self.values.get("ColumnsPositions")?; + let values: Option> = source.split_whitespace().take(limit).map(|v| v.parse::().ok().filter(|v| v.is_finite())).collect(); + values.filter(|values| !values.is_empty()) + } +} + /// A child of a page, in document order. #[derive(Clone, Debug, PartialEq)] pub enum PageChild { @@ -142,6 +280,20 @@ impl Page { self.values.get("AppliedMaster").filter(|m| *m != "n") } + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + /// `ItemTransform`; the identity when absent or malformed. + pub fn item_transform(&self) -> Matrix { + self.values.item_transform() + } + + /// `LayoutRule`, defaulting to `Off`. + pub fn layout_rule(&self) -> &str { + self.values.get("LayoutRule").unwrap_or("Off") + } + /// `OverrideList`: the `Self`s of the parent items overridden on this page. pub fn override_list(&self) -> Vec<&str> { self.values.get("OverrideList").map(|l| l.split_whitespace().collect()).unwrap_or_default() @@ -155,6 +307,10 @@ impl Page { }) } + pub fn margin_settings(&self) -> Option { + self.margin_preference().map(|values| MarginPreference { values }) + } + pub fn guides(&self) -> impl DoubleEndedIterator { self.children.iter().filter_map(|c| if let PageChild::Guide(g) = c { Some(g) } else { None }) } @@ -188,6 +344,16 @@ impl Guide { pub fn liquid(&self) -> bool { self.values.get("GuideType") == Some("Liquid") } + + /// `Locked` is true. + pub fn locked(&self) -> bool { + self.values.boolean("Locked") == Some(true) + } + + /// `ItemLayer`: the identifier of the layer the guide belongs to. + pub fn item_layer(&self) -> Option<&str> { + self.values.item_layer() + } } /// What a page item is. @@ -297,6 +463,61 @@ impl PageItem { self.values.prop_el("PathGeometry").map(PathGeometry::from_el).unwrap_or_default() } + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + pub fn item_layer(&self) -> Option<&str> { + self.values.item_layer() + } + + pub fn item_transform(&self) -> Matrix { + self.values.item_transform() + } + + pub fn name(&self) -> Option<&str> { + self.values.name() + } + + pub fn locked(&self) -> bool { + self.values.locked() + } + + pub fn hidden(&self) -> bool { + !self.values.visible() + } + + pub fn nonprinting(&self) -> bool { + self.values.boolean("Nonprinting") == Some(true) + } + + pub fn gradient_fill_angle(&self) -> Option { + self.values.num("GradientFillAngle") + } + pub fn gradient_fill_start(&self) -> Option<[f64; 2]> { + self.values.pair("GradientFillStart") + } + pub fn gradient_fill_length(&self) -> Option { + self.values.num("GradientFillLength") + } + pub fn gradient_stroke_angle(&self) -> Option { + self.values.num("GradientStrokeAngle") + } + pub fn gradient_stroke_start(&self) -> Option<[f64; 2]> { + self.values.pair("GradientStrokeStart") + } + pub fn gradient_stroke_length(&self) -> Option { + self.values.num("GradientStrokeLength") + } + + pub fn text_path(&self) -> Option { + self.other("TextPath").map(|el| TextPath { values: Values::of(el) }) + } + + pub fn text_wrap(&self) -> Option { + self.other("TextWrapPreference").map(TextWrapPreference::from_el) + } + /// Replaces the outline. pub fn set_geometry(&mut self, g: &PathGeometry) { self.values.set_prop_el("PathGeometry", Some(g.to_el())); @@ -346,6 +567,169 @@ impl PageItem { } } +/// Parsed IDML `TextWrapPreference` values, including the nested offset and contour elements. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TextWrapPreference { + values: Values, + contour_type: Option, + offsets: Option<[f64; 4]>, +} + +/// Parsed IDML frame fitting options. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FrameFittingOption { + pub crop: [Option; 4], + pub alignment: Option, + pub auto_fit: bool, + pub fitting_on_empty_frame: Option, +} + +impl FrameFittingOption { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + Self { + crop: [values.num("TopCrop"), values.num("LeftCrop"), values.num("BottomCrop"), values.num("RightCrop")], + alignment: values.get("FittingAlignment").map(str::to_owned), + auto_fit: values.boolean("AutoFit") == Some(true), + fitting_on_empty_frame: values.get("FittingOnEmptyFrame").map(str::to_owned), + } + } +} + +/// IDML baseline-grid position relative to a page, frame, or inset. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum BaselineFrameGridRelative { + TopMargin, + TopOfFrame, + TopInset, + #[default] + TopOfPage, +} + +/// Parsed IDML custom baseline-grid options on an item or object style. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BaselineFrameGridOption { + pub use_custom: bool, + pub start: f64, + pub increment: f64, + pub relative_to: BaselineFrameGridRelative, +} + +impl BaselineFrameGridOption { + pub fn from_el(el: &El) -> Self { + let values = Values::of(el); + let relative = values.get("BaselineFrameGridRelativeOption").unwrap_or(""); + let relative = relative.strip_suffix("OfBaselineFrameGridRelativeOption").unwrap_or(relative); + let relative_to = match relative { + "TopOfMargin" | "TopMargin" => BaselineFrameGridRelative::TopMargin, + "TopOfFrame" => BaselineFrameGridRelative::TopOfFrame, + "TopOfInset" | "TopInset" => BaselineFrameGridRelative::TopInset, + _ => BaselineFrameGridRelative::TopOfPage, + }; + Self { + use_custom: values.boolean("UseCustomBaselineFrameGrid") == Some(true), + start: values.num("StartingOffsetForBaselineFrameGrid").unwrap_or(0.0), + increment: values.num("BaselineFrameGridIncrement").unwrap_or(12.0), + relative_to, + } + } +} + +impl TextWrapPreference { + pub fn from_el(el: &El) -> Self { + let contour_type = el.child(Local("ContourOption")).and_then(|c| Values::of(c).get("ContourType").map(str::to_string)); + let offsets = el.child(Local("Properties")).and_then(|p| p.child(Local("TextWrapOffset"))).map(|o| { + let values = Values::of(o); + [ + values.num("Top").unwrap_or(0.0), + values.num("Left").unwrap_or(0.0), + values.num("Bottom").unwrap_or(0.0), + values.num("Right").unwrap_or(0.0), + ] + }); + Self { values: Values::of(el), contour_type, offsets } + } + + pub fn mode(&self) -> Option<&str> { + self.values.get("TextWrapMode") + } + pub fn inverse(&self) -> bool { + self.values.boolean("Inverse") == Some(true) + } + pub fn side(&self) -> Option<&str> { + self.values.get("TextWrapSide") + } + pub fn contour_type(&self) -> Option<&str> { + self.contour_type.as_deref() + } + pub fn offsets(&self) -> Option<[f64; 4]> { + self.offsets + } + + /// Writes the IDML preference structure around caller-supplied enum values and path geometry. + pub fn to_el(mode: &str, inverse: bool, side: &str, contour: &str, offsets: [f64; 4], paths: &[PathGeometry]) -> El { + use crate::value::num; + + let mut properties = El::new("Properties"); + for path in paths { + properties.push(path.to_el()); + } + properties.push( + El::new("TextWrapOffset") + .with_attr("Top", num(offsets[0])) + .with_attr("Left", num(offsets[1])) + .with_attr("Bottom", num(offsets[2])) + .with_attr("Right", num(offsets[3])), + ); + El::new("TextWrapPreference") + .with_attr("Inverse", if inverse { "true" } else { "false" }) + .with_attr("ApplyToMasterPageOnly", "false") + .with_attr("TextWrapSide", side) + .with_attr("TextWrapMode", mode) + .with_child(properties) + .with_child(El::new("ContourOption").with_attr("ContourType", contour).with_attr("IncludeInsideEdges", "false")) + } +} + +/// Type-on-a-path settings. +#[derive(Clone, Debug, PartialEq)] +pub struct TextPath { + pub values: Values, +} + +impl TextPath { + /// Writes IDML type-on-a-path settings for a frame and its story. + pub fn to_el(frame_self: &str, parent_story: &str, alignment: &str, flipped: bool, start: f64, end: f64) -> El { + El::new("TextPath") + .with_attr("Self", format!("{frame_self}tp")) + .with_attr("ParentStory", parent_story) + .with_attr("PreviousTextFrame", "n") + .with_attr("NextTextFrame", "n") + .with_attr("PathEffect", "RainbowPathEffect") + .with_attr("PathAlignment", "CenterPathAlignment") + .with_attr("TextAlignment", alignment) + .with_attr("FlipPathEffect", if flipped { "Flipped" } else { "NotFlipped" }) + .with_attr("StartBracket", crate::value::num(start)) + .with_attr("EndBracket", crate::value::num(end)) + } + + pub fn parent_story(&self) -> Option<&str> { + self.values.get("ParentStory").filter(|s| *s != "n") + } + pub fn start_bracket(&self) -> Option { + self.values.num("StartBracket") + } + pub fn end_bracket(&self) -> Option { + self.values.num("EndBracket") + } + pub fn flipped(&self) -> bool { + self.values.get("FlipPathEffect") == Some("Flipped") + } + pub fn alignment(&self) -> Option<&str> { + self.values.get("TextAlignment") + } +} + /// What a placed graphic is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum GraphicKind { @@ -420,6 +804,119 @@ impl Link { } } +/// A placed graphic's layer choices, independent of the document model that stores them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct GraphicLayerOptions { + pub attributes: Vec<(String, String)>, + pub layers: Vec>, + /// Parent indices in pre-order. Missing entries and invalid parents are treated as top-level. + pub parents: Vec>, +} + +impl GraphicLayerOptions { + /// Reads a `GraphicLayerOption` subtree while preserving layer order and hierarchy. + pub fn from_el(option: &El) -> Self { + let attributes = option.attrs.iter().filter(|(key, _)| key != "Self").cloned().collect(); + let mut roots: Vec<_> = option.elements().collect(); + roots.reverse(); + let mut pending: Vec<_> = roots.into_iter().map(|element| (element, None)).collect(); + let mut layers = Vec::new(); + let mut parents = Vec::new(); + while let Some((element, parent)) = pending.pop() { + let layer_parent = if element.local() == "GraphicLayer" { + let index = layers.len(); + layers.push(element.attrs.iter().filter(|(key, _)| key != "Self").cloned().collect()); + parents.push(parent); + Some(index) + } else { + parent + }; + let mut children: Vec<_> = element.elements().collect(); + children.reverse(); + pending.extend(children.into_iter().map(|child| (child, layer_parent))); + } + Self { attributes, layers, parents } + } + + /// Serializes this layer tree, generating fresh IDs for the option and each layer. + pub fn to_el(&self, self_id: &str, mut fresh: impl FnMut() -> String) -> El { + let mut option = El::new("GraphicLayerOption").with_attr("Self", self_id); + for (key, value) in &self.attributes { + if valid_layer_attribute(key) { + option.set_attr(key, value); + } + } + // A parent must still be open in the pre-order walk. IDML layer groups have a depth cap. + let mut open = Vec::new(); + let mut parents = Vec::with_capacity(self.layers.len()); + for index in 0..self.layers.len() { + let parent = self.parents.get(index).copied().flatten(); + if let Some(at) = parent.and_then(|parent| open.iter().position(|id| *id == parent)).filter(|at| *at < 239) { + open.truncate(at + 1); + parents.push(parent); + } else { + open.clear(); + parents.push(None); + } + open.push(index); + } + let mut children: Vec> = (0..self.layers.len()).map(|_| Vec::new()).collect(); + let mut roots = Vec::new(); + for (index, attributes) in self.layers.iter().enumerate().rev() { + let mut layer = El::new("GraphicLayer").with_attr("Self", fresh()); + for (key, value) in attributes { + if valid_layer_attribute(key) { + layer.set_attr(key, value); + } + } + if let Some(nested) = children.get_mut(index) { + for child in std::mem::take(nested).into_iter().rev() { + layer.push(child); + } + } + if let Some(nested) = parents.get(index).copied().flatten().and_then(|parent| children.get_mut(parent)) { + nested.push(layer); + } else { + roots.push(layer); + } + } + for layer in roots.into_iter().rev() { + option.push(layer); + } + option + } +} + +fn valid_layer_attribute(key: &str) -> bool { + !key.is_empty() + && key != "Self" + && key != "xmlns" + && key + .bytes() + .enumerate() + .all(|(index, byte)| byte.is_ascii_alphabetic() || byte == b'_' || (index > 0 && (byte.is_ascii_digit() || matches!(byte, b'.' | b'-')))) +} + +/// A placed PDF's import options. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PdfAttribute { + values: Values, +} + +impl PdfAttribute { + pub fn page_index(&self) -> u32 { + self.values + .get("PageNumber") + .and_then(|value| value.trim().parse::().ok()) + .and_then(|page| u32::try_from(page.saturating_sub(1)).ok()) + .unwrap_or(0) + } + + pub fn crop(&self) -> Option<&str> { + self.values.get("PDFCrop") + } +} + impl Graphic { pub fn from_el(el: &El) -> Option { let kind = GraphicKind::of(el.local())?; @@ -449,6 +946,83 @@ impl Graphic { self.children.iter().find_map(|c| if let GraphicChild::Link(l) = c { Some(l) } else { None }) } + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + pub fn applied_object_style(&self) -> Option<&str> { + self.values.get("AppliedObjectStyle") + } + + pub fn item_transform(&self) -> Matrix { + self.values.item_transform() + } + + /// GraphicBounds in IDML's `Left`, `Top`, `Right`, `Bottom` order. + pub fn bounds(&self) -> [f64; 4] { + self.values + .prop_el("GraphicBounds") + .map(Values::of) + .map(|values| ["Left", "Top", "Right", "Bottom"].map(|key| values.num(key).unwrap_or(0.0))) + .unwrap_or([0.0; 4]) + } + + /// Two finite values from InDesign's `ActualPpi` field. + pub fn actual_ppi(&self) -> Option<[f64; 2]> { + let source = self.values.get("ActualPpi")?; + let numbers: Vec = source.split_whitespace().take(3).filter_map(|value| value.parse().ok()).collect(); + <[f64; 2]>::try_from(numbers).ok().filter(|values| values.iter().all(|value| value.is_finite())) + } + + pub fn fill_color(&self) -> Option<&str> { + self.values.get("FillColor") + } + + pub fn fill_tint(&self) -> Option { + self.values.num("FillTint") + } + + /// The MIME fallback when a linked graphic's bytes cannot be sniffed. + pub fn fallback_mime(&self) -> &'static str { + let format = self.link().and_then(Link::format).unwrap_or(""); + match format { + value if value.contains("EPS") || self.kind == GraphicKind::EPS => "application/postscript", + value if value.contains("JPEG") => "image/jpeg", + value if value.contains("TIFF") => "image/tiff", + value if value.contains("PDF") || self.kind == GraphicKind::PDF => "application/pdf", + value if value.contains("GIF") => "image/gif", + _ => "image/png", + } + } + + pub fn layer_options(&self) -> Option { + self.children + .iter() + .find_map(|child| match child { + GraphicChild::Other(el) if el.local() == "GraphicLayerOption" => Some(el), + GraphicChild::Other(el) => el.find("GraphicLayerOption"), + GraphicChild::Link(link) => { + link.rest.iter().find_map(|el| if el.local() == "GraphicLayerOption" { Some(el) } else { el.find("GraphicLayerOption") }) + } + }) + .or_else(|| self.values.prop_el("GraphicLayerOption")) + .map(GraphicLayerOptions::from_el) + } + + pub fn pdf_attribute(&self) -> Option { + self.children + .iter() + .find_map(|child| match child { + GraphicChild::Other(el) if el.local() == "PDFAttribute" => Some(el), + GraphicChild::Other(el) => el.find("PDFAttribute"), + GraphicChild::Link(link) => { + link.rest.iter().find_map(|el| if el.local() == "PDFAttribute" { Some(el) } else { el.find("PDFAttribute") }) + } + }) + .or_else(|| self.values.prop_el("PDFAttribute")) + .map(|el| PdfAttribute { values: Values::of(el) }) + } + /// `Properties/GraphicBounds`: `top left bottom right` in the graphic's inner coordinates. pub fn graphic_bounds(&self) -> Option<[f64; 4]> { let b = self.values.prop_el("GraphicBounds")?; diff --git a/crates/idml/src/model/story.rs b/crates/idml/src/model/story.rs index 889c7b350b..38839b0d3a 100644 --- a/crates/idml/src/model/story.rs +++ b/crates/idml/src/model/story.rs @@ -2,9 +2,116 @@ //! anchored page items, hyperlink and change containers). use craft_xml::{El, Local, Node}; +use std::collections::{BTreeMap, HashMap}; use super::{PageItem, Values, tidy}; +/// Resolved IDML anchored-object options from an item and its inherited style levels. +#[derive(Clone, Debug, PartialEq)] +pub struct AnchoredObjectValues { + pub position: String, + pub anchor_point: String, + pub horizontal_alignment: String, + pub horizontal_reference: String, + pub vertical_alignment: String, + pub vertical_reference: String, + pub pin_position: bool, + pub spine_relative: bool, + pub space_above: f64, + pub x_offset: f64, + pub y_offset: f64, +} + +/// An IDML `AnchoredObjectSetting` element. +#[derive(Clone, Debug, PartialEq)] +pub struct AnchoredObjectSetting { + attributes: Vec<(String, String)>, +} + +impl AnchoredObjectSetting { + pub fn inline_position(y_offset: f64) -> Self { + Self { attributes: vec![("AnchoredPosition".into(), "InlinePosition".into()), ("AnchorYoffset".into(), crate::value::num(y_offset))] } + } + + pub fn above_line(horizontal_alignment: &str, space_above: f64, y_offset: f64) -> Self { + Self { + attributes: vec![ + ("AnchoredPosition".into(), "AboveLine".into()), + ("HorizontalAlignment".into(), horizontal_alignment.into()), + ("AnchorSpaceAbove".into(), crate::value::num(space_above)), + ("AnchorYoffset".into(), crate::value::num(y_offset)), + ], + } + } + + #[allow(clippy::too_many_arguments)] + pub fn anchored( + anchor_point: &str, + horizontal_reference: &str, + vertical_reference: &str, + horizontal_alignment: &str, + vertical_alignment: &str, + x_offset: f64, + y_offset: f64, + pin_position: bool, + spine_relative: bool, + ) -> Self { + Self { + attributes: vec![ + ("AnchoredPosition".into(), "Anchored".into()), + ("AnchorPoint".into(), anchor_point.into()), + ("HorizontalReferencePoint".into(), horizontal_reference.into()), + ("VerticalReferencePoint".into(), vertical_reference.into()), + ("HorizontalAlignment".into(), horizontal_alignment.into()), + ("VerticalAlignment".into(), vertical_alignment.into()), + ("AnchorXoffset".into(), crate::value::num(x_offset)), + ("AnchorYoffset".into(), crate::value::num(y_offset)), + ("PinPosition".into(), bool_string(pin_position)), + ("SpineRelative".into(), bool_string(spine_relative)), + ], + } + } + + pub fn to_el(&self) -> El { + let mut element = El::new("AnchoredObjectSetting"); + for (key, value) in &self.attributes { + element.set_attr(key, value); + } + element + } +} + +fn bool_string(value: bool) -> String { + if value { "true" } else { "false" }.into() +} + +impl AnchoredObjectValues { + /// Resolves attributes item-first from `AnchoredObjectSetting` children. + pub fn from_elements(elements: &[&El]) -> Self { + let get = |key: &str, default: &str| { + elements + .iter() + .filter_map(|element| element.child(Local("AnchoredObjectSetting"))) + .find_map(|setting| Values::of(setting).get(key).map(str::to_owned)) + .unwrap_or_else(|| default.to_owned()) + }; + let number = |key: &str| get(key, "0").parse::().ok().filter(|value| value.is_finite()).unwrap_or(0.0); + Self { + position: get("AnchoredPosition", "InlinePosition"), + anchor_point: get("AnchorPoint", "BottomRightAnchor"), + horizontal_alignment: get("HorizontalAlignment", "LeftAlign"), + horizontal_reference: get("HorizontalReferencePoint", "TextFrame"), + vertical_alignment: get("VerticalAlignment", "BottomAlign"), + vertical_reference: get("VerticalReferencePoint", "LineBaseline"), + pin_position: get("PinPosition", "true") == "true", + spine_relative: get("SpineRelative", "false") == "true", + space_above: number("AnchorSpaceAbove"), + x_offset: number("AnchorXoffset"), + y_offset: number("AnchorYoffset"), + } + } +} + /// A `Story`. #[derive(Clone, Debug, Default, PartialEq)] pub struct Story { @@ -12,6 +119,26 @@ pub struct Story { pub children: Vec, } +/// The IDML `StoryPreference` element written for a story. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StoryPreference { + pub optical_margin_alignment: bool, + pub optical_margin_size: f64, + pub vertical: bool, + pub right_to_left: bool, +} + +impl StoryPreference { + pub fn to_el(self) -> El { + El::new("StoryPreference") + .with_attr("OpticalMarginAlignment", self.optical_margin_alignment) + .with_attr("OpticalMarginSize", self.optical_margin_size) + .with_attr("FrameType", "TextFrameType") + .with_attr("StoryOrientation", if self.vertical { "Vertical" } else { "Horizontal" }) + .with_attr("StoryDirection", if self.right_to_left { "RightToLeftDirection" } else { "LeftToRightDirection" }) + } +} + /// One node of a story's text, in document order. IDML nests freely (an `XMLElement` or a /// `HyperlinkTextSource` can hold paragraph ranges or content), so every container holds these. #[derive(Clone, Debug, PartialEq)] @@ -24,10 +151,19 @@ pub enum TextNode { Content(Vec), /// `Br`: the end of a paragraph. Break, + /// A processing instruction at a structural story position. The parent serializer preserves + /// it in place; `to_el` represents it as a one-instruction `Content` fragment. + ProcessingInstruction { + target: String, + data: String, + }, /// Text inside another element ([`CONTAINERS`]): a hyperlink's source, a tracked change, an /// XML element, a cross-reference's source, a footnote, a note. Container(Container), Table(Table), + Anchor(StoryAnchor), + PageReference(PageReference), + TextVariable(Values), /// A page item anchored in the text. Item(PageItem), /// Anything else (`StoryPreference`, `HyperlinkTextDestination`, `TextVariableInstance`, …), @@ -35,6 +171,264 @@ pub enum TextNode { Other(El), } +#[derive(Clone, Debug, PartialEq)] +pub struct StoryAnchor { + pub name: String, + pub values: Values, +} + +impl StoryAnchor { + /// Builds the IDML `Self` value for a hyperlink text destination. + pub fn destination_self(id: u64) -> String { + format!("HyperlinkTextDestination/a{id}") + } + + /// Writes an IDML `HyperlinkTextDestination` from a DesignCraft-independent anchor identity. + pub fn destination_el(id: u64, name: &str) -> El { + El::new("HyperlinkTextDestination") + .with_attr("Self", Self::destination_self(id)) + .with_attr("Name", name) + .with_attr("Hidden", "false") + .with_attr("DestinationUniqueKey", id & 0xFFFF_FFFF) + } + + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + pub fn label(&self) -> Option<&str> { + self.values.name() + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PageReference { + pub values: Values, +} + +/// Nested index topics and their See / See also references for one IDML `Index`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct IndexValues { + pub topics: BTreeMap, String>, + pub cross_references: Vec, +} + +/// An index cross-reference attached to a topic path. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IndexCrossReferenceValues { + pub from: Vec, + pub reference_type: String, + pub target: String, +} + +/// A topic path and its sort keys, as they are saved on nested IDML `Topic` elements. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct IndexTopicPath { + pub path: Vec, + pub sort: Vec, +} + +/// An IDML index cross-reference as stored under an index topic. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct IndexReference { + pub from: IndexTopicPath, + pub referenced_topic: Option, + pub reference_type: Option, +} + +/// Parsed IDML index topics and cross-references. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct IndexDocument { + pub topics: HashMap, + pub cross_references: Vec, +} + +impl IndexDocument { + pub fn from_el(element: &El) -> Self { + let mut result = Self::default(); + let mut stack: Vec<(&El, IndexTopicPath)> = + element.elements().filter(|child| child.local() == "Topic").map(|topic| (topic, IndexTopicPath::default())).collect(); + while let Some((topic, prefix)) = stack.pop() { + let name = topic.attr("Name").unwrap_or_default().to_string(); + let mut current = prefix.clone(); + current.path.push(name); + if let Some(key) = topic.attr("SortOrder").filter(|key| !key.is_empty()) { + current.sort.resize(prefix.path.len(), String::new()); + current.sort.push(key.to_string()); + } + if let Some(self_id) = topic.attr("Self") { + result.topics.insert(self_id.to_string(), current.clone()); + } + for child in topic.elements() { + if child.local() == "CrossReference" { + result.cross_references.push(IndexReference { + from: current.clone(), + referenced_topic: child.attr("ReferencedTopic").map(str::to_string), + reference_type: child.attr("CrossReferenceType").map(str::to_string), + }); + } else if child.local() == "Topic" { + stack.push((child, current.clone())); + } + } + } + result + } +} + +impl IndexValues { + /// Builds the IDML `Self` value for a topic path. + pub fn topic_self(path: &[String]) -> String { + let mut id = String::from("ix"); + for part in path { + id.push_str("Topicn"); + id.push_str(&crate::value::escape_id(part)); + } + id + } + + /// Writes the nested IDML index grammar, assigning a fresh ID to each cross-reference. + pub fn to_el(&self, mut fresh: impl FnMut() -> String) -> El { + let mut topics = self.topics.clone(); + for reference in &self.cross_references { + topics.entry(vec![reference.target.clone()]).or_default(); + } + + fn build( + topics: &BTreeMap, String>, + references: &[IndexCrossReferenceValues], + prefix: &[String], + fresh: &mut impl FnMut() -> String, + ) -> Vec { + let mut out = Vec::new(); + for (path, sort_order) in topics.iter().filter(|(path, _)| path.len() == prefix.len() + 1 && path.starts_with(prefix)) { + let mut element = El::new("Topic") + .with_attr("Self", IndexValues::topic_self(path)) + .with_attr("SortOrder", sort_order) + .with_attr("Name", path.last().map_or("", String::as_str)); + for reference in references.iter().filter(|reference| reference.from == *path) { + element.push( + El::new("CrossReference") + .with_attr("Self", fresh()) + .with_attr("ReferencedTopic", IndexValues::topic_self(std::slice::from_ref(&reference.target))) + .with_attr("CrossReferenceType", &reference.reference_type) + .with_attr("CustomTypeString", ""), + ); + } + element.children.extend(build(topics, references, path, fresh).into_iter().map(Node::El)); + out.push(element); + } + out + } + + let mut element = El::new("Index").with_attr("Self", "ix"); + element.children = build(&topics, &self.cross_references, &[], &mut fresh).into_iter().map(Node::El).collect(); + element + } +} + +/// Text saved inside an IDML `CrossReferenceSource` before the application regenerates it from +/// the cross-reference format. Page-number variables are separate segments so callers can retain +/// the last displayed page while mapping to their own text model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SavedCrossReference { + pub self_id: Option, + pub applied_format: Option, + pub parts: Vec, + /// The first directly nested character range, which supplies the marker's formatting. + pub character_range: Option, +} + +/// The IDML cross-reference source wrapper around its saved character range. +pub struct CrossReferenceSource; + +impl CrossReferenceSource { + pub fn to_el(self_id: &str, applied_format: &str, name: &str, character_range: El) -> El { + El::new("CrossReferenceSource") + .with_attr("Self", self_id) + .with_attr("AppliedFormat", applied_format) + .with_attr("Name", name) + .with_attr("Hidden", "false") + .with_child(character_range) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum SavedCrossReferencePart { + Text(String), + PageNumber { result_text: Option }, +} + +impl SavedCrossReference { + /// Reads the bounded saved-text grammar. `page_variables` contains IDs whose variable type is + /// the cross-reference page number; when the document omits variable definitions, InDesign's + /// conventional `TV XRefPageNumber` suffix is recognized. + pub fn from_el(el: &El, page_variables: &[String]) -> SavedCrossReference { + let mut parsed = SavedCrossReference { + self_id: el.attr("Self").map(str::to_string), + applied_format: el.attr("AppliedFormat").map(str::to_string), + parts: Vec::new(), + character_range: el.find(Local("CharacterStyleRange")).and_then(|range| match TextNode::from_el(range) { + TextNode::Character(range) => Some(range), + _ => None, + }), + }; + saved_xref_parts(el, page_variables, &mut parsed.parts, 0); + parsed + } + + pub fn from_container(container: &Container, page_variables: &[String]) -> SavedCrossReference { + Self::from_el(&container.to_el(), page_variables) + } +} + +fn saved_xref_parts(el: &El, page_variables: &[String], parts: &mut Vec, depth: usize) { + if depth > 16 { + return; + } + for child in el.elements() { + match child.local() { + "Content" => parts.push(SavedCrossReferencePart::Text(child.deep_text())), + "TextVariableInstance" => { + let id = child.attr("AssociatedTextVariable").unwrap_or_default(); + let page_number = + page_variables.iter().any(|variable| variable == id) || (page_variables.is_empty() && id.ends_with("TV XRefPageNumber")); + if page_number { + parts.push(SavedCrossReferencePart::PageNumber { result_text: child.attr("ResultText").map(str::to_string) }); + } else { + parts.push(SavedCrossReferencePart::Text(child.attr("ResultText").unwrap_or_default().to_string())); + } + } + "Change" if child.attr("ChangeType") == Some("DeletedText") => {} + "CharacterStyleRange" | "Change" => saved_xref_parts(child, page_variables, parts, depth + 1), + _ => {} + } + } +} + +impl PageReference { + pub fn referenced_topic(&self) -> Option<&str> { + self.values.get("ReferencedTopic") + } + pub fn reference_type(&self) -> Option<&str> { + self.values.get("PageReferenceType") + } + pub fn limit(&self) -> Option { + self.values.num("PageReferenceLimit") + } + + /// Writes a page-reference record from the shared index model's type and target. + pub fn to_el(self_id: &str, reference_type: &str, topic: &str, id: usize, limit: Option) -> El { + let mut el = El::new("PageReference") + .with_attr("Self", self_id) + .with_attr("PageReferenceType", reference_type) + .with_attr("ReferencedTopic", topic) + .with_attr("Id", id); + if let Some(limit) = limit { + el.set_attr("PageReferenceLimit", limit); + } + el + } +} + /// The elements read as [`TextNode::Container`]. pub const CONTAINERS: [&str; 7] = ["HyperlinkTextSource", "Change", "XMLElement", "CrossReferenceSource", "Footnote", "Note", "EndnoteRange"]; @@ -54,6 +448,54 @@ pub struct Container { pub children: Vec, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ContainerKind { + HyperlinkTextSource, + Change, + XMLElement, + CrossReferenceSource, + Footnote, + Note, + EndnoteRange, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TrackedChangeKind { + Deleted, + Inserted, + Other, +} + +impl Container { + pub fn to_el(&self) -> El { + with_children(self.values.element(&self.name), &self.children) + } + + pub fn kind(&self) -> ContainerKind { + match self.name.as_str() { + "HyperlinkTextSource" => ContainerKind::HyperlinkTextSource, + "Change" => ContainerKind::Change, + "XMLElement" => ContainerKind::XMLElement, + "CrossReferenceSource" => ContainerKind::CrossReferenceSource, + "Footnote" => ContainerKind::Footnote, + "Note" => ContainerKind::Note, + _ => ContainerKind::EndnoteRange, + } + } + + pub fn self_id(&self) -> Option<&str> { + self.values.self_id() + } + + pub fn change_kind(&self) -> Option { + (self.kind() == ContainerKind::Change).then(|| match self.values.get("ChangeType") { + Some("DeletedText") => TrackedChangeKind::Deleted, + Some("InsertedText" | "MovedText") => TrackedChangeKind::Inserted, + _ => TrackedChangeKind::Other, + }) + } +} + /// A piece of a `Content` element. #[derive(Clone, Debug, PartialEq)] pub enum ContentPart { @@ -85,6 +527,11 @@ pub enum Ace { } impl Ace { + /// Parses an IDML ACE instruction's decimal code. + pub fn from_decimal(value: &str) -> Option { + value.trim().parse::().ok().map(Ace::from_code) + } + pub fn from_code(code: u32) -> Ace { match code { 4 => Ace::FootnoteNumber, @@ -115,6 +562,63 @@ pub struct Table { pub children: Vec, } +/// The row and column grid of an IDML table, read without allocating cell models. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableLayout { + pub rows: Vec, + pub columns: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableRow { + pub values: Values, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableColumn { + pub values: Values, +} + +impl TableLayout { + pub fn from_el(el: &El) -> TableLayout { + Self::from_table(&Table::from_el(el)) + } + + pub fn from_table(table: &Table) -> TableLayout { + let mut layout = TableLayout::default(); + for child in &table.children { + if let TableChild::Other(element) = child { + match element.local() { + "Row" => layout.rows.push(TableRow { values: Values::of(element) }), + "Column" => layout.columns.push(TableColumn { values: Values::of(element) }), + _ => {} + } + } + } + layout + } +} + +impl TableRow { + pub fn auto_grow(&self) -> Option { + self.values.boolean("AutoGrow") + } + + pub fn minimum_height(&self) -> Option { + self.values.num("MinimumHeight") + } + + pub fn single_row_height(&self) -> Option { + self.values.num("SingleRowHeight") + } +} + +impl TableColumn { + pub fn single_column_width(&self) -> Option { + self.values.num("SingleColumnWidth") + } +} + /// A child of a table, in document order. #[derive(Clone, Debug, PartialEq)] pub enum TableChild { @@ -130,13 +634,34 @@ pub struct Cell { pub children: Vec, } +/// Format-level options on an IDML table cell, before DesignCraft maps them into its model. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CellOptions { + pub fill_color: Option, + pub fill_tint: Option, + pub insets: [Option; 4], + pub vertical_justification: Option, + pub first_baseline_offset: Option, + pub minimum_first_baseline_offset: Option, + pub rotation_angle: Option, + pub edge_stroke_priorities: [i32; 4], + pub edge_strokes: [super::StrokeValues; 4], +} + /// The children of `el` other than ``, as text nodes. fn nodes(el: &El) -> Vec { - el.elements().filter(|e| !e.is(Local("Properties"))).map(TextNode::from_el).collect() + el.children + .iter() + .filter_map(|node| match node { + Node::El(e) if !e.is(Local("Properties")) => Some(TextNode::from_el(e)), + Node::Pi { target, data } => Some(TextNode::ProcessingInstruction { target: target.clone(), data: data.clone() }), + _ => None, + }) + .collect() } fn with_children(mut el: El, children: &[TextNode]) -> El { - el.children.extend(children.iter().map(|c| Node::El(c.to_el()))); + el.children.extend(children.iter().map(TextNode::to_node)); el } @@ -148,6 +673,11 @@ impl TextNode { "Content" => TextNode::Content(content_parts(el)), "Br" => TextNode::Break, "Table" => TextNode::Table(Table::from_el(el)), + "HyperlinkTextDestination" | "ParagraphDestination" => { + TextNode::Anchor(StoryAnchor { name: el.local().to_string(), values: Values::of(el) }) + } + "PageReference" => TextNode::PageReference(PageReference { values: Values::of(el) }), + "TextVariableInstance" => TextNode::TextVariable(Values::of(el)), n if CONTAINERS.contains(&n) => TextNode::Container(Container { name: n.to_string(), values: Values::of(el), children: nodes(el) }), _ => PageItem::from_el(el).map_or_else(|| TextNode::Other(tidy(el)), TextNode::Item), } @@ -170,13 +700,30 @@ impl TextNode { c } TextNode::Break => El::new("Br"), + TextNode::ProcessingInstruction { target, data } => { + let mut content = El::new("Content"); + content.children.push(Node::Pi { target: target.clone(), data: data.clone() }); + content + } TextNode::Container(c) => with_children(c.values.element(&c.name), &c.children), TextNode::Table(t) => t.to_el(), + TextNode::Anchor(a) => a.values.element(&a.name), + TextNode::PageReference(r) => r.values.element("PageReference"), + TextNode::TextVariable(v) => v.element("TextVariableInstance"), TextNode::Item(i) => i.to_el(), TextNode::Other(e) => e.clone(), } } + /// Serializes this node in its parent position, preserving processing instructions as XML + /// instructions rather than wrapping them in an element. + pub fn to_node(&self) -> Node { + match self { + TextNode::ProcessingInstruction { target, data } => Node::Pi { target: target.clone(), data: data.clone() }, + _ => Node::El(self.to_el()), + } + } + /// The nodes this one holds; none for content, breaks, page items and others. pub fn children(&self) -> &[TextNode] { match self { @@ -226,6 +773,26 @@ impl Story { }) } + /// Whether `StoryDirection` selects right-to-left order. + pub fn right_to_left(&self) -> bool { + self.preference().and_then(|values| values.get("StoryDirection").map(str::to_string)).as_deref() == Some("RightToLeftDirection") + } + + /// Whether `StoryOrientation` selects vertical composition. + pub fn vertical(&self) -> bool { + self.preference().and_then(|values| values.get("StoryOrientation").map(str::to_string)).as_deref() == Some("Vertical") + } + + /// Whether optical margin alignment is enabled; false when absent. + pub fn optical_margin_enabled(&self) -> bool { + self.preference().and_then(|values| values.boolean("OpticalMarginAlignment")) == Some(true) + } + + /// The `OpticalMarginSize`, if finite. + pub fn optical_margin_size(&self) -> Option { + self.preference().and_then(|values| values.num("OpticalMarginSize")) + } + /// The story's paragraph ranges in reading order, those inside containers included, but not /// those of its tables, footnotes or notes (which are text of their own). pub fn paragraphs(&self) -> Vec<&Range> { @@ -275,6 +842,11 @@ fn text(nodes: &[TextNode], ace: &dyn Fn(Ace) -> Option) -> String { } } TextNode::Break => out.push('\n'), + TextNode::ProcessingInstruction { target, data } if target == "ACE" => { + if let Ok(code) = data.trim().parse::() { + out.extend(ace(Ace::from_code(code))); + } + } TextNode::Paragraph(r) | TextNode::Character(r) => stack.extend(r.children.iter().rev()), TextNode::Container(c) if inline_container(&c.name) => stack.extend(c.children.iter().rev()), _ => {} @@ -284,6 +856,11 @@ fn text(nodes: &[TextNode], ace: &dyn Fn(Ace) -> Option) -> String { } impl Range { + /// `ParagraphBreakType`, except `Anywhere` which means no forced break. + pub fn paragraph_break_type(&self) -> Option<&str> { + self.values.get("ParagraphBreakType").filter(|kind| *kind != "Anywhere") + } + /// `AppliedParagraphStyle` of a paragraph range. pub fn paragraph_style(&self) -> Option<&str> { self.values.get("AppliedParagraphStyle") @@ -378,6 +955,14 @@ impl Table { } impl Cell { + pub fn from_el(el: &El) -> Cell { + Cell { values: Values::of(el), children: nodes(el) } + } + + pub fn to_el(&self) -> El { + with_children(self.values.element("Cell"), &self.children) + } + /// `Name`: `column:row` of the cell's top left (`2:0`). pub fn position(&self) -> Option<(u32, u32)> { let (c, r) = self.values.name()?.split_once(':')?; @@ -390,6 +975,27 @@ impl Cell { (n("ColumnSpan"), n("RowSpan")) } + pub fn options(&self) -> CellOptions { + let inset = |current: &str, legacy: &str| self.values.num(current).or_else(|| self.values.num(legacy)); + let priority = |side: &str| self.values.prop(&format!("{side}StrokePriority")).and_then(|v| v.trim().parse().ok()).unwrap_or(0); + CellOptions { + fill_color: self.values.value("FillColor"), + fill_tint: self.values.num("FillTint"), + insets: [ + inset("TextTopInset", "TopInset"), + inset("TextLeftInset", "LeftInset"), + inset("TextBottomInset", "BottomInset"), + inset("TextRightInset", "RightInset"), + ], + vertical_justification: self.values.value("VerticalJustification"), + first_baseline_offset: self.values.value("FirstBaselineOffset"), + minimum_first_baseline_offset: self.values.num("MinimumFirstBaselineOffset"), + rotation_angle: self.values.num("RotationAngle"), + edge_stroke_priorities: [priority("TopEdge"), priority("LeftEdge"), priority("BottomEdge"), priority("RightEdge")], + edge_strokes: ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].map(|side| self.values.stroke_values(side)), + } + } + pub fn paragraphs(&self) -> Vec<&Range> { paragraphs(&self.children) } diff --git a/crates/idml/src/part.rs b/crates/idml/src/part.rs index e8fd72d6b1..d0d3661c30 100644 --- a/crates/idml/src/part.rs +++ b/crates/idml/src/part.rs @@ -22,6 +22,25 @@ pub const fn xml_limits() -> craft_xml::Limits { /// `META-INF/container.xml` of a package. pub const CONTAINER_XML: &str = "\n\n\t\n\t\t\n\t\n\n"; +/// The standard root element for `designmap.xml`, including its required namespace and core +/// document identity fields. The caller supplies DesignCraft-independent values; children are +/// appended after construction. +pub fn designmap_root(self_id: &str, story_list: &str, name: &str, zero_point: &str, active_layer: &str) -> El { + El::new("Document") + .with_attr("xmlns:idPkg", PACKAGING_NS) + .with_attr("DOMVersion", DOM_VERSION) + .with_attr("Self", self_id) + .with_attr("StoryList", story_list) + .with_attr("Name", name) + .with_attr("ZeroPoint", zero_point) + .with_attr("ActiveLayer", active_layer) +} + +/// An `idPkg` reference in `designmap.xml` to a part stored at `src`. +pub fn designmap_include(kind: &str, src: &str) -> El { + El::new(format!("idPkg:{kind}")).with_attr("src", src) +} + /// Parses a part into its root element with [`xml_limits`]. /// /// Names are kept as written (`idPkg:Story`), text is kept exactly (it is story content), CDATA @@ -112,10 +131,15 @@ pub fn part_xml(root: &El) -> Vec { /// `designmap.xml` as bytes: [`part_xml`] with the `` instruction that tells InDesign /// what the file is. pub fn designmap_xml(root: &El) -> Vec { + let pi = format!("", DOM_VERSION); + designmap_xml_with_pi(root, &pi) +} + +/// A designmap part with the caller's `` metadata instruction. +pub fn designmap_xml_with_pi(root: &El, pi: &str) -> Vec { let mut s = String::from(DECL_STANDALONE); - s.push_str("\n"); + s.push_str(pi); + s.push('\n'); root.write_xml_pretty(&mut s, "\t"); s.into_bytes() } diff --git a/crates/idml/src/value.rs b/crates/idml/src/value.rs index cb54644db8..ab09cbaecc 100644 --- a/crates/idml/src/value.rs +++ b/crates/idml/src/value.rs @@ -30,7 +30,15 @@ pub fn nums(s: &str) -> Vec { /// An `ItemTransform`: the six coefficients `a b c d tx ty`, or `None` when the value is not /// six finite numbers. pub fn matrix(s: &str) -> Option<[f64; 6]> { - <[f64; 6]>::try_from(nums(s)).ok() + let mut tokens = s.split_whitespace(); + let mut matrix = [0.0_f64; 6]; + for value in &mut matrix { + *value = tokens.next()?.parse().ok()?; + if !value.is_finite() { + return None; + } + } + tokens.next().is_none().then_some(matrix) } /// A transform as an `ItemTransform` value. diff --git a/crates/idml/tests/model.rs b/crates/idml/tests/model.rs index 98c94df1a1..075a77c821 100644 --- a/crates/idml/tests/model.rs +++ b/crates/idml/tests/model.rs @@ -266,3 +266,17 @@ fn deeply_nested_groups_are_read_and_walked() { let again = Spread::from_el(&parse_part(&part_xml(&s.to_el())).unwrap()); assert_eq!(again, s); } + +#[test] +fn text_variable_decoration_uses_preference_and_falls_back_to_legacy_root_values() { + let preferred = parse_part( + br#""#, + ) + .unwrap(); + let variable = craft_idml::model::TextVariableValues::from_el(&preferred); + assert_eq!((variable.before.as_str(), variable.after.as_str()), ("of ", " pages")); + + let legacy = parse_part(br#""#).unwrap(); + let variable = craft_idml::model::TextVariableValues::from_el(&legacy); + assert_eq!((variable.before.as_str(), variable.after.as_str()), ("of ", " pages")); +} diff --git a/crates/idml/tests/story.rs b/crates/idml/tests/story.rs index c21b1f398d..fe2642edce 100644 --- a/crates/idml/tests/story.rs +++ b/crates/idml/tests/story.rs @@ -69,6 +69,10 @@ fn a_story_reads_as_ranges_and_content() { // The body paragraph's character range holds every kind of node. let body = paras[1].characters(); assert_eq!(body.len(), 1); + let TextNode::Anchor(destination) = &body[0].children[6] else { panic!() }; + assert_eq!(destination.name, "HyperlinkTextDestination"); + assert_eq!(destination.values.self_id(), Some("ud1")); + assert_eq!(destination.values.value("Name").as_deref(), Some("here")); let kinds: Vec = body[0] .children .iter() @@ -77,13 +81,14 @@ fn a_story_reads_as_ranges_and_content() { TextNode::Content(_) => "Content".into(), TextNode::Table(_) => "Table".into(), TextNode::Item(i) => format!("item {}", i.kind.name()), + TextNode::Anchor(anchor) => format!("anchor {}", anchor.name), TextNode::Other(e) => format!("other {}", e.name), n => format!("{n:?}"), }) .collect(); assert_eq!( kinds, - ["HyperlinkTextSource", "Change", "Content", "Footnote", "Table", "item Rectangle", "other HyperlinkTextDestination", "Content"] + ["HyperlinkTextSource", "Change", "Content", "Footnote", "Table", "item Rectangle", "anchor HyperlinkTextDestination", "Content"] ); } diff --git a/crates/idml/tests/value.rs b/crates/idml/tests/value.rs index 75ef55a087..236c132867 100644 --- a/crates/idml/tests/value.rs +++ b/crates/idml/tests/value.rs @@ -25,6 +25,8 @@ fn transforms_and_points() { assert_eq!(matrix("1 0 0 1 36"), None); assert_eq!(matrix("1 0 0 1 36 72 9"), None); assert_eq!(matrix("1 0 0 1 NaN 0"), None); + assert_eq!(matrix("0 1 x -1 0 0 5"), None, "invalid coefficients cannot shift later values"); + assert_eq!(matrix("1e1000 0 0 1 0 0"), None, "non-finite coefficients are rejected"); assert_eq!(matrix_str(&[1.0, 0.0, 0.0, 1.0, 36.0, -72.5]), "1 0 0 1 36 -72.5"); assert_eq!(point("3 4"), Some((3.0, 4.0))); assert_eq!(point("3 4 5"), Some((3.0, 4.0))); diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 30f7f7046e..2dc9426ac3 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -13,7 +13,7 @@ workspace = true [features] corpus = [] default = [] -avif = ["image/avif"] +avif = ["image/avif", "dep:ravif", "dep:rav1e", "dep:avif-serialize"] heif = ["dep:craft-heif"] [dependencies] @@ -30,8 +30,13 @@ zune-jpeg = "0.5" zune-core = "0.5" jpeg-encoder = "0.6" craft-jpeg = { workspace = true } +craft-metadata = { workspace = true } zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } craft-heif = { workspace = true, optional = true } +ravif = { version = "0.13", default-features = false, optional = true } +rav1e = { version = "0.8", default-features = false, optional = true } +avif-serialize = { version = "0.8", optional = true } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 0fdcd6ae4c..955542c91b 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -250,8 +250,9 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them the image: when the image fits but its extra samples don't, it opens without them and carries `DecodeWarning::ExtraSamplesDropped`. * Every directory is reachable: `tiff_info` lists the main IFD chain and its SubIFDs (tag 330) - with each page's size, kind (page, reduced-resolution copy, mask) and storage, walked with a - seen-set, a depth limit and a 10 000-directory cap; `decode_tiff_page` opens any of them. + with each page's size, kind (page, reduced-resolution copy, mask), storage, InkSet and + ExtraSamples, walked with a seen-set, a depth limit and a 10 000-directory cap; + `decode_tiff_page` opens any of them. `decode` opens the first full-resolution page, like Photoshop (thumbnails are skipped). * Banded decoding: the image is allocated once at its final size and each strip or row of tiles is decoded straight into it, in parallel on native targets, with at most one @@ -304,6 +305,8 @@ also passed to the underlying decoders. A violation returns `CodecError::LimitEx defaults are 262144 px per side, 2^30 pixels and 8 GiB (2 GiB on 32-bit targets such as wasm). PNG also bounds the aggregate decoded text and XMP (UTF-8 keywords and values) by `max_alloc`, including chunks after IDAT. This budget is separate from pixels, not a total process-memory cap. +PNG `cICP` and `cLLI` values are retained as image color metadata. `encode_png_pq` writes linear-light +Rec. 2020 RGB as 16-bit BT.2100 PQ, with measured content-light levels and the required chunks. ## Tests diff --git a/crates/image-codecs/src/cicp.rs b/crates/image-codecs/src/cicp.rs index fc148837cc..290c82bc32 100644 --- a/crates/image-codecs/src/cicp.rs +++ b/crates/image-codecs/src/cicp.rs @@ -27,6 +27,8 @@ impl Cicp { pub const TRANSFER_PQ: u16 = 16; /// ARIB STD-B67 / BT.2100 hybrid log-gamma. pub const TRANSFER_HLG: u16 = 18; + /// Linear light. + pub const TRANSFER_LINEAR: u16 = 8; /// PQ or HLG: samples that [`linearize`] decodes to linear light. pub fn is_hdr(self) -> bool { @@ -41,6 +43,15 @@ pub const HLG_PEAK_NITS: f32 = 1000.0; /// PQ's absolute peak. pub const PQ_PEAK_NITS: f32 = 10_000.0; +/// HDR content light levels in the units used by PNG `cLLI` (0.0001 cd/m² per unit). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ContentLightLevel { + /// Maximum content light level in 0.0001 cd/m² units. + pub max_content_light_level: u32, + /// Maximum frame-average light level in 0.0001 cd/m² units. + pub max_frame_average_light_level: u32, +} + /// BT.2100 HLG inverse OETF: non-linear signal `E'` (0..1) to normalised scene light `E` (0..1). pub fn hlg_inverse_oetf(e: f32) -> f32 { const A: f32 = 0.178_832_77; @@ -74,6 +85,18 @@ pub fn pq_to_linear(e: f32) -> f32 { y * PQ_PEAK_NITS / REFERENCE_WHITE_NITS } +/// BT.2100 PQ signal for linear light relative to [`REFERENCE_WHITE_NITS`]. +pub fn linear_to_pq(linear: f32) -> f32 { + const M1: f32 = 2610.0 / 16384.0; + const M2: f32 = 2523.0 / 4096.0 * 128.0; + const C1: f32 = 3424.0 / 4096.0; + const C2: f32 = 2413.0 / 4096.0 * 32.0; + const C3: f32 = 2392.0 / 4096.0 * 32.0; + let nits = if linear.is_finite() { linear.max(0.0) * REFERENCE_WHITE_NITS } else { 0.0 }; + let y = (nits / PQ_PEAK_NITS).clamp(0.0, 1.0).powf(M1); + ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2) +} + /// Relative luminance weights of the RGB primaries `code` (BT.2020's for anything else, the /// space BT.2100 defines HLG in). fn luma_weights(code: u16) -> [f32; 3] { @@ -104,7 +127,8 @@ pub fn linearize(img: Image, cicp: Cicp) -> Result { let mut out = Image::from_raw(w, h, layout, SampleType::F32, v.iter().flat_map(|x| x.to_ne_bytes()).collect())?; out.meta = img.meta; out.warnings = img.warnings; - out.cicp = Some(cicp); + // CICP describes the samples, not their source encoding. These samples are now linear. + out.cicp = Some(Cicp { transfer: Cicp::TRANSFER_LINEAR, matrix: 0, full_range: true, ..cicp }); Ok(out) } @@ -156,7 +180,10 @@ mod tests { assert!(close(pq_to_linear(1.0), 10_000.0 / 203.0, 0.05)); // 203 cd/m² is PQ signal ≈ 0.5807 (BT.2408). assert!(close(pq_to_linear(0.5807), 1.0, 0.005), "{}", pq_to_linear(0.5807)); + assert!(close(linear_to_pq(1.0), 0.5807, 0.0001)); + assert!(close(pq_to_linear(linear_to_pq(4.0)), 4.0, 0.001)); assert!(pq_to_linear(f32::NAN).is_finite()); + assert!(linear_to_pq(f32::NAN).is_finite()); } #[test] @@ -167,7 +194,15 @@ mod tests { .unwrap() .with_icc(Some(b"encoded-profile".to_vec())); let out = linearize(img, hlg).unwrap(); - assert_eq!((out.sample_type(), out.layout(), out.icc.as_deref(), out.cicp), (SampleType::F32, ChannelLayout::Rgba, None, Some(hlg))); + assert_eq!( + (out.sample_type(), out.layout(), out.icc.as_deref(), out.cicp), + ( + SampleType::F32, + ChannelLayout::Rgba, + None, + Some(Cicp { primaries: hlg.primaries, transfer: Cicp::TRANSFER_LINEAR, matrix: 0, full_range: true }) + ) + ); let v = out.to_normalized(); assert!(v[..3].iter().all(|&x| close(x, 1.0, 0.005)), "{v:?}"); assert!(close(v[3], 1.0, 1e-6) && v[4..7] == [0.0; 3] && close(v[7], 0.5, 1e-3), "{v:?}"); diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index 4c4c22388c..0288ae22b2 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -1,3 +1,4 @@ +pub(crate) mod avif; pub(crate) mod dds; pub(crate) mod dds_bc; pub(crate) mod deep_exr; @@ -10,6 +11,7 @@ pub(crate) mod gif_frames; pub(crate) mod gif_palette; pub(crate) mod heif; pub(crate) mod iff; +pub(crate) mod jp2; pub(crate) mod jpeg; pub(crate) mod jxl; pub(crate) mod pcx; diff --git a/crates/image-codecs/src/codecs/avif.rs b/crates/image-codecs/src/codecs/avif.rs new file mode 100644 index 0000000000..d27112fa18 --- /dev/null +++ b/crates/image-codecs/src/codecs/avif.rs @@ -0,0 +1,211 @@ +//! AVIF encoding helpers (8/16-bit SDR via `ravif` and 10-bit 4:4:4 BT.2020 HDR via `rav1e` + `avif-serialize`). + +use crate::{CodecError, Format, Image}; + +/// Transfer function for [`encode_avif_hdr`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HdrTransfer { + Pq, + Hlg, +} + +/// Absolute luminance of SDR white in an HDR file (ITU-R BT.2408 reference white), cd/m^2. +pub const HDR_REFERENCE_WHITE_NITS: f32 = 203.0; + +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +fn pq_encode(nits: f32) -> f32 { + const M1: f32 = 2610.0 / 16384.0; + const M2: f32 = 2523.0 / 4096.0 * 128.0; + const C1: f32 = 3424.0 / 4096.0; + const C2: f32 = 2413.0 / 4096.0 * 32.0; + const C3: f32 = 2392.0 / 4096.0 * 32.0; + let y = (nits / 10_000.0).clamp(0.0, 1.0).powf(M1); + ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2) +} + +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +fn hlg_signal(rgb: [f32; 3]) -> [f32; 3] { + const A: f32 = 0.17883277; + const B: f32 = 0.28466892; + const C: f32 = 0.559_910_7; + rgb.map(|v| { + let s = if v.is_finite() { v.clamp(0.0, 12.0) / 12.0 } else { 0.0 }; + if s <= 1.0 / 12.0 { (3.0 * s).sqrt() } else { A * (12.0 * s - B).ln() + C } + }) +} + +/// Encode an 8-bit or 16-bit SDR `Image` as AVIF (`4:4:4`, 10-bit AV1) with `quality` (`1..=100`) +/// and `speed` (`1..=10`). +pub fn encode_avif_with_speed(img: &Image, quality: u8, speed: u8) -> Result, CodecError> { + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + { + let mut enc = + ravif::Encoder::new().with_quality(f32::from(quality.clamp(1, 100))).with_speed(speed.clamp(1, 10)).with_bit_depth(ravif::BitDepth::Ten); + let alpha_mode = if img.layout().has_alpha() { ravif::AlphaColorMode::UnassociatedClean } else { ravif::AlphaColorMode::UnassociatedDirty }; + enc = enc.with_alpha_color_mode(alpha_mode); + let w = img.width() as usize; + let h = img.height() as usize; + if let Some(s16) = img.to_u16_samples() { + let ch = img.layout().channels(); + let mut planes = Vec::with_capacity(w * h); + let mut a_plane = if img.layout().has_alpha() { Some(Vec::with_capacity(w * h)) } else { None }; + for px in s16.chunks_exact(ch) { + let (r, g, b, a) = match ch { + 1 => (px[0], px[0], px[0], u16::MAX), + 2 => (px[0], px[0], px[0], px[1]), + 3 => (px[0], px[1], px[2], u16::MAX), + _ => (px[0], px[1], px[2], px[3]), + }; + let (rf, gf, bf) = (f32::from(r) / 65535.0, f32::from(g) / 65535.0, f32::from(b) / 65535.0); + let y = 0.299 * rf + 0.587 * gf + 0.114 * bf; + let cb = (bf - y) * (0.5 / (1.0 - 0.114)) + 0.5; + let cr = (rf - y) * (0.5 / (1.0 - 0.299)) + 0.5; + let q10 = |v: f32| (v * 1023.0).round().clamp(0.0, 1023.0) as u16; + planes.push([q10(y), q10(cb), q10(cr)]); + if let Some(ap) = &mut a_plane { + ap.push(q10(f32::from(a) / 65535.0)); + } + } + let alpha = a_plane.map(Vec::into_iter); + let res = enc + .encode_raw_planes_10_bit(w, h, planes, alpha, ravif::PixelRange::Full, ravif::MatrixCoefficients::BT601) + .map_err(|e| CodecError::encode(Format::Avif, e))?; + return Ok(res.avif_file); + } + let rgba = img.to_rgba8(); + let px: Vec = rgba.as_chunks::<4>().0.iter().map(|c| ravif::RGBA8::new(c[0], c[1], c[2], c[3])).collect(); + let res = enc.encode_rgba(ravif::Img::new(&px[..], w, h)).map_err(|e| CodecError::encode(Format::Avif, e))?; + Ok(res.avif_file) + } + #[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] + { + let _ = (img, quality, speed); + Err(CodecError::unsupported(Format::Avif, "AVIF encoding is not available in this build")) + } +} + +/// Encode linear BT.2020 HDR `rgb` (`width * height * 3` floats, `1.0` = `203` cd/m^2) as +/// 10-bit 4:4:4 BT.2020 PQ or HLG AVIF. +pub fn encode_avif_hdr( + width: u32, + height: u32, + rgb: &[f32], + quality: u8, + speed: u8, + exif: Option<&[u8]>, + transfer: HdrTransfer, +) -> Result, CodecError> { + let (w, h) = (width as usize, height as usize); + let n = w.checked_mul(h).ok_or_else(|| CodecError::encode(Format::Avif, "image too large"))?; + if n == 0 || n.checked_mul(3).is_none_or(|need| rgb.len() < need) { + return Err(CodecError::encode(Format::Avif, "HDR AVIF: sample buffer too short")); + } + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + { + use rav1e::prelude::*; + const K: [f32; 3] = [0.2627, 0.6780, 0.0593]; + let mut max_nits = 0f32; + let mut sum_nits = 0f64; + let planes: Vec<[u16; 3]> = rgb + .as_chunks::<3>() + .0 + .iter() + .take(n) + .map(|c| { + let nits = [c[0], c[1], c[2]].map(|v| (if v.is_finite() { v.max(0.0) } else { 0.0 }) * HDR_REFERENCE_WHITE_NITS); + let y_nits = K[0] * nits[0] + K[1] * nits[1] + K[2] * nits[2]; + max_nits = max_nits.max(nits[0].max(nits[1]).max(nits[2])); + sum_nits += f64::from(y_nits); + let [r, g, b] = match transfer { + HdrTransfer::Pq => nits.map(pq_encode), + HdrTransfer::Hlg => hlg_signal([c[0], c[1], c[2]]), + }; + let y = K[0] * r + K[1] * g + K[2] * b; + let cb = (b - y) / (2.0 * (1.0 - K[2])) + 0.5; + let cr = (r - y) / (2.0 * (1.0 - K[0])) + 0.5; + [y, cb, cr].map(|v| (v * 1023.0).round().clamp(0.0, 1023.0) as u16) + }) + .collect(); + let q = f32::from(quality.clamp(1, 100)) / 100.0; + let x = if q >= 0.82 { + (1.0 - q) * 2.6 + } else if q > 0.25 { + 1.0 - 0.125 - q * 0.5 + } else { + 1.0 - q + }; + let quantizer = (x * 255.0).round() as usize; + let mut ec = EncoderConfig::with_speed_preset(speed.clamp(1, 10)); + ec.width = w; + ec.height = h; + ec.time_base = Rational::new(1, 1); + ec.bit_depth = 10; + ec.chroma_sampling = ChromaSampling::Cs444; + ec.pixel_range = PixelRange::Full; + ec.color_description = Some(ColorDescription { + color_primaries: ColorPrimaries::BT2020, + transfer_characteristics: match transfer { + HdrTransfer::Pq => TransferCharacteristics::SMPTE2084, + HdrTransfer::Hlg => TransferCharacteristics::HLG, + }, + matrix_coefficients: MatrixCoefficients::BT2020NCL, + }); + let cll = (max_nits.ceil().clamp(1.0, 10_000.0) as u16, (sum_nits / n as f64).ceil().clamp(1.0, 10_000.0) as u16); + ec.content_light = + (transfer == HdrTransfer::Pq).then_some(ContentLight { max_content_light_level: cll.0, max_frame_average_light_level: cll.1 }); + ec.still_picture = true; + ec.quantizer = quantizer; + ec.min_quantizer = quantizer.min(255) as u8; + ec.speed_settings.multiref = false; + ec.speed_settings.rdo_lookahead_frames = 1; + ec.speed_settings.scene_detection_mode = SceneDetectionSpeed::None; + let mut ctx: Context = Config::new().with_encoder_config(ec).new_context().map_err(|e| CodecError::encode(Format::Avif, e))?; + let mut frame = ctx.new_frame(); + { + let mut it = planes.iter(); + let mut fp = frame.planes.iter_mut(); + let (Some(py), Some(pu), Some(pv)) = (fp.next(), fp.next(), fp.next()) else { + return Err(CodecError::encode(Format::Avif, "AV1: frame has no planes")); + }; + let (mut sy, mut su, mut sv) = (py.mut_slice(Default::default()), pu.mut_slice(Default::default()), pv.mut_slice(Default::default())); + for ((ry, ru), rv) in sy.rows_iter_mut().zip(su.rows_iter_mut()).zip(sv.rows_iter_mut()).take(h) { + for ((y, u), v) in ry.iter_mut().zip(ru.iter_mut()).zip(rv.iter_mut()).take(w) { + let Some(p) = it.next() else { break }; + (*y, *u, *v) = (p[0], p[1], p[2]); + } + } + } + ctx.send_frame(frame).map_err(|e| CodecError::encode(Format::Avif, e))?; + ctx.flush(); + let mut av1 = Vec::new(); + loop { + match ctx.receive_packet() { + Ok(mut p) if p.frame_type == FrameType::KEY => av1.append(&mut p.data), + Ok(_) => {} + Err(EncoderStatus::Encoded | EncoderStatus::LimitReached) => break, + Err(e) => return Err(CodecError::encode(Format::Avif, e)), + } + } + use avif_serialize::constants as c; + let mut a = avif_serialize::Aviffy::new(); + a.set_matrix_coefficients(c::MatrixCoefficients::Bt2020Ncl) + .set_transfer_characteristics(match transfer { + HdrTransfer::Pq => c::TransferCharacteristics::Smpte2084, + HdrTransfer::Hlg => c::TransferCharacteristics::Hlg, + }) + .set_color_primaries(c::ColorPrimaries::Bt2020) + .set_full_color_range(true); + if transfer == HdrTransfer::Pq { + a.set_content_light_level(cll.0, cll.1); + } + if let Some(exif) = exif { + a.set_exif(exif.to_vec()); + } + Ok(a.to_vec(&av1, None, width, height, 10)) + } + #[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] + { + let _ = (width, height, rgb, quality, speed, exif, transfer); + Err(CodecError::unsupported(Format::Avif, "AVIF encoding is not available in this build")) + } +} diff --git a/crates/image-codecs/src/codecs/jp2.rs b/crates/image-codecs/src/codecs/jp2.rs new file mode 100644 index 0000000000..763ac9c9c9 --- /dev/null +++ b/crates/image-codecs/src/codecs/jp2.rs @@ -0,0 +1,242 @@ +//! JPEG 2000 (JP2 container and raw J2K codestream) decoding via `hayro-jpeg2000`. +//! +//! Decodes within `Limits`, rejecting unsupported JPX multi-layer/composition boxes and +//! checking declared SIZ/tile/palette/channel-definition bounds before pixel allocation. + +use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image as Jp2Image}; + +use crate::Format; +use crate::error::CodecError; +use crate::image::{ChannelLayout, Image, SampleType}; +use crate::options::Limits; + +const F: Format = Format::Jp2; +const JP2_SIGNATURE: &[u8] = b"\0\0\0\x0cjP \r\n\x87\n"; +const MAX_PROFILE: usize = 4 * 1024 * 1024; +const MAX_TILES: u64 = 65_535; +const TILE_COMPONENT_BYTES: u64 = 256; + +/// Boxes at one JP2 nesting level. Invalid lengths stop the walk at that level. +fn boxes(b: &[u8]) -> impl Iterator { + let mut at = 0usize; + std::iter::from_fn(move || { + let header = b.get(at..at.checked_add(8)?)?; + let size = u32::from_be_bytes(header.get(..4)?.try_into().ok()?); + let (length, head) = match size { + 0 => (b.len().checked_sub(at)?, 8usize), + 1 => (usize::try_from(u64::from_be_bytes(b.get(at.checked_add(8)?..at.checked_add(16)?)?.try_into().ok()?)).ok()?, 16usize), + n => (n as usize, 8usize), + }; + if length < head { + return None; + } + let end = at.checked_add(length)?; + let data = b.get(at.checked_add(head)?..end)?; + let ty = header.get(4..8)?; + at = end; + Some((ty, data)) + }) +} + +fn unsupported_jpx_content(bytes: &[u8]) -> bool { + fn association_has_content(data: &[u8], depth: usize) -> bool { + if depth >= 16 { + return true; + } + boxes(data).any(|(ty, child)| { + matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1)) + }) + } + let mut codestreams = 0u8; + for (ty, data) in boxes(bytes) { + match ty { + b"jp2c" => { + codestreams = codestreams.saturating_add(1); + if codestreams > 1 { + return true; + } + } + b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true, + b"asoc" if association_has_content(data, 0) => return true, + _ => {} + } + } + false +} + +fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> { + let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? }; + if stream.get(..4)? != b"\xff\x4f\xff\x51" { + return None; + } + let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize; + let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize; + if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length { + return None; + } + let be32 = |range: std::ops::Range| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes); + let width = be32(8..12)?.checked_sub(be32(16..20)?)?; + let height = be32(12..16)?.checked_sub(be32(20..24)?)?; + let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) { + (Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))), + _ => None, + }; + let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?; + let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?; + Some((count as u64, width, height, across.checked_mul(down)?)) +} + +fn single_header_boxes(bytes: &[u8]) -> bool { + let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h"); + let (Some((_, header)), None) = (headers.next(), headers.next()) else { + return false; + }; + [b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1) +} + +fn channel_definitions(bytes: &[u8]) -> Option { + if bytes.starts_with(b"\xff\x4f") { + return None; + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?; + let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?; + let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n))); + let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else { + return Some(0); + }; + let mut defs: Vec<[u16; 3]> = + entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect(); + defs.sort_unstable(); + let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0); + let colors = defs.len() - usize::from(opacity); + let mut seen = vec![false; colors]; + let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| { + usize::from(channel) == i + && (i >= colors + || (kind == 0 + && usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true)))) + }); + Some(if layout_ok { defs.len() as u64 } else { 0 }) +} + +fn palette_columns(bytes: &[u8], components: u64) -> Result, ()> { + if bytes.starts_with(b"\xff\x4f") { + return Ok(None); + } + let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else { + return Ok(None); + }; + let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else { + return Ok(None); + }; + let columns = palette.get(2).copied().ok_or(())?; + let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?; + if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) { + return Err(()); + } + let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else { + return Ok(Some(u64::from(columns))); + }; + if mapping.len() != usize::from(columns) * 4 { + return Err(()); + } + for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 { + let valid = u64::from(u16::from_be_bytes([c0, c1])) < components + && match kind { + 0 => true, + 1 => column < columns, + _ => false, + }; + if !valid { + return Err(()); + } + } + Ok(Some(u64::from(columns))) +} + +pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { + let malformed = |msg: &str| CodecError::malformed(F, msg); + if bytes.starts_with(JP2_SIGNATURE) && unsupported_jpx_content(bytes) { + return Err(CodecError::unsupported(F, "unsupported color space or JPX content")); + } + if bytes.starts_with(JP2_SIGNATURE) && !single_header_boxes(bytes) { + return Err(malformed("invalid JP2 header boxes")); + } + let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or_else(|| malformed("invalid codestream SIZ"))?; + if tile_count == 0 || tile_count > MAX_TILES { + return Err(malformed("invalid tile count")); + } + let max_alloc = limits.max_alloc; + let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h)); + if declared_w == 0 + || declared_h == 0 + || declared_w > limits.max_width + || declared_h > limits.max_height + || declared_pixels.is_none_or(|n| n > limits.max_pixels) + || declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc) + || tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc) + { + return Err(CodecError::LimitExceeded(format!("dimensions {declared_w}x{declared_h} exceed decode limits"))); + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default(); + if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) { + return Err(CodecError::unsupported(F, "ICC profile exceeds 4 MiB limit")); + } + let palette = palette_columns(bytes, codestream_channels).map_err(|()| malformed("invalid JP2 palette"))?; + let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten()); + if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows) + && u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc + { + return Err(CodecError::LimitExceeded("JP2 palette exceeds max_alloc".into())); + } + let image = Jp2Image::new(bytes, &DecodeSettings::default()).map_err(|e| malformed(&format!("{e:?}")))?; + let (w, h) = (image.width(), image.height()); + let color = image.color_space(); + let (channels, icc) = match color { + ColorSpace::Gray => (1u8, None), + ColorSpace::RGB => (3u8, None), + ColorSpace::CMYK => (4u8, None), + ColorSpace::Icc { num_channels: ch @ (1 | 3 | 4), profile } if profile.len() <= MAX_PROFILE => (*ch, Some(profile.to_vec())), + _ => return Err(CodecError::unsupported(F, "unsupported JPEG 2000 color space")), + }; + let has_alpha = image.has_alpha(); + let stride = u64::from(channels) + u64::from(has_alpha); + if palette.is_some_and(|columns| columns != stride) { + return Err(malformed("JP2 palette columns do not match output channels")); + } + if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) { + return Err(malformed("JP2 channel definitions do not match output channels")); + } + let layout = match (channels, has_alpha) { + (1, false) => ChannelLayout::Gray, + (1, true) => ChannelLayout::GrayA, + (3, false) => ChannelLayout::Rgb, + (3, true) => ChannelLayout::Rgba, + (4, false) => ChannelLayout::Cmyk, + (4, true) => ChannelLayout::CmykA, + _ => return Err(CodecError::unsupported(F, "unsupported channel count")), + }; + limits.check(w, h, layout, SampleType::U8)?; + let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0)); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(|| CodecError::LimitExceeded("pixel count overflow".into()))?; + let size = pixels.checked_mul(stride).ok_or_else(|| CodecError::LimitExceeded("sample count overflow".into()))?; + let plane_bytes = + pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(|| CodecError::LimitExceeded("plane overflow".into()))?; + let scratch_bytes = plane_bytes + .checked_mul(2) + .and_then(|n| n.checked_add(pixels.checked_mul(8)?)) + .ok_or_else(|| CodecError::LimitExceeded("scratch overflow".into()))?; + let working = size + .checked_add(plane_bytes) + .and_then(|n| n.checked_add(scratch_bytes)) + .ok_or_else(|| CodecError::LimitExceeded("memory overflow".into()))?; + if working > max_alloc { + return Err(CodecError::LimitExceeded(format!("working set {working} exceeds max_alloc {max_alloc}"))); + } + let len = usize::try_from(size).map_err(|_| CodecError::LimitExceeded("buffer does not fit in memory".into()))?; + let mut samples = vec![0u8; len]; + image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|e| malformed(&format!("{e:?}")))?; + let mut out = Image::from_raw(w, h, layout, SampleType::U8, samples)?; + out.icc = icc; + Ok(out) +} diff --git a/crates/image-codecs/src/codecs/jpeg.rs b/crates/image-codecs/src/codecs/jpeg.rs index 8e68451ef6..bcd86ad5a9 100644 --- a/crates/image-codecs/src/codecs/jpeg.rs +++ b/crates/image-codecs/src/codecs/jpeg.rs @@ -37,9 +37,53 @@ pub(crate) struct JpegMeta { pub dpi: Option<(f32, f32)>, /// The APP13 Photoshop image resource blocks (`8BIM` ...), segments joined, without the header. pub photoshop: Option>, + /// Whether an Adobe APP14 marker identifies the four-component samples as inverted CMYK. + pub adobe_marker: bool, pub adobe_transform: Option, /// (width, height, components) from the first SOFn. pub frame: Option<(u32, u32, u8)>, + /// [`crate::JpegInfo::held_coefficients`] of the first SOFn and the first scan. + pub held_coefficients: u64, +} + +/// The first frame of `b` as [`crate::JpegInfo`], from its markers alone (see [`crate::jpeg_info`]). +pub(crate) fn info(b: &[u8]) -> Option { + let m = scan_metadata(b); + let (width, height, components) = m.frame?; + let layout = match components { + 1 => ChannelLayout::Gray, + 3 => ChannelLayout::Rgb, + 4 => ChannelLayout::Cmyk, + _ => return None, + }; + let held_coefficients = m.held_coefficients; + Some(crate::JpegInfo { width, height, layout, whole_coefficients: uses_craft_jpeg(b), held_coefficients }) +} + +/// Bytes of the coefficients `zune-jpeg` holds beside its output for a frame it can't turn into +/// rows as it reads (see [`crate::JpegInfo::held_coefficients`]), from the frame's header +/// segment `seg` and the number of components in its first scan: per component, a 64-value +/// block of `i16`s for each of its H × V blocks in every MCU (A.2), the MCUs covering the frame +/// at the largest sampling factors. 0 for any other frame. +fn held_coefficients(marker: u8, seg: &[u8], scan_components: Option) -> u64 { + let &[8, h0, h1, w0, w1, n, ref comps @ ..] = seg else { return 0 }; + // Progressive scans refine every block in turn; a sequential first scan without every + // component leaves its rows unfinished until the scans that bring the others. + let held = match marker { + 0xC2 => true, + 0xC0 | 0xC1 => scan_components.is_some_and(|s| s < n), + _ => false, + }; + if !held { + return 0; + } + let (h, w) = (u64::from(u16::from_be_bytes([h0, h1])), u64::from(u16::from_be_bytes([w0, w1]))); + let factors: Vec<(u64, u64)> = + comps.as_chunks::<3>().0.iter().take(usize::from(n)).map(|&[_, f, _]| (u64::from(f >> 4), u64::from(f & 15))).collect(); + let hmax = factors.iter().map(|f| f.0).max().unwrap_or(1).max(1); + let vmax = factors.iter().map(|f| f.1).max().unwrap_or(1).max(1); + let mcus = w.div_ceil(8 * hmax) * h.div_ceil(8 * vmax); + factors.iter().map(|&(fh, fv)| mcus * fh * fv * 64 * 2).sum() } /// Walk the marker segments up to SOS and collect metadata. @@ -49,6 +93,9 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { // Photoshop splits a large resource block over consecutive APP13 segments. let mut photoshop: Vec = Vec::new(); let mut jfif_dpi = None; + // The first frame header and the number of components in the first scan. + let mut sof: Option<(u8, &[u8])> = None; + let mut scan_components = None; let mut i = 2; while i + 4 <= b.len() { if b[i] != 0xFF { @@ -64,6 +111,7 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { continue; } if marker == 0xDA || marker == 0xD9 { + scan_components = (marker == 0xDA).then(|| b.get(i + 4).copied()).flatten(); break; } let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize; @@ -100,14 +148,19 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { let h = u16::from_be_bytes([seg[1], seg[2]]) as u32; let w = u16::from_be_bytes([seg[3], seg[4]]) as u32; m.frame = Some((w, h, seg[5])); + sof = Some((marker, seg)); } - 0xEE if seg.len() >= 12 && seg.starts_with(b"Adobe") => { - m.adobe_transform = Some(seg[11]); + 0xEE if seg.starts_with(b"Adobe") => { + m.adobe_marker = true; + if seg.len() >= 12 { + m.adobe_transform = Some(seg[11]); + } } _ => {} } i += 2 + len; } + m.held_coefficients = sof.map_or(0, |(marker, seg)| held_coefficients(marker, seg, scan_components)); m.dpi = photoshop_resolution(&photoshop) .or_else(|| m.xmp.as_deref().and_then(xmp_resolution)) .or_else(|| m.exif.as_deref().and_then(exif_resolution)) @@ -264,9 +317,21 @@ fn craft_jpeg_error(e: craft_jpeg::Error) -> CodecError { } } +fn undo_craft_cmyk_inversion_u8(samples: &mut [u8], enabled: bool) { + if enabled { + samples.iter_mut().for_each(|v| *v = 255 - *v); + } +} + +fn undo_craft_cmyk_inversion_u16(samples: &mut [u16], enabled: bool) { + if enabled { + samples.iter_mut().for_each(|v| *v = 65535 - *v); + } +} + /// Decode a file [`uses_craft_jpeg`] routes away from `zune-jpeg`; `damaged` says entropy-coded /// data was cut short or corrupt. -fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option) -> Result<(Image, bool), CodecError> { +fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option, adobe_marker: bool) -> Result<(Image, bool), CodecError> { let mut lim = craft_jpeg::Limits::default(); lim.max_pixels = limits.max_pixels; lim.max_alloc = limits.max_alloc; @@ -277,9 +342,19 @@ fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option) 4 => ChannelLayout::Cmyk, n => return Err(err(format!("{n} components"))), }; + // craft-jpeg returns non-YCC CMYK samples with Adobe's inversion already undone, + // regardless of whether the file actually has an Adobe marker. Unmarked four-component + // streams are also found with direct ink samples, so restore those when using this backend. + let restore_unmarked_cmyk = !adobe_marker && matches!(layout, ChannelLayout::Cmyk); let img = match d.samples { - craft_jpeg::Samples::U8(px) => Image::from_raw(d.width, d.height, layout, SampleType::U8, px)?, - craft_jpeg::Samples::U16(px) => Image::from_u16(d.width, d.height, layout, &px)?, + craft_jpeg::Samples::U8(mut px) => { + undo_craft_cmyk_inversion_u8(&mut px, restore_unmarked_cmyk); + Image::from_raw(d.width, d.height, layout, SampleType::U8, px)? + } + craft_jpeg::Samples::U16(mut px) => { + undo_craft_cmyk_inversion_u16(&mut px, restore_unmarked_cmyk); + Image::from_u16(d.width, d.height, layout, &px)? + } }; Ok((img, d.damaged)) } @@ -311,7 +386,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { return Err(err("the truncated scan is too short for the frame it declares")); } - let (mut img, damaged) = decode_craft_jpeg(bytes, limits, meta.adobe_transform)?; + let (mut img, damaged) = decode_craft_jpeg(bytes, limits, meta.adobe_transform, meta.adobe_marker)?; img.icc = meta.icc; img.meta = Metadata { exif: meta.exif, xmp: meta.xmp, dpi: meta.dpi, photoshop_resources: meta.photoshop, ..Default::default() }; if end == DataEnd::Truncated || damaged { @@ -350,8 +425,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result } px.truncate(expected); match input { - // Adobe-style CMYK is stored inverted (255 = no ink). - ColorSpace::CMYK => px.iter_mut().for_each(|v| *v = 255 - *v), + // Adobe-style CMYK is stored inverted (255 = no ink). Four-component JPEGs without + // APP14 are also encountered with their CMYK samples stored as ink values directly. + ColorSpace::CMYK if meta.adobe_marker => px.iter_mut().for_each(|v| *v = 255 - *v), ColorSpace::YCCK => { for p in px.as_chunks_mut::<4>().0 { let (y, cb, cr) = (p[0] as f32, p[1] as f32 - 128.0, p[2] as f32 - 128.0); @@ -403,6 +479,9 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result| { + let mut b = vec![0xFF, 0xD8, 0xFF, marker, 0, 8 + 3 * factors.len() as u8, precision]; + b.extend_from_slice(&34_200u16.to_be_bytes()); + b.extend_from_slice(&48_000u16.to_be_bytes()); + b.push(factors.len() as u8); + for (i, &f) in factors.iter().enumerate() { + b.extend_from_slice(&[i as u8 + 1, f, 0]); + } + if let Some(n) = scan { + b.extend_from_slice(&[0xFF, 0xDA, 0, 6 + 2 * n, n]); + for c in 1..=n { + b.extend_from_slice(&[c, 0]); + } + b.extend_from_slice(&[0, 63, 0]); + } + b.extend_from_slice(&[0xFF, 0xD9]); + b + }; + let held = |b: &[u8]| info(b).map(|i| i.held_coefficients); + let all_444 = 6_000 * 4_275 * 3 * 128; + // 4:4:4: 6,000 × 4,275 MCUs of one block per component. + assert_eq!(held(&frame(0xC2, 8, &[0x11, 0x11, 0x11], Some(1))), Some(all_444)); + // 4:2:0: 3,000 × 2,138 MCUs of 4 + 1 + 1 blocks. + assert_eq!(held(&frame(0xC2, 8, &[0x22, 0x11, 0x11], None)), Some(3_000 * 2_138 * 6 * 128)); + // Sequential frames whose first scan lacks components hold them all too. + assert_eq!(held(&frame(0xC0, 8, &[0x11, 0x11, 0x11], Some(1))), Some(all_444)); + assert_eq!(held(&frame(0xC1, 8, &[0x11, 0x11, 0x11], Some(2))), Some(all_444)); + // A sequential first scan with every component is read a line of MCUs at a time, and a + // 12-bit progressive frame goes to craft-jpeg: they hold none. + assert_eq!(held(&frame(0xC0, 8, &[0x11, 0x11, 0x11], Some(3))), Some(0)); + assert_eq!(held(&frame(0xC0, 8, &[0x11, 0x11, 0x11], None)), Some(0)); + assert_eq!(held(&frame(0xC2, 12, &[0x11, 0x11, 0x11], None)), Some(0)); + } + /// An APP1 Extended XMP fragment (GUID, total size, offset, data). fn extended_xmp(offset: u32) -> Vec { let mut seg = EXTENDED_XMP_HEADER.to_vec(); @@ -891,6 +1040,47 @@ mod tests { assert!(img.warnings.is_empty()); } + #[test] + fn unmarked_cmyk_restores_direct_ink_polarity_on_craft_backend() { + // craft-jpeg always returns non-YCC four-component samples with Adobe inversion undone. + // The adapter restores direct inks only when no APP14 marker identifies Adobe storage. + let mut u8_samples = [0, 32, 200, 255]; + undo_craft_cmyk_inversion_u8(&mut u8_samples, true); + assert_eq!(u8_samples, [255, 223, 55, 0]); + undo_craft_cmyk_inversion_u8(&mut u8_samples, false); + assert_eq!(u8_samples, [255, 223, 55, 0], "marked samples keep craft-jpeg polarity"); + + let mut u16_samples = [0, 8192, 32768, 65535]; + undo_craft_cmyk_inversion_u16(&mut u16_samples, true); + assert_eq!(u16_samples, [65535, 57343, 32767, 0]); + undo_craft_cmyk_inversion_u16(&mut u16_samples, false); + assert_eq!(u16_samples, [65535, 57343, 32767, 0], "marked samples keep craft-jpeg polarity"); + } + + #[test] + fn twelve_bit_cmyk_without_app14_keeps_direct_ink_polarity_on_craft_backend() { + let image = Image::from_u8(16, 16, ChannelLayout::Cmyk, [10u8, 100, 200, 50].repeat(256)).unwrap(); + let mut marked = crate::encode(&image, Format::Jpeg, &EncodeOptions { jpeg_quality: 95, ..Default::default() }).unwrap(); + let sof = marked.windows(2).position(|pair| pair == [0xFF, 0xC0]).expect("baseline SOF0"); + marked[sof + 1] = 0xC1; + marked[sof + 4] = 12; + assert!(uses_craft_jpeg(&marked), "12-bit SOF1 routes through craft-jpeg"); + + let app14 = b"\xFF\xEE\x00\x0EAdobe"; + let start = marked.windows(app14.len()).position(|part| part == app14).expect("Adobe APP14 marker"); + let mut unmarked = Vec::with_capacity(marked.len() - 16); + unmarked.extend_from_slice(&marked[..start]); + unmarked.extend_from_slice(&marked[start + 16..]); + assert!(uses_craft_jpeg(&unmarked)); + + let adobe = crate::decode(&marked).unwrap().to_u16_samples().unwrap(); + let direct_inks = crate::decode(&unmarked).unwrap().to_u16_samples().unwrap(); + assert_eq!(adobe.len(), direct_inks.len()); + for (&stored_adobe, &ink) in adobe.iter().zip(&direct_inks) { + assert_eq!(ink, 65535 - stored_adobe, "unmarked samples remain direct inks"); + } + } + #[test] fn twelve_bit_jpeg_keeps_its_photoshop_resources() { // An APP13 `8BIM` block (paths, Photoshop settings) right after SOI, as on the zune-jpeg path. diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index cf061f49b8..4ceb754039 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -581,6 +581,10 @@ impl> PngDecodeRows { let info = self.reader.info(); let icc = info.icc_profile.as_ref().map(|c| c.to_vec()); let mut meta = Metadata { exif: info.exif_metadata.as_ref().map(|c| c.to_vec()), ..Default::default() }; + meta.content_light_level = info.content_light_level.map(|light| crate::cicp::ContentLightLevel { + max_content_light_level: light.max_content_light_level, + max_frame_average_light_level: light.max_frame_average_light_level, + }); if let Some(d) = info.pixel_dims && d.unit == png::Unit::Meter && d.xppu > 0 @@ -597,7 +601,13 @@ impl> PngDecodeRows { warnings.push(DecodeWarning::MoreFrames { total: u32::try_from(self.images).ok() }); } let orientation = meta.exif.as_deref().map_or(1, crate::orientation::exif_orientation); - PngExtras { icc, meta, warnings, orientation } + let cicp = info.coding_independent_code_points.map(|c| crate::cicp::Cicp { + primaries: u16::from(c.color_primaries), + transfer: u16::from(c.transfer_function), + matrix: u16::from(c.matrix_coefficients), + full_range: c.is_video_full_range_image, + }); + PngExtras { icc, cicp, meta, warnings, orientation } } /// The image itself, with what the metadata scan accepted. @@ -606,6 +616,7 @@ impl> PngDecodeRows { let mut img = Image::from_raw(self.width, height, self.layout, self.sample, std::mem::take(&mut self.buf))?; let extras = self.extras(); img.icc = extras.icc; + img.cicp = extras.cicp; img.meta = extras.meta; img.warnings = extras.warnings; Ok(img) @@ -624,6 +635,8 @@ fn to_native_endian(samples: &mut [u8]) { /// they are complete only once the pixels have been read. pub struct PngExtras { pub icc: Option>, + /// The PNG `cICP` colour description, if present. + pub cicp: Option, pub meta: Metadata, pub warnings: Vec, /// The EXIF orientation (1-8) the pixels are stored in; 1 when there is none. @@ -1050,29 +1063,114 @@ impl Write for FallibleOutput<'_> { pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { let img = src.converted(plan.layout, plan.sample); let (w, h) = img.dimensions(); - let bpp = img.layout().channels() * img.sample_type().bytes(); // Big-endian sample bytes. let mut data = std::borrow::Cow::Borrowed(img.data()); if img.sample_type() == SampleType::U16 { to_big_endian(data.to_mut()); } + encode_data( + RawPng { + width: w, + height: h, + layout: img.layout(), + sample: img.sample_type(), + icc: img.icc.as_ref(), + cicp: img.cicp, + meta: &img.meta, + data: &data, + }, + opts, + ) +} + +struct RawPng<'a> { + width: u32, + height: u32, + layout: ChannelLayout, + sample: SampleType, + icc: Option<&'a Vec>, + cicp: Option, + meta: &'a Metadata, + data: &'a [u8], +} + +fn encode_data(raw: RawPng<'_>, opts: &EncodeOptions) -> Result, CodecError> { + let RawPng { width: w, height: h, layout, sample, icc, cicp, meta, data } = raw; + let bpp = layout.channels() * sample.bytes(); let mut out = Vec::new(); { let mut output = FallibleOutput(&mut out); - let mut writer = start(&mut output, (w, h), (img.layout(), img.sample_type()), img.icc.as_ref(), &img.meta, opts)?; + let mut writer = start(&mut output, (w, h), (layout, sample), icc, cicp, meta, opts)?; if opts.png_interlaced { - let idat = adam7_idat(&data, w as usize, h as usize, bpp, opts.png_compression)?; + let idat = adam7_idat(data, w as usize, h as usize, bpp, opts.png_compression)?; write_idat(&mut writer, &idat, MAX_IDAT)?; - } else if let Some(idat) = parallel_idat(&data, w as usize, h as usize, bpp, opts.png_compression) { + } else if let Some(idat) = parallel_idat(data, w as usize, h as usize, bpp, opts.png_compression) { write_idat(&mut writer, &idat, MAX_IDAT)?; } else { - writer.write_image_data(&data).map_err(|e| CodecError::encode(F, e))?; + writer.write_image_data(data).map_err(|e| CodecError::encode(F, e))?; } writer.finish().map_err(|e| CodecError::encode(F, e))?; } Ok(out) } +/// Encodes linear-light Rec. 2020 RGB as 16-bit PNG with BT.2100 PQ (`cICP`) and measured +/// content-light levels (`cLLI`). Input samples are relative to 203 cd/m² diffuse white, as in +/// [`crate::cicp::linearize`]. Negative and non-finite values become black; values above 10,000 +/// cd/m² are clipped to the PQ signal range. EXIF, XMP, and resolution metadata follow `opts`. +pub fn encode_pq(src: &Image, opts: &EncodeOptions) -> Result, CodecError> { + if src.layout() != ChannelLayout::Rgb || src.sample_type() != SampleType::F32 { + return Err(CodecError::encode(F, "PQ PNG input must be linear-light F32 RGB")); + } + let (width, height) = src.dimensions(); + if width == 0 || height == 0 { + return Err(CodecError::InvalidImage("cannot encode an empty image".into())); + } + let pixels = usize::try_from(u64::from(width) * u64::from(height)).map_err(|_| CodecError::encode(F, "image is too large"))?; + let samples = pixels.checked_mul(3).ok_or_else(|| CodecError::encode(F, "image is too large"))?; + let bytes = samples.checked_mul(2).ok_or_else(|| CodecError::encode(F, "image is too large"))?; + if src.data().len() != samples.checked_mul(4).ok_or_else(|| CodecError::encode(F, "image is too large"))? { + return Err(CodecError::encode(F, "RGB buffer length does not match the image dimensions")); + } + let mut output = Vec::new(); + output.try_reserve_exact(bytes).map_err(|_| CodecError::encode(F, "not enough memory for PQ samples"))?; + let mut max_nits = 0.0f32; + let mut sum_luma = 0.0f64; + for rgb in src.data().as_chunks::<12>().0 { + let read = |at| -> Result { + let bytes = rgb.get(at..at + 4).ok_or_else(|| CodecError::encode(F, "RGB buffer is truncated"))?; + let bytes: [u8; 4] = bytes.try_into().map_err(|_| CodecError::encode(F, "RGB sample is truncated"))?; + Ok(f32::from_ne_bytes(bytes)) + }; + let values = [read(0)?, read(4)?, read(8)?]; + let nits = values.map(|v| if v.is_finite() { (v.max(0.0) * crate::cicp::REFERENCE_WHITE_NITS).min(crate::cicp::PQ_PEAK_NITS) } else { 0.0 }); + max_nits = max_nits.max(nits[0]).max(nits[1]).max(nits[2]); + // CTA-861.3-A defines MaxFALL as the average of each pixel's maximum linear RGB channel. + sum_luma += f64::from(nits[0].max(nits[1]).max(nits[2])); + for value in nits { + let encoded = crate::cicp::linear_to_pq(value / crate::cicp::REFERENCE_WHITE_NITS); + output.extend_from_slice(&((encoded * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes()); + } + } + let max_cll = ((max_nits.ceil().clamp(1.0, crate::cicp::PQ_PEAK_NITS)) as u32).saturating_mul(10_000); + let max_fall = (((sum_luma / pixels as f64).ceil().clamp(1.0, f64::from(crate::cicp::PQ_PEAK_NITS))) as u32).saturating_mul(10_000); + let mut meta = src.meta.clone(); + meta.content_light_level = Some(crate::cicp::ContentLightLevel { max_content_light_level: max_cll, max_frame_average_light_level: max_fall }); + encode_data( + RawPng { + width, + height, + layout: ChannelLayout::Rgb, + sample: SampleType::U16, + icc: None, + cicp: Some(crate::cicp::Cicp { primaries: 9, transfer: crate::cicp::Cicp::TRANSFER_PQ, matrix: 0, full_range: true }), + meta: &meta, + data: &output, + }, + opts, + ) +} + /// 16-bit native-endian samples to PNG's big-endian order, in place. fn to_big_endian(data: &mut [u8]) { for c in data.as_chunks_mut::<2>().0 { @@ -1088,6 +1186,7 @@ fn start( (w, h): (u32, u32), (layout, sample): (ChannelLayout, SampleType), icc: Option<&Vec>, + cicp: Option, meta: &Metadata, opts: &EncodeOptions, ) -> Result, CodecError> { @@ -1154,6 +1253,22 @@ fn start( } } let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?; + if let Some(cicp) = cicp { + let point = |value: u16, name: &str| { + u8::try_from(value).map_err(|_| CodecError::encode(F, format!("CICP {name} value {value} does not fit in a byte"))) + }; + // PNG stores RGB samples, so cICP's matrix coefficients byte is always zero. + let cicp_bytes = [point(cicp.primaries, "primaries")?, point(cicp.transfer, "transfer")?, 0, u8::from(cicp.full_range)]; + writer.write_chunk(png::chunk::cICP, &cicp_bytes).map_err(|e| CodecError::encode(F, e))?; + } + if opts.embed_metadata + && let Some(light) = meta.content_light_level + { + let mut bytes = [0; 8]; + bytes[..4].copy_from_slice(&light.max_content_light_level.to_be_bytes()); + bytes[4..].copy_from_slice(&light.max_frame_average_light_level.to_be_bytes()); + writer.write_chunk(png::chunk::cLLI, &bytes).map_err(|e| CodecError::encode(F, e))?; + } if let Some(stereo) = opts.png_stereo { // Ancillary chunk before IDAT, as the spec recommends for `sTER`. writer.write_chunk(png::chunk::ChunkType(*b"sTER"), &[stereo.mode()]).map_err(|e| CodecError::encode(F, e))?; @@ -1208,7 +1323,7 @@ impl PngRows { return Err(CodecError::InvalidImage("cannot encode an empty image".into())); } let plan = crate::fidelity::plan(first, F, opts); - let writer = start(out, (width, height), (plan.layout, plan.sample), first.icc.as_ref(), &first.meta, opts)?; + let writer = start(out, (width, height), (plan.layout, plan.sample), first.icc.as_ref(), first.cicp, &first.meta, opts)?; Ok(Self { writer, plan, @@ -1599,6 +1714,83 @@ pub fn encode_indexed( Ok(out) } +#[cfg(test)] +mod hdr_tests { + use super::*; + + #[test] + fn generic_png_roundtrip_keeps_cicp_and_content_light_level() { + let mut image = Image::from_raw(1, 1, ChannelLayout::Rgb, SampleType::U16, vec![0, 0, 0, 0, 0, 0]).unwrap(); + image.cicp = Some(crate::cicp::Cicp { primaries: 9, transfer: 16, matrix: 9, full_range: true }); + image.meta.content_light_level = + Some(crate::cicp::ContentLightLevel { max_content_light_level: 2_030_000, max_frame_average_light_level: 1_250_000 }); + + let encoded = encode(&image, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U16 }, &EncodeOptions::default()).unwrap(); + let decoded = decode(&encoded, &Limits::default()).unwrap(); + assert_eq!(decoded.cicp, Some(crate::cicp::Cicp { matrix: 0, ..image.cicp.unwrap() })); + assert_eq!(decoded.meta.content_light_level, image.meta.content_light_level); + } + + #[test] + fn generic_png_keeps_cicp_alongside_icc() { + let mut image = Image::from_raw(1, 1, ChannelLayout::Rgb, SampleType::U16, vec![0, 0, 0, 0, 0, 0]).unwrap(); + image.cicp = Some(crate::cicp::Cicp { primaries: 9, transfer: 16, matrix: 0, full_range: true }); + image.icc = Some(b"synthetic ICC profile".to_vec()); + + let encoded = encode(&image, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U16 }, &EncodeOptions::default()).unwrap(); + let decoded = decode(&encoded, &Limits::default()).unwrap(); + assert_eq!(decoded.cicp, image.cicp); + assert_eq!(decoded.icc, image.icc); + } + + #[test] + fn linearized_pq_pixels_are_tagged_as_linear_in_generic_png() { + let cicp = crate::cicp::Cicp { primaries: 9, transfer: crate::cicp::Cicp::TRANSFER_PQ, matrix: 0, full_range: true }; + let encoded_white = (0.5807f32 * 65535.0).round() as u16; + let mut image = Image::from_u16(1, 1, ChannelLayout::Rgb, &[encoded_white; 3]).unwrap(); + image.cicp = Some(cicp); + let linear = crate::cicp::linearize(image, cicp).unwrap(); + let png = encode(&linear, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U16 }, &EncodeOptions::default()).unwrap(); + let decoded = decode(&png, &Limits::default()).unwrap(); + assert_eq!(decoded.cicp.unwrap().transfer, crate::cicp::Cicp::TRANSFER_LINEAR); + assert!(decoded.to_normalized().iter().all(|&v| (v - 1.0).abs() < 0.001)); + } + + #[test] + fn pq_png_writes_rec2020_codes_and_measured_light_levels() { + let image = Image::from_f32(1, 1, ChannelLayout::Rgb, &[1.0, 1.0, 1.0]).unwrap(); + let encoded = encode_pq(&image, &EncodeOptions::default()).unwrap(); + let mut reader = png::Decoder::new(Cursor::new(&encoded)).read_info().unwrap(); + let info = reader.info(); + let cicp = info.coding_independent_code_points.unwrap(); + assert_eq!((cicp.color_primaries, cicp.transfer_function, cicp.matrix_coefficients, cicp.is_video_full_range_image), (9, 16, 0, true)); + let light = info.content_light_level.unwrap(); + assert_eq!((light.max_content_light_level, light.max_frame_average_light_level), (2_030_000, 2_030_000)); + let mut bytes = vec![0; reader.output_buffer_size().unwrap()]; + let frame = reader.next_frame(&mut bytes).unwrap(); + let rgb = bytes.get(..frame.buffer_size()).unwrap().as_chunks::<2>().0.iter().map(|v| u16::from_be_bytes(*v)).collect::>(); + assert_eq!(rgb.len(), 3); + for sample in rgb { + assert!((f32::from(sample) / 65535.0 - 0.5807).abs() < 0.001); + } + } + + #[test] + fn pq_png_maxfall_uses_highest_channel_for_saturated_pixels() { + let image = Image::from_f32(2, 1, ChannelLayout::Rgb, &[1.0, 0.0, 0.0, 0.0, 0.0, 1.0]).unwrap(); + let encoded = encode_pq(&image, &EncodeOptions::default()).unwrap(); + let reader = png::Decoder::new(Cursor::new(encoded)).read_info().unwrap(); + let light = reader.info().content_light_level.unwrap(); + assert_eq!((light.max_content_light_level, light.max_frame_average_light_level), (2_030_000, 2_030_000)); + } + + #[test] + fn pq_png_rejects_empty_images() { + let image = Image::from_f32(0, 1, ChannelLayout::Rgb, &[]).unwrap(); + assert!(encode_pq(&image, &EncodeOptions::default()).is_err()); + } +} + #[cfg(test)] mod stereo_tests { use super::*; @@ -2030,7 +2222,8 @@ mod streamed_tests { let whole = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap(); let (_, zlib, _) = split(&whole); let mut out = Vec::new(); - let mut w = start(&mut out, (64, 40), (ChannelLayout::Rgb, SampleType::U8), None, &Metadata::default(), &EncodeOptions::default()).unwrap(); + let mut w = + start(&mut out, (64, 40), (ChannelLayout::Rgb, SampleType::U8), None, None, &Metadata::default(), &EncodeOptions::default()).unwrap(); write_idat(&mut w, &zlib, 100).unwrap(); w.finish().unwrap(); let (_, joined, count) = split(&out); diff --git a/crates/image-codecs/src/codecs/tiff_ifd.rs b/crates/image-codecs/src/codecs/tiff_ifd.rs index 8fac8c6b42..0783cbdf3d 100644 --- a/crates/image-codecs/src/codecs/tiff_ifd.rs +++ b/crates/image-codecs/src/codecs/tiff_ifd.rs @@ -41,6 +41,7 @@ pub(crate) const TAG_TILE_WIDTH: u16 = 322; pub(crate) const TAG_TILE_LENGTH: u16 = 323; pub(crate) const TAG_TILE_OFFSETS: u16 = 324; pub(crate) const TAG_SUB_IFDS: u16 = 330; +pub(crate) const TAG_INK_SET: u16 = 332; pub(crate) const TAG_EXTRA_SAMPLES: u16 = 338; pub(crate) const TAG_SAMPLE_FORMAT: u16 = 339; @@ -349,6 +350,56 @@ pub struct TiffPage { pub tiled: bool, /// `PlanarConfiguration` 2: each sample in its own plane. pub planar: bool, + /// TIFF `InkSet` (tag 332), when present. Only meaningful for photometric 5 (Separated). + pub ink_set: Option, + /// TIFF `ExtraSamples` (tag 338), one per extra sample. Empty when the tag is absent or + /// unreadable. + pub extra_samples: Vec, +} + +/// The TIFF `InkSet` tag (332) of a separated image. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InkSet { + /// 1: the samples are cyan, magenta, yellow and black. + Cmyk, + /// 2: the samples are the inks listed in the `InkNames` tag. + InkNames, + /// Any other value; TIFF 6.0 defines only 1 and 2. + Invalid(u16), +} + +impl InkSet { + fn from_tag(value: u16) -> Self { + match value { + 1 => Self::Cmyk, + 2 => Self::InkNames, + v => Self::Invalid(v), + } + } +} + +/// What one extra sample of a TIFF holds, from the `ExtraSamples` tag (338). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExtraSampleKind { + /// 0: unspecified data. + Unspecified, + /// 1: associated (premultiplied) alpha. + AssociatedAlpha, + /// 2: unassociated (straight) alpha. + UnassociatedAlpha, + /// Any other value; TIFF 6.0 defines only 0, 1 and 2. + Invalid(u16), +} + +impl ExtraSampleKind { + fn from_tag(value: u16) -> Self { + match value { + 0 => Self::Unspecified, + 1 => Self::AssociatedAlpha, + 2 => Self::UnassociatedAlpha, + v => Self::Invalid(v), + } + } } /// The directory structure of a TIFF file: its byte order, BigTIFF or not, and every image @@ -405,6 +456,14 @@ fn describe(f: &File<'_>, ifd: &Ifd, parent: Option) -> TiffPage { compression: u16_of(TAG_COMPRESSION, 1), tiled: ifd.get(TAG_TILE_OFFSETS).is_some(), planar: f.tag_uint(ifd, TAG_PLANAR) == Some(2), + ink_set: f.tag_uint(ifd, TAG_INK_SET).map(|v| InkSet::from_tag(u16::try_from(v).unwrap_or(u16::MAX))), + // Capped at the sample count: a file cannot have more extra samples than samples. + extra_samples: f + .tag_uints(ifd, TAG_EXTRA_SAMPLES, u64::from(u16_of(TAG_SAMPLES, 1))) + .unwrap_or_default() + .into_iter() + .map(|v| ExtraSampleKind::from_tag(u16::try_from(v).unwrap_or(u16::MAX))) + .collect(), } } diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index c77f9a09f6..ecaf945cd8 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -42,6 +42,8 @@ pub enum Format { Dicom, /// Amiga IFF/ILBM (`FORM ... ILBM`): planar bitplanes with a palette or 24-bit RGB. Iff, + /// JPEG 2000 (JP2 container or raw J2K codestream): read-only; see [`ASYMMETRIC_EXCEPTIONS`]. + Jp2, } /// What a format can hold **and** what this crate reads/writes for it. @@ -98,6 +100,7 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ writing needs an HEVC encoder, and the mature ones (x265, libheif) are C, so write stays \ unsupported. Without the feature HEIF is detected but neither read nor written.", ), + (Format::Jp2, "JPEG 2000 decode uses hayro-jpeg2000 (pure Rust); writing JPEG 2000 is not provided."), ]; use ChannelLayout as L; @@ -110,9 +113,10 @@ const TIFF_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L:: impl Format { /// Every format known to the crate (enabled or not). - pub const ALL: [Format; 23] = [ + pub const ALL: [Format; 24] = [ Format::Png, Format::Jpeg, + Format::Jp2, Format::Jxl, Format::Tiff, Format::WebP, @@ -171,6 +175,7 @@ impl Format { Format::Cineon => "Cineon", Format::Dicom => "DICOM", Format::Iff => "Amiga IFF", + Format::Jp2 => "JPEG 2000", } } @@ -201,6 +206,7 @@ impl Format { Format::Cineon => &["cin"], Format::Dicom => &["dcm", "dicom", "dc3"], Format::Iff => &["iff", "lbm", "ilbm"], + Format::Jp2 => &["jp2", "j2k", "j2c", "jpf", "jpx"], } } @@ -229,6 +235,7 @@ impl Format { Format::Cineon => "image/x-cin", Format::Dicom => "application/dicom", Format::Iff => "image/x-iff", + Format::Jp2 => "image/jp2", } } @@ -303,6 +310,7 @@ pub fn caps(format: Format) -> FormatCaps { Format::Cineon => FormatCaps { depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Dicom => FormatCaps { read: true, write: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Iff => FormatCaps { depths: &[S::U8], layouts: &[L::Rgb, L::Rgba], alpha: true, ..base }, + Format::Jp2 => FormatCaps { read: true, write: false, layouts: &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA], icc: true, ..base }, } } @@ -320,6 +328,10 @@ pub fn detect(bytes: &[u8]) -> Option { if b.starts_with(&[0xFF, 0x0A]) || b.starts_with(b"\0\0\0\x0cJXL \r\n\x87\n") { return Some(Format::Jxl); } + // JPEG 2000 container signature box or raw J2K codestream (SOC + SIZ). + if b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") || b.starts_with(b"\xff\x4f\xff\x51") { + return Some(Format::Jp2); + } if b.starts_with(b"II*\0") || b.starts_with(b"MM\0*") || b.starts_with(b"II+\0") || b.starts_with(b"MM\0+") { return Some(Format::Tiff); } diff --git a/crates/image-codecs/src/image.rs b/crates/image-codecs/src/image.rs index dc555c42ba..a6f417c726 100644 --- a/crates/image-codecs/src/image.rs +++ b/crates/image-codecs/src/image.rs @@ -142,6 +142,9 @@ pub struct Metadata { pub dpi: Option<(f32, f32)>, /// Free-form key/value text (PNG tEXt/iTXt, TIFF ASCII tags). pub text: Vec<(String, String)>, + /// HDR content light levels carried by formats such as PNG `cLLI`, in units of + /// 0.0001 cd/m² per value. A zero value means that level is unknown. + pub content_light_level: Option, /// Photoshop image resources (`8BIM` resource blocks): TIFF tag 34377. Kept opaque here; /// `photocraft-io` reads and writes them through `photocraft-psd`. pub photoshop_resources: Option>, @@ -174,6 +177,7 @@ impl Metadata { && self.xmp.is_none() && self.dpi.is_none() && self.text.is_empty() + && self.content_light_level.is_none() && self.photoshop_resources.is_none() && self.photoshop_layers.is_none() && self.extra_samples.is_empty() diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index e02c438ec8..61109faa1e 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -32,16 +32,18 @@ pub mod source_settings; pub mod web; pub use crate::allocation::probe_allocation_size; pub use crate::cicp::Cicp; +pub use crate::cicp::ContentLightLevel; +pub use crate::codecs::avif::{HDR_REFERENCE_WHITE_NITS, HdrTransfer, encode_avif_hdr, encode_avif_with_speed}; pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color}; pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES}; pub use crate::codecs::png::{ - PngDecodeRows, PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, SharedBytes, encode_indexed as encode_png_indexed, palette as png_palette, - stereo as png_stereo, + PngDecodeRows, PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, SharedBytes, encode_indexed as encode_png_indexed, + encode_pq as encode_png_pq, palette as png_palette, stereo as png_stereo, }; pub use crate::codecs::tiff::{ PhotoshopTags as TiffPhotoshopTags, TiffBands, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian, }; -pub use crate::codecs::tiff_ifd::{TiffInfo, TiffPage, TiffPageKind}; +pub use crate::codecs::tiff_ifd::{ExtraSampleKind, InkSet, TiffInfo, TiffPage, TiffPageKind}; pub use crate::error::CodecError; pub use crate::exif_color::{EXIF_COLOR_SPACE_SRGB, exif_color_space}; pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with}; @@ -60,7 +62,7 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_ pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; pub use half::f16; -use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jpeg, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; +use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -101,6 +103,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Iff => iff::decode(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), + Format::Jp2 => jp2::decode(bytes, l), Format::Jxl => Err(CodecError::unsupported(format, "JPEG XL reading is not yet available; export is supported")), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l), }?; @@ -211,6 +214,29 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { Ok(if (5..=8).contains(&o) { (h, w) } else { (w, h) }) } +/// A JPEG's frame as its header declares it, read without decoding pixels: the stored size, the +/// layout [`decode`] returns, whether [`decode`] hands the file to its whole-coefficient +/// decoder (arithmetic-coded, lossless or 12-bit frames), whose working set is several times the +/// decoded image, and the coefficients it holds beside its output when it can't decode row by row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct JpegInfo { + pub width: u32, + pub height: u32, + pub layout: ChannelLayout, + pub whole_coefficients: bool, + /// Bytes of DCT coefficients [`decode`] holds at once beside its output when it can't turn + /// the frame into rows as it reads: an 8-bit progressive frame (SOF2), whose scans refine + /// every block in turn, or an 8-bit Huffman one (SOF0, SOF1) whose first scan lacks some of + /// its components. Every block of every component at its own sampling, 64 16-bit values + /// each; 0 for the frames it decodes a line of MCUs at a time. + pub held_coefficients: u64, +} + +/// [`JpegInfo`] of `bytes`; `None` without a readable frame of 1, 3 or 4 components. +pub fn jpeg_info(bytes: &[u8]) -> Option { + jpeg::info(bytes) +} + /// The colour table of a GIF's first frame (its Local Color Table, else the Global one) and the /// entry its Graphic Control Extension makes transparent, read without decoding pixels. pub fn gif_palette(bytes: &[u8]) -> Option<(Vec<[u8; 3]>, Option)> { @@ -422,6 +448,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result iff::encode(image, plan), Format::OpenExr => exr::encode(image, plan, opts), Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")), + Format::Jp2 => Err(CodecError::unsupported(format, "JPEG 2000 is import-only; save as PNG or TIFF instead")), Format::Jxl => jxl::encode(image, plan), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => { via_image::encode(format, image, plan, opts) diff --git a/crates/image-codecs/src/options.rs b/crates/image-codecs/src/options.rs index 9674b4edfb..ed96b87332 100644 --- a/crates/image-codecs/src/options.rs +++ b/crates/image-codecs/src/options.rs @@ -299,6 +299,9 @@ pub struct EncodeOptions { pub jpeg_chroma_subsampling: bool, /// JPEG scan layout (baseline, baseline optimized or progressive). pub jpeg_format: JpegFormat, + /// Optional number of progressive JPEG scans (typically 3..=5). Ignored unless + /// `jpeg_format` is [`JpegFormat::Progressive`]. + pub jpeg_progressive_scans: Option, pub png_compression: PngCompression, /// Write Adam7-interlaced PNG. pub png_interlaced: bool, @@ -336,6 +339,7 @@ impl Default for EncodeOptions { jpeg_quality: 90, jpeg_chroma_subsampling: true, jpeg_format: JpegFormat::Baseline, + jpeg_progressive_scans: None, png_compression: PngCompression::Default, png_interlaced: false, png_stereo: None, diff --git a/crates/image-codecs/src/resolution.rs b/crates/image-codecs/src/resolution.rs index a787cacbc3..6dbc9d5eea 100644 --- a/crates/image-codecs/src/resolution.rs +++ b/crates/image-codecs/src/resolution.rs @@ -1,575 +1,57 @@ -//! Image resolution (pixels per inch) recorded in metadata blocks: EXIF / TIFF IFD0 -//! (XResolution 282, YResolution 283, ResolutionUnit 296), XMP (`tiff:XResolution`, -//! `tiff:YResolution`, `tiff:ResolutionUnit`) and Photoshop's image resource -//! ResolutionInfo (`8BIM` resource 0x03ED); reading them, and rewriting the EXIF and XMP -//! copies on export so they agree with the resolution the file is written at. +//! Resolution metadata edits delegated to the shared [`craft_metadata::edit`] implementation. //! -//! Implemented from TIFF 6.0 (section 8, "Baseline fields": XResolution / YResolution are -//! RATIONAL, ResolutionUnit is SHORT, 1 = no absolute unit, 2 = inch, 3 = centimetre, -//! default 2), EXIF 2.3 (same tags in the 0th IFD, same default) and the Adobe Photoshop File -//! Formats Specification (ResolutionInfo: Fixed 16.16 hRes in pixels per inch, then the -//! display units; the vertical resolution likewise). -//! -//! **Precedence** when a file carries several, as Photoshop resolves them: Photoshop's own -//! ResolutionInfo, then the XMP `tiff:` properties, then EXIF, and only then the format's own -//! density field when it is the generic JFIF one (see the JPEG decoder). JFIF density is last -//! because cameras record the real resolution in EXIF while many tools and libraries write a -//! default JFIF density of 72 (or a bare aspect ratio) without knowing it; Photoshop shows a -//! camera JPEG at its EXIF resolution whatever its JFIF header says. Formats whose own field is -//! written deliberately (PNG `pHYs`, TIFF tags) keep it first; the metadata blocks only fill in -//! when it is missing. -//! -//! Everything read here is untrusted: offsets and counts are bounds-checked, both byte orders -//! and BigTIFF-style EXIF are handled, and anything malformed reads as "no resolution" rather -//! than as a wrong one. +//! Image codecs keep these wrappers so their public API and format-specific callers remain +//! stable while EXIF, XMP, and Photoshop ResolutionInfo parsing and editing live in one library. use std::borrow::Cow; -use crate::orientation::{Order, ifd0_entries, tiff_body, upright_exif, upright_xmp}; - -const TAG_X_RESOLUTION: u16 = 282; -const TAG_Y_RESOLUTION: u16 = 283; -const TAG_RESOLUTION_UNIT: u16 = 296; -const TYPE_SHORT: u16 = 3; -const TYPE_RATIONAL: u16 = 5; -const CM_PER_INCH: f64 = 2.54; -/// Photoshop's ResolutionInfo image resource. -const RESOLUTION_INFO: u16 = 0x03ED; -/// Resolutions above this (pixels per inch) are treated as damage, not data. -const MAX_PPI: f64 = 1_000_000.0; -/// Two resolutions this close (pixels per inch) are the same. -const SAME_PPI: f64 = 1e-3; - -/// A usable resolution pair, or `None`. -fn ppi_pair(x: f64, y: f64) -> Option<(f32, f32)> { - let ok = |v: f64| v.is_finite() && v > 0.0 && v <= MAX_PPI; - (ok(x) && ok(y)).then_some((x as f32, y as f32)) -} - -fn same(a: (f32, f32), b: (f32, f32)) -> bool { - (f64::from(a.0) - f64::from(b.0)).abs() < SAME_PPI && (f64::from(a.1) - f64::from(b.1)).abs() < SAME_PPI -} - -/// `ppi` as a TIFF RATIONAL: a whole number over 1 when it is one, else over 1000. -fn rational(ppi: f32) -> (u32, u32) { - let p = f64::from(ppi); - if (p - p.round()).abs() < SAME_PPI { (p.round() as u32, 1) } else { ((p * 1000.0).round() as u32, 1000) } -} - -/// One of the three resolution entries of IFD0. -#[derive(Clone, Copy)] -struct Field { - /// Offset of the 12- (BigTIFF: 20-) byte entry. - entry: usize, - tag: u16, - ty: u16, - count: u64, - /// Where the value bytes are, when the type is one we read and they lie inside the block. - value: Option, -} - -impl Field { - fn short(&self, order: Order, b: &[u8]) -> Option { - (self.ty == TYPE_SHORT && self.count == 1).then_some(())?; - order.u16(b, self.value?) - } - - fn rational(&self, order: Order, b: &[u8]) -> Option { - (self.ty == TYPE_RATIONAL && self.count == 1).then_some(())?; - let at = self.value?; - let (n, d) = (order.u32(b, at)?, order.u32(b, at.checked_add(4)?)?); - (d != 0).then(|| f64::from(n) / f64::from(d)) - } -} - -/// IFD0's resolution entries. -struct Ifd0 { - order: Order, - big: bool, - first: usize, - count: usize, - entry_bytes: usize, - fields: Vec, -} - -impl Ifd0 { - fn parse(b: &[u8]) -> Option { - let (order, first, count, entry_bytes, big) = ifd0_entries(b)?; - let mut fields = Vec::new(); - for i in 0..count { - let e = first.checked_add(i.checked_mul(entry_bytes)?)?; - let tag = order.u16(b, e)?; - if !matches!(tag, TAG_X_RESOLUTION | TAG_Y_RESOLUTION | TAG_RESOLUTION_UNIT) { - continue; - } - let ty = order.u16(b, e.checked_add(2)?)?; - let count = if big { order.u64(b, e.checked_add(4)?)? } else { u64::from(order.u32(b, e.checked_add(4)?)?) }; - let value = value_at(order, b, e, big, ty, count); - fields.push(Field { entry: e, tag, ty, count, value }); - } - Some(Ifd0 { order, big, first, count, entry_bytes, fields }) - } - - fn first_of(&self, tag: u16) -> Option<&Field> { - self.fields.iter().find(|f| f.tag == tag) - } -} - -/// Where an entry's SHORT or RATIONAL value bytes are: inline in the entry when they fit, -/// else at the offset it holds. `None` for other types or when they leave the block. -fn value_at(order: Order, b: &[u8], e: usize, big: bool, ty: u16, count: u64) -> Option { - let size = match ty { - TYPE_SHORT => 2u64, - TYPE_RATIONAL => 8, - _ => return None, - } - .checked_mul(count)?; - let (field, inline) = if big { (e.checked_add(12)?, 8) } else { (e.checked_add(8)?, 4) }; - let at = if size <= inline { - field - } else if big { - usize::try_from(order.u64(b, field)?).ok()? - } else { - usize::try_from(order.u32(b, field)?).ok()? - }; - (at.checked_add(usize::try_from(size).ok()?)? <= b.len()).then_some(at) -} - /// The resolution (pixels per inch, horizontal and vertical) recorded in IFD0 of an EXIF block -/// (with or without the JPEG `Exif\0\0` prefix) or a TIFF structure. -/// -/// Both XResolution and YResolution must be one RATIONAL each with a non-zero denominator. -/// ResolutionUnit 2 (inch, also when the tag is absent) is used as is, 3 (centimetre) is -/// converted; 1 (no absolute unit), any other value or a malformed unit entry gives `None`. -/// The first of duplicated entries wins. +/// or TIFF structure. pub fn exif_resolution(exif: &[u8]) -> Option<(f32, f32)> { - let b = tiff_body(exif); - let ifd = Ifd0::parse(b)?; - let unit = match ifd.first_of(TAG_RESOLUTION_UNIT) { - None => 2, - Some(f) => f.short(ifd.order, b)?, - }; - let scale = match unit { - 2 => 1.0, - 3 => CM_PER_INCH, - _ => return None, - }; - let x = ifd.first_of(TAG_X_RESOLUTION)?.rational(ifd.order, b)?; - let y = ifd.first_of(TAG_Y_RESOLUTION)?.rational(ifd.order, b)?; - ppi_pair(x * scale, y * scale) + craft_metadata::edit::exif_resolution(exif) } -/// `exif` with its IFD0 resolution set to `ppi` (pixels per inch), borrowed when it has no -/// resolution entries, already records that resolution, or cannot be parsed. -/// -/// Existing well-formed XResolution / YResolution (one RATIONAL) entries are rewritten in place, -/// and every well-formed ResolutionUnit (one SHORT) becomes 2 (inch). Malformed entries are -/// removed from IFD0 instead, so no stale value survives; all other bytes are kept. +/// `exif` with its IFD0 resolution set to `ppi`, borrowed when no edit is needed. pub fn exif_with_resolution(exif: &[u8], ppi: (f32, f32)) -> Cow<'_, [u8]> { - exif_with_resolution_inner(exif, ppi, false) + craft_metadata::edit::exif_with_resolution(exif, ppi) } -/// Like [`exif_with_resolution`], but adds X/Y resolution tags when a valid IFD0 has none. -/// Existing TIFF data stays in place, so its offsets remain valid. Used by CMYK JPEG, which -/// cannot carry a JFIF density marker. -pub(crate) fn exif_with_resolution_adding_missing(exif: &[u8], ppi: (f32, f32)) -> Cow<'_, [u8]> { - exif_with_resolution_inner(exif, ppi, true) -} - -/// Rewrite valid IFD0 resolution tags and optionally append tags that are missing or malformed. -fn exif_with_resolution_inner(exif: &[u8], ppi: (f32, f32), add_missing: bool) -> Cow<'_, [u8]> { - if ppi_pair(f64::from(ppi.0), f64::from(ppi.1)).is_none() { - return Cow::Borrowed(exif); - } - if exif.is_empty() { - if !add_missing { - return Cow::Borrowed(exif); - } - // An image with DPI but no source EXIF still needs a valid EXIF block when the output - // format cannot carry resolution in its own header (CMYK JPEG has no valid JFIF marker). - return Cow::Owned(exif_with_resolution_inner(b"II*\0\x08\0\0\0\0\0\0\0\0\0\0", ppi, true).into_owned()); - } - let body = tiff_body(exif); - let prefix = exif.len() - body.len(); - let Some(ifd) = Ifd0::parse(body) else { return Cow::Borrowed(exif) }; - if exif_resolution(body).is_some_and(|r| same(r, ppi)) { - return Cow::Borrowed(exif); - } - let missing_xy = ifd.first_of(TAG_X_RESOLUTION).and_then(|f| f.rational(ifd.order, body)).is_none() - || ifd.first_of(TAG_Y_RESOLUTION).and_then(|f| f.rational(ifd.order, body)).is_none(); - if add_missing && missing_xy { - let Some(body) = append_resolution_ifd(body, &ifd, ppi) else { return Cow::Borrowed(exif) }; - let mut full = exif.get(..prefix).unwrap_or_default().to_vec(); - full.extend_from_slice(&body); - return Cow::Owned(full); - } - if ifd.fields.is_empty() { - return Cow::Borrowed(exif); - } - let order = ifd.order; - let mut out = body.to_vec(); - let mut removed = Vec::new(); - for f in &ifd.fields { - let bytes = match f.tag { - TAG_RESOLUTION_UNIT if f.short(order, body).is_some() => put_u16(order, 2).to_vec(), - TAG_X_RESOLUTION | TAG_Y_RESOLUTION if f.rational(order, body).is_some() => { - let (n, d) = rational(if f.tag == TAG_X_RESOLUTION { ppi.0 } else { ppi.1 }); - [put_u32(order, n), put_u32(order, d)].concat() - } - _ => { - removed.push(f.entry); - continue; - } - }; - let slot = f.value.and_then(|at| out.get_mut(at..at.checked_add(bytes.len())?)); - match slot { - Some(slot) => slot.copy_from_slice(&bytes), - None => removed.push(f.entry), - } - } - if !removed.is_empty() { - remove_entries(&mut out, &ifd, &removed); - } - let mut full = exif.get(..prefix).unwrap_or_default().to_vec(); - full.extend_from_slice(&out); - if full == exif { Cow::Borrowed(exif) } else { Cow::Owned(full) } -} - -/// Append a replacement IFD0 with fresh resolution tags. Every other entry keeps its original -/// bytes and offsets, since the TIFF block's existing data remains where it was. -fn append_resolution_ifd(body: &[u8], ifd: &Ifd0, ppi: (f32, f32)) -> Option> { - let (count_bytes, next_bytes, alignment) = if ifd.big { (8usize, 8usize, 8usize) } else { (2usize, 4usize, 2usize) }; - let mut entries = Vec::with_capacity(ifd.count.saturating_add(3)); - for index in 0..ifd.count { - let entry = ifd.first.checked_add(index.checked_mul(ifd.entry_bytes)?)?; - let tag = ifd.order.u16(body, entry)?; - if matches!(tag, TAG_X_RESOLUTION | TAG_Y_RESOLUTION | TAG_RESOLUTION_UNIT) { - continue; - } - entries.push((tag, body.get(entry..entry.checked_add(ifd.entry_bytes)?)?.to_vec())); - } - let count = entries.len().checked_add(3)?; - if !ifd.big && count > usize::from(u16::MAX) { - return None; - } - - let new_ifd = align_up(body.len(), alignment)?; - let table_end = new_ifd.checked_add(count_bytes)?.checked_add(count.checked_mul(ifd.entry_bytes)?)?; - let next_at = ifd.first.checked_add(ifd.count.checked_mul(ifd.entry_bytes)?)?; - let next_ifd = body.get(next_at..next_at.checked_add(next_bytes)?)?; - let rational_at = align_up(table_end.checked_add(next_bytes)?, if ifd.big { 8 } else { 4 })?; - let y_rational_at = rational_at.checked_add(8)?; - if !ifd.big && (new_ifd > u32::MAX as usize || y_rational_at.checked_add(8)? > u32::MAX as usize) { - return None; - } - - entries.push((TAG_X_RESOLUTION, resolution_entry(ifd.order, ifd.big, TAG_X_RESOLUTION, u64::try_from(rational_at).ok()?)?)); - entries.push((TAG_Y_RESOLUTION, resolution_entry(ifd.order, ifd.big, TAG_Y_RESOLUTION, u64::try_from(y_rational_at).ok()?)?)); - entries.push((TAG_RESOLUTION_UNIT, resolution_entry(ifd.order, ifd.big, TAG_RESOLUTION_UNIT, 2)?)); - entries.sort_by_key(|(tag, _)| *tag); - - let mut out = body.to_vec(); - out.resize(new_ifd, 0); - if ifd.big { - out.extend_from_slice(&put_u64(ifd.order, count as u64)); - } else { - out.extend_from_slice(&put_u16(ifd.order, count as u16)); - } - for (_, entry) in entries { - out.extend_from_slice(&entry); - } - out.extend_from_slice(next_ifd); - out.resize(rational_at, 0); - let (xn, xd) = rational(ppi.0); - let (yn, yd) = rational(ppi.1); - out.extend_from_slice(&put_u32(ifd.order, xn)); - out.extend_from_slice(&put_u32(ifd.order, xd)); - out.extend_from_slice(&put_u32(ifd.order, yn)); - out.extend_from_slice(&put_u32(ifd.order, yd)); - - let offset_at: usize = if ifd.big { 8 } else { 4 }; - if ifd.big { - out.get_mut(offset_at..offset_at.checked_add(8)?)?.copy_from_slice(&put_u64(ifd.order, new_ifd as u64)); - } else { - out.get_mut(offset_at..offset_at.checked_add(4)?)?.copy_from_slice(&put_u32(ifd.order, u32::try_from(new_ifd).ok()?)); - } - Some(out) -} - -/// One IFD entry. Rational fields store an offset; the SHORT unit is inline. -fn resolution_entry(order: Order, big: bool, tag: u16, value: u64) -> Option> { - let entry_bytes = if big { 20 } else { 12 }; - let count_at = 4; - let value_at = if big { 12 } else { 8 }; - let mut entry = vec![0; entry_bytes]; - entry.get_mut(..2)?.copy_from_slice(&put_u16(order, tag)); - entry.get_mut(2..4)?.copy_from_slice(&put_u16(order, if tag == TAG_RESOLUTION_UNIT { TYPE_SHORT } else { TYPE_RATIONAL })); - if big { - entry.get_mut(count_at..count_at + 8)?.copy_from_slice(&put_u64(order, 1)); - if tag == TAG_RESOLUTION_UNIT { - entry.get_mut(value_at..value_at + 2)?.copy_from_slice(&put_u16(order, value as u16)); - } else { - entry.get_mut(value_at..value_at + 8)?.copy_from_slice(&put_u64(order, value)); - } - } else { - entry.get_mut(count_at..count_at + 4)?.copy_from_slice(&put_u32(order, 1)); - if tag == TAG_RESOLUTION_UNIT { - entry.get_mut(value_at..value_at + 2)?.copy_from_slice(&put_u16(order, value as u16)); - } else { - entry.get_mut(value_at..value_at + 4)?.copy_from_slice(&put_u32(order, u32::try_from(value).ok()?)); - } - } - Some(entry) -} - -/// Round `value` up to the next `alignment` boundary, returning `None` on overflow. -fn align_up(value: usize, alignment: usize) -> Option { - value.checked_add((alignment - value % alignment) % alignment) -} - -fn put_u16(order: Order, v: u16) -> [u8; 2] { - match order { - Order::Little => v.to_le_bytes(), - Order::Big => v.to_be_bytes(), - } -} - -fn put_u32(order: Order, v: u32) -> [u8; 4] { - match order { - Order::Little => v.to_le_bytes(), - Order::Big => v.to_be_bytes(), - } -} - -fn put_u64(order: Order, v: u64) -> [u8; 8] { - match order { - Order::Little => v.to_le_bytes(), - Order::Big => v.to_be_bytes(), - } -} - -/// Removes the IFD0 entries at offsets `removed` (see [`exif_with_resolution`]). -fn remove_entries(b: &mut [u8], ifd: &Ifd0, removed: &[usize]) { - let eb = ifd.entry_bytes; - let next_bytes = if ifd.big { 8 } else { 4 }; - let count_bytes = if ifd.big { 8 } else { 2 }; - let Some(table_end) = ifd.count.checked_mul(eb).and_then(|n| ifd.first.checked_add(n)) else { return }; - let Some(old) = b.get(ifd.first..table_end.saturating_add(next_bytes)).map(<[u8]>::to_vec) else { return }; - let mut table = Vec::with_capacity(old.len()); - let mut kept = 0usize; - for (i, entry) in old.chunks_exact(eb).take(ifd.count).enumerate() { - if !removed.contains(&(ifd.first + i * eb)) { - table.extend_from_slice(entry); - kept += 1; - } - } - table.extend_from_slice(old.get(ifd.count * eb..).unwrap_or_default()); - table.resize(old.len(), 0); - let count: Vec = if ifd.big { put_u64(ifd.order, kept as u64).to_vec() } else { put_u16(ifd.order, kept as u16).to_vec() }; - let Some(count_at) = ifd.first.checked_sub(count_bytes) else { return }; - if let Some(slot) = b.get_mut(count_at..ifd.first) { - slot.copy_from_slice(&count); - } - if let Some(slot) = b.get_mut(ifd.first..ifd.first + table.len()) { - slot.copy_from_slice(&table); - } -} - -/// The resolution in a Photoshop image resource block (a sequence of `8BIM` resources, as in a -/// JPEG's APP13 "Photoshop 3.0" segment or TIFF tag 34377): its ResolutionInfo (0x03ED), whose -/// Fixed 16.16 hRes / vRes are pixels per inch whatever display unit follows them. +/// The resolution (pixels per inch) recorded by Photoshop's ResolutionInfo image resource. pub fn photoshop_resolution(resources: &[u8]) -> Option<(f32, f32)> { - let be16 = |at: usize| resources.get(at..at.checked_add(2)?).map(|s| u16::from_be_bytes([s[0], s[1]])); - let be32 = |at: usize| resources.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])); - let mut i = 0usize; - while i < resources.len() { - let signature = resources.get(i..i.checked_add(4)?)?; - let id = be16(i.checked_add(4)?)?; - // Pascal name: length byte plus text, padded to an even size. - let name_len = usize::from(*resources.get(i.checked_add(6)?)?); - let name = (name_len + 1).next_multiple_of(2); - let size_at = i.checked_add(6)?.checked_add(name)?; - let size = usize::try_from(be32(size_at)?).ok()?; - let data = size_at.checked_add(4)?; - if signature == b"8BIM" && id == RESOLUTION_INFO { - let info = resources.get(data..data.checked_add(size)?)?; - if info.len() < 16 { - return None; - } - let fixed = |at: usize| be32(data + at).map(|v| f64::from(v) / 65536.0); - return ppi_pair(fixed(0)?, fixed(8)?); - } - i = data.checked_add(size)?.checked_add(size % 2)?; - } - None + craft_metadata::edit::photoshop_resolution(resources) } -/// The text ranges of every value of XMP property `key` (`key="v"`, `key='v'` or -/// `v`), in order. -fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> { - let mut out = Vec::new(); - let mut from = 0; - while let Some(k) = xmp.get(from..).and_then(|s| s.find(key)).map(|k| k + from) { - from = k + key.len(); - // An attribute or an opening tag of exactly this name (not ``, not `xkey`). - if !xmp.get(..k).and_then(|h| h.chars().next_back()).is_some_and(|c| c == '<' || c.is_ascii_whitespace()) { - continue; - } - let rest = xmp.get(from..).unwrap_or_default(); - let after_key = rest.trim_start(); - let (value, close) = if let Some(r) = after_key.strip_prefix('=') { - let r = r.trim_start(); - match r.chars().next() { - Some(q @ ('"' | '\'')) => (r.get(1..).unwrap_or_default(), q), - _ => continue, - } - } else if let Some(r) = rest.strip_prefix('>') { - (r, '<') - } else { - continue; - }; - let start = xmp.len() - value.len(); - // Advance past this value before searching for the next key. Without this, `from` - // only moved past the key text, so property-like text repeated inside an unrelated - // attribute re-ran this full-suffix `find(close)` for every occurrence, which is - // quadratic in the packet size. A missing close means the value is unterminated, so - // no later value can parse either; stop scanning in that case. - let Some(len) = value.find(close) else { break }; - out.push((start, start + len)); - from = start + len + close.len_utf8(); - } - out -} - -/// An XMP rational (`300/1`) or plain number. -fn xmp_number(s: &str) -> Option { - let s = s.trim(); - match s.split_once('/') { - Some((n, d)) => { - let (n, d) = (n.trim().parse::().ok()?, d.trim().parse::().ok()?); - (d != 0.0).then(|| n / d) - } - None => s.parse().ok(), - } -} - -const XMP_X: &str = "tiff:XResolution"; -const XMP_Y: &str = "tiff:YResolution"; -const XMP_UNIT: &str = "tiff:ResolutionUnit"; - -/// The resolution (pixels per inch) in an XMP packet's `tiff:XResolution` / `tiff:YResolution` -/// (with `tiff:ResolutionUnit`, 2 when absent, 3 converted from centimetres), or `None`. +/// The resolution (pixels per inch, horizontal and vertical) recorded in an XMP packet. pub fn xmp_resolution(xmp: &str) -> Option<(f32, f32)> { - let first = |key: &str| xmp_values(xmp, key).first().and_then(|&(a, b)| xmp.get(a..b)); - let unit = match first(XMP_UNIT) { - None => 2.0, - Some(u) => xmp_number(u)?, - }; - let scale = if unit == 2.0 { - 1.0 - } else if unit == 3.0 { - CM_PER_INCH - } else { - return None; - }; - ppi_pair(xmp_number(first(XMP_X)?)? * scale, xmp_number(first(XMP_Y)?)? * scale) + craft_metadata::edit::xmp_resolution(xmp) } -/// `xmp` with its `tiff:` resolution properties set to `ppi` (and the unit to 2, inch), -/// borrowed when it has none or already says so. +/// `xmp` with its resolution set to `ppi`, borrowed when no edit is needed. pub fn xmp_with_resolution(xmp: &str, ppi: (f32, f32)) -> Cow<'_, str> { - if ppi_pair(f64::from(ppi.0), f64::from(ppi.1)).is_none() || xmp_resolution(xmp).is_some_and(|r| same(r, ppi)) { - return Cow::Borrowed(xmp); - } - let text = |v: f32| { - let (n, d) = rational(v); - format!("{n}/{d}") - }; - let mut edits: Vec<(usize, usize, String)> = Vec::new(); - for (key, value) in [(XMP_X, text(ppi.0)), (XMP_Y, text(ppi.1)), (XMP_UNIT, "2".to_owned())] { - edits.extend(xmp_values(xmp, key).into_iter().map(|(a, b)| (a, b, value.clone()))); - } - if edits.is_empty() { - return Cow::Borrowed(xmp); - } - edits.sort_by_key(|e| e.0); - let mut out = String::with_capacity(xmp.len() + 16); - let mut at = 0; - for (a, b, v) in edits { - // Overlapping ranges can only come from malformed markup; keep the first edit. - if a < at { - continue; - } - out.push_str(xmp.get(at..a).unwrap_or_default()); - out.push_str(&v); - at = b; - } - out.push_str(xmp.get(at..).unwrap_or_default()); - if out == xmp { Cow::Borrowed(xmp) } else { Cow::Owned(out) } + craft_metadata::edit::xmp_with_resolution(xmp, ppi) } -/// `exif` without its embedded thumbnail, or `None` when it has none (or doesn't parse). -/// -/// EXIF keeps the thumbnail in IFD1, the IFD IFD0's next-IFD pointer names. Finder, Android's -/// gallery and upload pickers show that thumbnail instead of decoding the image, so a copied one -/// keeps showing the photo as it was before it was edited (#2147, #2373). The pointer is cleared; -/// nothing else moves, so every other offset in the block stays valid. -fn exif_without_thumbnail(exif: &[u8]) -> Option> { - let body = tiff_body(exif); - let prefix = exif.len() - body.len(); - let (_, first, count, entry_bytes, big_tiff) = ifd0_entries(body)?; - let next = prefix.checked_add(first)?.checked_add(count.checked_mul(entry_bytes)?)?; - let width = if big_tiff { 8 } else { 4 }; - // In bounds: `ifd0_entries` checked that the whole pointer is present. - if exif.get(next..next.checked_add(width)?)?.iter().all(|b| *b == 0) { - return None; - } - let mut out = exif.to_vec(); - out.get_mut(next..next + width)?.fill(0); - Some(out) -} - -/// The EXIF to write next to upright pixels at resolution `ppi`: Orientation 1 (see -/// [`upright_exif`]), no thumbnail of the source image (see [`exif_without_thumbnail`]) and, -/// when `ppi` is known, the resolution (see [`exif_with_resolution`]). +/// The EXIF to write next to upright pixels at resolution `ppi`. pub fn export_exif(exif: &[u8], ppi: Option<(f32, f32)>) -> Cow<'_, [u8]> { - export_exif_inner(exif, ppi, false) + craft_metadata::edit::export_exif(exif, ppi) } -/// Export EXIF for a format without its own resolution field, adding missing X/Y resolution -/// entries to valid metadata when necessary. +/// Export EXIF, adding missing resolution entries when `ppi` is supplied. pub(crate) fn export_exif_adding_missing_resolution(exif: &[u8], ppi: Option<(f32, f32)>) -> Cow<'_, [u8]> { - export_exif_inner(exif, ppi, true) + craft_metadata::edit::export_exif_adding_missing_resolution(exif, ppi) } -/// Normalize EXIF orientation and thumbnails, optionally adding missing output resolution tags. -fn export_exif_inner(exif: &[u8], ppi: Option<(f32, f32)>, add_missing: bool) -> Cow<'_, [u8]> { - let up = upright_exif(exif); - let up = match exif_without_thumbnail(&up) { - Some(v) => Cow::Owned(v), - None => up, - }; - let Some(ppi) = ppi else { return up }; - let result = if add_missing { exif_with_resolution_adding_missing(&up, ppi) } else { exif_with_resolution(&up, ppi) }; - if let Cow::Owned(v) = result { - return Cow::Owned(v); - } - up -} - -/// The XMP to write next to upright pixels at resolution `ppi` (see [`upright_xmp`] and -/// [`xmp_with_resolution`]). +/// The XMP to write next to upright pixels at resolution `ppi`. pub fn export_xmp(xmp: &str, ppi: Option<(f32, f32)>) -> Cow<'_, str> { - let up = upright_xmp(xmp); - let Some(ppi) = ppi else { return up }; - if let Cow::Owned(v) = xmp_with_resolution(&up, ppi) { - return Cow::Owned(v); - } - up + craft_metadata::edit::export_xmp(xmp, ppi) } -/// The resolution a decoded file's metadata blocks record, in precedence order: XMP, then -/// EXIF (Photoshop's ResolutionInfo is format-specific and read by the decoder). +/// Resolution recorded by XMP or EXIF when a format-specific resolution field is absent. +pub fn resolution(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> { + craft_metadata::edit::resolution(exif, xmp) +} + +/// Resolution a decoded file's EXIF and XMP blocks record, in precedence order. pub(crate) fn from_metadata(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> { - xmp.and_then(xmp_resolution).or_else(|| exif.and_then(exif_resolution)) + craft_metadata::edit::resolution(exif, xmp) } diff --git a/crates/image-codecs/src/web.rs b/crates/image-codecs/src/web.rs index dfd0cd9b90..098462ad7f 100644 --- a/crates/image-codecs/src/web.rs +++ b/crates/image-codecs/src/web.rs @@ -286,7 +286,8 @@ pub fn decode_wbmp(bytes: &[u8]) -> Result<(u32, u32, Vec), CodecError> { /// JPEG from 8-bit RGB (`rgb.len() == 3·w·h`): quality 1..=100, optional progressive scans and /// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density, EXIF and -/// XMP. EXIF that doesn't fit in one segment is left out (see [`jpeg_exif_fits`]). +/// XMP. EXIF that doesn't fit in one segment is left out (see [`jpeg_exif_fits`]); XMP that +/// doesn't fit loses its layered-document properties, else is left out too (see [`jpeg_xmp_fits`]). #[allow(clippy::too_many_arguments)] pub fn encode_jpeg_rgb8( width: u32, @@ -326,11 +327,10 @@ pub fn encode_jpeg_rgb8( if let Some(seg) = exif.and_then(|x| crate::codecs::jpeg::exif_segment(x, ppi)) { enc.add_app_segment(1, &seg).map_err(e)?; } - if let Some(x) = xmp { - // Its `tiff:` resolution, if any, says what the JFIF density says (#1691). - let x = crate::resolution::export_xmp(x, ppi); - let mut seg = b"http://ns.adobe.com/xap/1.0/\0".to_vec(); - seg.extend_from_slice(x.as_bytes()); + // Its `tiff:` resolution, if any, says what the JFIF density says. A packet past one segment + // loses its layered-document properties, else is left out, as the other JPEG paths do; see + // [`jpeg_xmp_fits`]. + if let Some(seg) = xmp.and_then(|x| crate::codecs::jpeg::xmp_segment(x, ppi)) { enc.add_app_segment(1, &seg).map_err(e)?; } if let Some(icc) = icc { @@ -345,6 +345,12 @@ pub fn jpeg_exif_fits(exif: &[u8], dpi: Option) -> bool { crate::codecs::jpeg::exif_segment(exif, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))).is_some() } +/// Whether [`encode_jpeg_rgb8`] writes `xmp` at `dpi`: it must fit in one APP1 segment, if need +/// be without its layered-document properties. +pub fn jpeg_xmp_fits(xmp: &str, dpi: Option) -> bool { + crate::codecs::jpeg::xmp_segment(xmp, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))).is_some() +} + #[cfg(test)] mod tests { use super::*; @@ -355,6 +361,27 @@ mod tests { (w, h, img.convert(crate::ChannelLayout::Rgba, crate::SampleType::U8).data().to_vec()) } + /// XMP past one APP1 segment loses its layered-document properties, and a packet still too + /// large is left out; the JPEG is written either way. + #[test] + fn web_jpeg_oversized_xmp_is_trimmed_or_left_out() { + let rgb = vec![100u8; 8 * 8 * 3]; + let ancestors = format!( + "{}", + "id".repeat(5_000) + ); + assert!(ancestors.len() > 70_000); + assert!(jpeg_xmp_fits(&ancestors, Some(72.0)), "trimmed, it fits"); + let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), None, Some(&ancestors)).unwrap(); + let xmp = crate::decode(&out).unwrap().meta.xmp.unwrap_or_default(); + assert!(xmp.contains("dc:title=\"kept\"") && !xmp.contains("DocumentAncestors"), "{xmp}"); + let big = format!("", "x".repeat(70_000)); + assert!(!jpeg_xmp_fits(&big, Some(72.0))); + let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), None, Some(&big)).unwrap(); + let img = crate::decode(&out).unwrap(); + assert_eq!((img.dimensions(), img.meta.xmp), ((8, 8), None), "written without the XMP"); + } + fn pattern(w: usize, h: usize, n: usize) -> Vec { (0..w * h).map(|i| (((i % w) * 7 + (i / w) * 13 + (i * i) % 5) % n) as u8).collect() } diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index 0c7bc03d44..6b213ea838 100644 --- a/crates/image-codecs/tests/it/png_jpeg.rs +++ b/crates/image-codecs/tests/it/png_jpeg.rs @@ -115,6 +115,26 @@ fn jpeg_cmyk_roundtrip_with_adobe_marker() { assert!(psnr(&img, &back) > 35.0, "{}", psnr(&img, &back)); } +#[test] +fn jpeg_cmyk_without_adobe_marker_keeps_samples_as_inks() { + let img = Image::from_u8(16, 16, ChannelLayout::Cmyk, [10u8, 100, 200, 50].repeat(256)).unwrap(); + let marked = encode(&img, Format::Jpeg, &EncodeOptions { jpeg_quality: 95, ..Default::default() }).unwrap(); + let signature = b"\xFF\xEE\x00\x0EAdobe"; + let start = marked.windows(signature.len()).position(|part| part == signature).expect("Adobe APP14 marker"); + // APP14's two marker bytes and two-byte length precede its 12-byte payload. + let mut unmarked = Vec::with_capacity(marked.len() - 16); + unmarked.extend_from_slice(&marked[..start]); + unmarked.extend_from_slice(&marked[start + 16..]); + + let adobe_pixels = decode(&marked).unwrap().data().to_vec(); + let unmarked_pixels = decode(&unmarked).unwrap().data().to_vec(); + for (adobe, raw) in adobe_pixels.as_chunks::<4>().0.iter().zip(unmarked_pixels.as_chunks::<4>().0) { + for (&ink, &stored) in adobe.iter().zip(raw) { + assert_eq!(stored, 255 - ink, "unmarked CMYK samples are direct inks"); + } + } +} + #[test] fn jpeg_ycck_decodes_to_cmyk() { let img = synth(40, 32, ChannelLayout::Cmyk, SampleType::U8, 4, 0.02); diff --git a/crates/image-codecs/tests/it/tiff_pages.rs b/crates/image-codecs/tests/it/tiff_pages.rs index 0e589786fc..b94509598e 100644 --- a/crates/image-codecs/tests/it/tiff_pages.rs +++ b/crates/image-codecs/tests/it/tiff_pages.rs @@ -382,6 +382,21 @@ fn associated_alpha_is_made_straight() { assert_eq!(img.to_u16_samples().unwrap(), [32768, 32768]); } +#[test] +fn ink_set_and_extra_samples_are_listed() { + let px = [10u8, 20, 30, 40, 17, 128]; + let d = strips(1, 1, 8, 6, 5, 1, &px).tag(332, SHORT, &[2]).tag(338, SHORT, &[0, 1]); + let info = tiff_info(&build(true, false, &[d], &[0]).bytes).unwrap(); + use ExtraSampleKind::*; + assert_eq!((info.pages[0].ink_set, &info.pages[0].extra_samples[..]), (Some(InkSet::InkNames), &[Unspecified, AssociatedAlpha][..])); + let d = strips(1, 1, 8, 6, 5, 1, &px).tag(332, SHORT, &[7]).tag(338, SHORT, &[2, 5]); + let info = tiff_info(&build(true, false, &[d], &[0]).bytes).unwrap(); + assert_eq!((info.pages[0].ink_set, &info.pages[0].extra_samples[..]), (Some(InkSet::Invalid(7)), &[UnassociatedAlpha, Invalid(5)][..])); + let d = strips(1, 1, 8, 4, 5, 1, &px[..4]); + let info = tiff_info(&build(true, false, &[d], &[0]).bytes).unwrap(); + assert_eq!((info.pages[0].ink_set, &info.pages[0].extra_samples[..]), (None, &[][..])); +} + #[test] fn white_is_zero_opens_with_the_right_tones() { // #691: 00 FF 00 in a WhiteIsZero file is white, black, white. diff --git a/crates/jpeg/Cargo.toml b/crates/jpeg/Cargo.toml index afdae2fdbc..fba86444d9 100644 --- a/crates/jpeg/Cargo.toml +++ b/crates/jpeg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-jpeg" -description = "Clean-room JPEG decoder (ITU-T T.81): 12-bit and arithmetic-coded frames, and baseline frames a band of rows at a time." +description = "Clean-room JPEG decoder and 8-bit optimized baseline encoder (ITU-T T.81)." version.workspace = true edition.workspace = true license.workspace = true @@ -12,8 +12,14 @@ workspace = true [dependencies] thiserror = { workspace = true } +rayon = { workspace = true, optional = true } [dev-dependencies] # Reference encoder and baseline decoder for the comparison tests. jpeg-encoder = "0.6" zune-jpeg = "0.5" +jpeg-decoder = "0.3" + +[features] +default = [] +parallel = ["dep:rayon"] diff --git a/crates/jpeg/README.md b/crates/jpeg/README.md index 6b04cc8ea1..3b72ebd065 100644 --- a/crates/jpeg/README.md +++ b/crates/jpeg/README.md @@ -1,11 +1,14 @@ # craft-jpeg -A clean-room JPEG decoder for the Craft apps, written from ITU-T T.81 (ISO/IEC 10918-1). It -covers the processes that common Rust JPEG decoders skip: 12-bit samples and arithmetic coding. -It also decodes the common sequential 8-bit files a band of rows at a time ([`Bands`](#decoding-in-bands)), -for images too large to decode into one buffer. -No `unsafe`, no panics on malformed input, and it builds for `wasm32-unknown-unknown`. The only -dependency is `thiserror`. +A clean-room JPEG decoder and 8-bit baseline encoder for the Craft apps, written from ITU-T T.81 +(ISO/IEC 10918-1). The decoder covers processes that common Rust JPEG decoders skip: 12-bit +samples and arithmetic coding. It also decodes the common sequential 8-bit files a band of rows +at a time ([`Bands`](#decoding-in-bands)), for images too large to decode into one buffer. The +baseline encoder writes per-image optimized Huffman tables and supports grayscale and YCbCr 4:4:4, +4:2:2 and 4:2:0. + +No `unsafe`, no panics on malformed input, and it builds for `wasm32-unknown-unknown`. The required +dependency is `thiserror`; the optional `parallel` feature adds Rayon for multi-core encoding. ```toml craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "" } @@ -99,6 +102,24 @@ fn use_craft_jpeg(bytes: &[u8]) -> bool { SOF11 (lossless) falls in that range and returns `Unsupported`. +## Baseline encoding + +`encode_baseline(data, width, height, channels, quality, subsampling, app_segments)` writes an +interleaved 8-bit baseline JPEG with optimized Huffman tables. `channels` is 1 (gray), 3 (RGB), or +4 (RGBA; alpha is ignored). Dimensions must be in `1..=65535`, quality is clamped to `1..=100`, +and a short sample buffer is rejected. APP segments must use markers `0xE0..=0xEF` and payloads +no larger than 65533 bytes. Invalid input returns `EncodeError::InvalidInput` instead of an empty +or malformed JPEG. + +```rust +use craft_jpeg::{ChromaSubsampling, encode_baseline}; + +let jpeg = encode_baseline(&rgb, width, height, 3, 90, ChromaSubsampling::S420, &[])?; +``` + +Enable the `parallel` Cargo feature to encode restart-interval bands concurrently. The output is +byte-stable across sequential and parallel execution. + ## Decoding in bands `Bands` decodes a sequential Huffman-coded (SOF0, SOF1) 8-bit file whose first scan holds every @@ -141,10 +162,11 @@ if reader.damaged() { /* warn: part of the image is missing */ } ## Boundaries -- In scope: decoding the frames above into samples. -- Out of scope: metadata. The decoder skips every APPn and COM segment. ICC profiles, EXIF, - XMP, Photoshop resources, resolution and the APP14 `Adobe` segment are the app's to read. - Color management and encoding also stay in the apps. +- In scope: decoding the frames above into samples and encoding 8-bit baseline JPEG. +- Out of scope: metadata interpretation. The decoder skips every APPn and COM segment. ICC + profiles, EXIF, XMP, Photoshop resources, resolution and the APP14 `Adobe` segment are the + caller's to read; the encoder accepts caller-constructed APP segments. Color management stays + with each app. ## Testing @@ -152,6 +174,9 @@ if reader.damaged() { /* warn: part of the image is missing */ } - unit tests in `src/tests.rs`: arithmetic-coded streams from a test-only encoder must decode to the coefficients that went in, and Huffman streams are compared against `zune-jpeg`. +- unit tests in `src/encode.rs`: optimized table validity and file-size reduction, independent + `jpeg-decoder` and `zune-jpeg` decoding, 4:4:4/4:2:2/4:2:0 frame-header sampling, invalid input, + and pinned output hashes for grayscale, RGB, RGBA and the existing 4:2:0 path. - `tests/conformance.rs`, on libjpeg-turbo's test images in `tests/data` (provenance and how the derived files were made: `tests/data/SOURCE.md`): - `testimgari.jpg` (SOF9) decodes to exactly the samples of its jpegtran Huffman transcode. diff --git a/crates/jpeg/src/encode.rs b/crates/jpeg/src/encode.rs new file mode 100644 index 0000000000..548f4c9f96 --- /dev/null +++ b/crates/jpeg/src/encode.rs @@ -0,0 +1,879 @@ +//! Parallel baseline JPEG encoder (ITU-T T.81 / JFIF). +//! +//! The image is cut into bands of MCU rows separated by restart markers (`DRI` + `RSTn`): DC +//! prediction restarts at every marker, so bands are entropy-coded independently on all cores and +//! concatenated. Quantization uses the example tables of T.81 Annex K scaled by the usual 1–100 +//! quality convention. Huffman tables are made for each image from its own symbol counts (T.81 +//! Annex K.2): a first pass over the bands counts the symbols, a second codes them. The file stays +//! interleaved baseline with the tables in its `DHT` segments, readable by every decoder, and is +//! smaller than with the Annex K example tables at the same pixels. Supports grayscale and YCbCr +//! 4:4:4, 4:2:2, and 4:2:0. + +/// Chroma sampling for baseline JPEG encoding. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ChromaSubsampling { + /// Full resolution chroma. + #[default] + S444, + /// Half horizontal resolution chroma. + S422, + /// Half horizontal and vertical resolution chroma. + S420, +} + +/// Why a baseline JPEG could not be encoded. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum EncodeError { + /// Invalid dimensions, channel count, or source buffer length. + #[error("invalid JPEG input: {0}")] + InvalidInput(String), +} + +/// T.81 Annex K.1 / K.2 example quantization tables (natural order). +const Q_LUMA: [u16; 64] = [ + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, + 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, +]; +const Q_CHROMA: [u16; 64] = [ + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, +]; + +/// Zig-zag position k → natural index. +const ZIGZAG: [usize; 64] = [ + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, + 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +]; + +/// T.81 Annex K.3 example Huffman tables: (code counts per length 1..16, symbols). +const DC_LUMA_BITS: [u8; 16] = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; +const DC_CHROMA_BITS: [u8; 16] = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; +const DC_VALS: [u8; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; +const AC_LUMA_BITS: [u8; 16] = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d]; +const AC_LUMA_VALS: [u8; 162] = [ + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, +]; +const AC_CHROMA_BITS: [u8; 16] = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; +const AC_CHROMA_VALS: [u8; 162] = [ + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, +]; + +/// Huffman code table: symbol → (code, length). +struct Huff { + code: [(u16, u8); 256], +} + +impl Huff { + /// Canonical codes from counts (T.81 Annex C). + fn new(bits: &[u8; 16], vals: &[u8]) -> Huff { + let mut code = [(0u16, 0u8); 256]; + let (mut c, mut k) = (0u16, 0usize); + for (len, &n) in bits.iter().enumerate() { + for _ in 0..n { + if let Some(&v) = vals.get(k) { + code[v as usize] = (c, len as u8 + 1); + } + c = c.wrapping_add(1); + k += 1; + } + c = c.wrapping_shl(1); + } + Huff { code } + } +} + +/// Symbol counts of one Huffman table: index = symbol (DC size category, or AC run/size byte). +type Freq = [u64; 256]; + +/// The code lengths (`BITS`, counts per length 1..16) and symbols (`HUFFVAL`) of an optimal +/// Huffman table for `freq`, limited to 16-bit codes and never assigning the all-ones code +/// (T.81 Annex K.2, figures K.1–K.4). Symbols with a zero count get no code. At least one symbol +/// is always present (a table nothing used gets symbol 0), so the result is a valid `DHT`. +fn optimal_table(freq: &Freq) -> ([u8; 16], Vec) { + // 256 is the reserved pseudo-symbol: counted once, it takes the longest code, which is + // then dropped so no real code is all ones (K.2) + let mut f = [0u64; 257]; + f[..256].copy_from_slice(freq); + if f[..256].iter().all(|&c| c == 0) { + f[0] = 1; + } + f[256] = 1; + let mut size = [0usize; 257]; + let mut next: [Option; 257] = [None; 257]; + loop { + // the two smallest non-zero counts; on equal counts the larger symbol goes first (K.1) + let mut c1: Option = None; + for i in 0..257 { + if f[i] > 0 && c1.is_none_or(|c| f[i] <= f[c]) { + c1 = Some(i); + } + } + let Some(c1) = c1 else { break }; + let mut c2: Option = None; + for i in 0..257 { + if i != c1 && f[i] > 0 && c2.is_none_or(|c| f[i] <= f[c]) { + c2 = Some(i); + } + } + let Some(c2) = c2 else { break }; + f[c1] = f[c1].saturating_add(f[c2]); + f[c2] = 0; + // every symbol in both trees goes one level deeper; c2's chain is appended to c1's + let mut k = c1; + size[k] += 1; + while let Some(n) = next[k] { + k = n; + size[k] += 1; + } + next[k] = Some(c2); + let mut k = c2; + size[k] += 1; + while let Some(n) = next[k] { + k = n; + size[k] += 1; + } + } + // counts per code length; 257 symbols need at most 256 levels + let mut bits = [0usize; 257]; + for &s in &size { + if s > 0 { + bits[s.min(256)] += 1; + } + } + // limit to 16 bits (K.3): move pairs of the longest codes up, one level at a time (the + // deepest level of a full tree always holds an even number of codes) + for i in (17..257).rev() { + while bits[i] >= 2 { + let Some(j) = (1..i - 1).rev().find(|&j| bits[j] > 0) else { break }; + bits[i] -= 2; + bits[i - 1] += 1; + bits[j + 1] += 2; + bits[j] -= 1; + } + } + // drop the reserved symbol's code: it is one of the longest + if let Some(i) = (1..=16).rev().find(|&i| bits[i] > 0) { + bits[i] -= 1; + } + // symbols by code length, then by value (K.4); the reserved symbol is not listed + let mut vals = Vec::new(); + for len in 1..257 { + vals.extend((0..256).filter(|&s| size[s] == len).map(|s| s as u8)); + } + let mut out = [0u8; 16]; + for (o, &b) in out.iter_mut().zip(&bits[1..=16]) { + *o = b.min(255) as u8; + } + (out, vals) +} + +fn scaled_quant(base: &[u16; 64], quality: u8) -> [u16; 64] { + let q = quality.clamp(1, 100) as u32; + let scale = if q < 50 { 5000 / q } else { 200 - 2 * q }; + base.map(|b| ((b as u32 * scale + 50) / 100).clamp(1, 255) as u16) +} + +/// Entropy-coded segment writer with 0xFF byte stuffing. +struct Bits { + out: Vec, + acc: u32, + n: u32, +} + +impl Bits { + fn new() -> Bits { + Bits { out: Vec::new(), acc: 0, n: 0 } + } + #[inline] + fn put(&mut self, code: u32, len: u32) { + if len == 0 { + return; + } + self.acc = (self.acc << len) | (code & ((1 << len) - 1)); + self.n += len; + while self.n >= 8 { + let b = (self.acc >> (self.n - 8)) as u8; + self.out.push(b); + if b == 0xFF { + self.out.push(0); + } + self.n -= 8; + } + self.acc &= (1 << self.n) - 1; + } + /// Pad with 1-bits to a byte boundary. + fn finish(mut self) -> Vec { + if self.n > 0 { + let pad = 8 - self.n; + self.put((1 << pad) - 1, pad); + } + self.out + } +} + +/// AAN output scale factors: `s[0] = 1`, `s[k] = cos(kπ/16)·√2`. +fn aan_scale() -> [f32; 8] { + std::array::from_fn(|k| if k == 0 { 1.0 } else { ((k as f64 * std::f64::consts::PI / 16.0).cos() * std::f64::consts::SQRT_2) as f32 }) +} + +/// Quantization reciprocals with the AAN scaling folded in: coefficient = out / (8·s[u]·s[v]·q). +fn recip_table(q: &[u16; 64]) -> [f32; 64] { + let s = aan_scale(); + std::array::from_fn(|i| 1.0 / (q[i] as f32 * s[i / 8] * s[i % 8] * 8.0)) +} + +/// One 8-point forward DCT (Arai–Agui–Nakajima flowgraph, 5 multiplies) on `d[o + k·stride]`. +#[inline(always)] +fn aan_1d(d: &mut [f32; 64], o: usize, stride: usize) { + let g = |k: usize| o + k * stride; + let (t0, t7) = (d[g(0)] + d[g(7)], d[g(0)] - d[g(7)]); + let (t1, t6) = (d[g(1)] + d[g(6)], d[g(1)] - d[g(6)]); + let (t2, t5) = (d[g(2)] + d[g(5)], d[g(2)] - d[g(5)]); + let (t3, t4) = (d[g(3)] + d[g(4)], d[g(3)] - d[g(4)]); + // even part + let (t10, t13, t11, t12) = (t0 + t3, t0 - t3, t1 + t2, t1 - t2); + d[g(0)] = t10 + t11; + d[g(4)] = t10 - t11; + let z1 = (t12 + t13) * 0.707_106_77; + d[g(2)] = t13 + z1; + d[g(6)] = t13 - z1; + // odd part + let (t10, t11, t12) = (t4 + t5, t5 + t6, t6 + t7); + let z5 = (t10 - t12) * 0.382_683_43; + let z2 = 0.541_196_1 * t10 + z5; + let z4 = 1.306_563 * t12 + z5; + let z3 = t11 * 0.707_106_77; + let (z11, z13) = (t7 + z3, t7 - z3); + d[g(5)] = z13 + z2; + d[g(3)] = z13 - z2; + d[g(1)] = z11 + z4; + d[g(7)] = z11 - z4; +} + +/// Forward DCT of a level-shifted 8×8 block and quantization. +#[inline] +fn fdct_quant(block: &[f32; 64], recip: &[f32; 64], out: &mut [i16; 64]) { + let mut d = *block; + for r in 0..8 { + aan_1d(&mut d, r * 8, 1); + } + for c in 0..8 { + aan_1d(&mut d, c, 8); + } + for i in 0..64 { + out[i] = round_i16(d[i] * recip[i]); + } +} +/// `x.round() as i16` (half away from zero, saturating, NaN to 0) for every `x` (checked for all of them), in plain +/// arithmetic: without SSE4.1 `f32::round` is a libm call, one per coefficient, that keeps the loop from vectorising. +#[inline(always)] +fn round_i16(x: f32) -> i16 { + // (below 2^24 the truncation is exact and so is the remainder) + let c = x.clamp(-65536.0, 65536.0); + let t = c as i32; + let f = c - t as f32; + let r = t + i32::from(f >= 0.5) - i32::from(f <= -0.5); + r.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16 +} + +#[inline] +fn magnitude(v: i32) -> (u32, u32) { + let a = v.unsigned_abs(); + let size = 32 - a.leading_zeros(); + let bits = if v < 0 { (v - 1) as u32 } else { v as u32 }; + (size, bits & ((1u32 << size) - 1)) +} + +/// The Huffman symbols of one quantized block in coding order: `sym(ac, symbol, bits, n)` for the +/// DC size category (`ac` false) and each AC run/size, ZRL and EOB (`ac` true), each followed by +/// its `n` extra bits `bits`. +#[inline(always)] +fn block_symbols(q: &[i16; 64], pred: &mut i32, mut sym: impl FnMut(bool, usize, u32, u32)) { + let d = q[0] as i32 - *pred; + *pred = q[0] as i32; + let (s, b) = magnitude(d); + sym(false, s as usize, b, s); + let mut run = 0u32; + for &zi in &ZIGZAG[1..] { + let v = q[zi] as i32; + if v == 0 { + run += 1; + continue; + } + while run >= 16 { + sym(true, 0xF0, 0, 0); + run -= 16; + } + let (s, b) = magnitude(v); + sym(true, ((run << 4) | s) as usize, b, s); + run = 0; + } + if run > 0 { + sym(true, 0x00, 0, 0); + } +} + +/// One coded symbol of the entropy-coded data: bits 0–7 the symbol, 8–9 its table (0 DC luma, +/// 1 AC luma, 2 DC chroma, 3 AC chroma), 10–13 the number of extra bits, 14–29 those bits (a +/// baseline coefficient needs at most 11). +type Token = u32; + +/// Append one block's symbols to `out` and count them in `freq` (by table, as in [`Token`]). +fn tokenize_block(q: &[i16; 64], pred: &mut i32, chroma: bool, out: &mut Vec, freq: &mut [Freq; 4]) { + let base = if chroma { 2 } else { 0 }; + block_symbols(q, pred, |is_ac, s, bits, n| { + let table = base + is_ac as usize; + freq[table][s & 0xFF] += 1; + out.push((s as u32 & 0xFF) | (table as u32) << 8 | (n & 0xF) << 10 | (bits & 0xFFFF) << 14); + }); +} + +/// Code a band's symbols with `tables` (indexed as in [`Token`]). +fn write_tokens(tokens: &[Token], tables: &[Huff; 4]) -> Vec { + let mut w = Bits::new(); + for &t in tokens { + let (s, table, n, bits) = (t & 0xFF, (t >> 8) & 3, (t >> 10) & 0xF, t >> 14); + let (c, l) = tables[table as usize].code[s as usize]; + w.put(c as u32, l as u32); + w.put(bits, n); + } + w.finish() +} + +/// Planar component samples (level-shifted to −128..127) with edge replication on read. +struct Plane { + w: usize, + h: usize, + data: Vec, +} + +impl Plane { + #[inline] + fn block(&self, bx: usize, by: usize, out: &mut [f32; 64]) { + let (x0, y0) = (bx * 8, by * 8); + if x0 + 8 <= self.w && y0 + 8 <= self.h { + for y in 0..8 { + let i = (y0 + y) * self.w + x0; + out[y * 8..y * 8 + 8].copy_from_slice(&self.data[i..i + 8]); + } + return; + } + for y in 0..8 { + let sy = (by * 8 + y).min(self.h - 1); + let row = &self.data[sy * self.w..(sy + 1) * self.w]; + for x in 0..8 { + out[y * 8 + x] = row[(bx * 8 + x).min(self.w - 1)]; + } + } + } +} + +fn segment(out: &mut Vec, marker: u8, payload: &[u8]) { + out.extend_from_slice(&[0xFF, marker]); + out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); + out.extend_from_slice(payload); +} + +fn dht(out: &mut Vec, class_id: u8, bits: &[u8; 16], vals: &[u8]) { + let mut p = vec![class_id]; + p.extend_from_slice(bits); + p.extend_from_slice(vals); + segment(out, 0xC4, &p); +} + +/// Encode interleaved 8-bit samples (`channels` 1, 3 or 4; alpha is dropped), with Huffman +/// tables made for the image. +pub fn encode( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], +) -> Vec { + encode_with(data, width, height, channels, quality, sub, app_segments, true) +} + +/// Encode an 8-bit grayscale, RGB, or RGBA image as an interleaved baseline JPEG with per-image +/// optimized Huffman tables. Alpha is ignored. Metadata APP segments are supplied as `(marker, +/// payload)` pairs. +pub fn encode_baseline( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], +) -> Result, EncodeError> { + let fits = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).is_some_and(|n| n <= data.len()); + if !fits || width == 0 || height == 0 || width > 65_535 || height > 65_535 || !matches!(channels, 1 | 3 | 4) { + return Err(EncodeError::InvalidInput(format!("{width}x{height}, {channels} channels, {} bytes", data.len()))); + } + if app_segments.iter().any(|(marker, payload)| !(0xE0..=0xEF).contains(marker) || payload.len() > 65_533) { + return Err(EncodeError::InvalidInput("APP markers must be 0xE0..=0xEF with payloads no larger than 65533 bytes".into())); + } + Ok(encode(data, width, height, channels, quality, sub, app_segments)) +} + +/// [`encode`], with optimized Huffman tables or (`optimize` false) the Annex K example tables. +#[allow(clippy::too_many_arguments)] +fn encode_with( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], + optimize: bool, +) -> Vec { + // The public entry takes caller-sized dimensions: refuse (an empty output) what would size an allocation from + // them or index past `data`, rather than panic or allocate for them. + let fits = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).is_some_and(|n| n <= data.len()); + if !fits || width == 0 || height == 0 || width > 65_535 || height > 65_535 || !matches!(channels, 1 | 3 | 4) { + return Vec::new(); + } + let gray = channels == 1; + let (hs, vs) = match (gray, sub) { + (true, _) | (false, ChromaSubsampling::S444) => (1usize, 1usize), + (false, ChromaSubsampling::S422) => (2, 1), + (false, ChromaSubsampling::S420) => (2, 2), + }; + #[cfg(feature = "parallel")] + use rayon::prelude::*; + // colour conversion (JFIF YCbCr, full range, level-shifted) of the pixel rows `rows`, one band's worth at a + // time (in the band's task: the planes of the whole image would be ~290 MB at 24 MP, written and read back + // once): 4:4:4 Y, Cb, Cr at full resolution in one pass; 4:2:0 Y, and chroma (rows `crows` of the + // half-size planes) straight from 2×2 RGB means (conversion is linear: average first, then convert once) + let ncomp = if gray || hs == 2 { 1 } else { 3 }; + let (cw, ch) = (width.div_ceil(hs), height.div_ceil(vs)); + let convert = |rows: std::ops::Range, crows: std::ops::Range| -> Vec { + let mut full: Vec> = (0..ncomp).map(|_| vec![0f32; rows.len() * width]).collect(); + for (k, y) in rows.clone().enumerate() { + let src = &data[y * width * channels..(y + 1) * width * channels]; + let mut out: Vec<&mut [f32]> = full.iter_mut().map(|p| &mut p[k * width..(k + 1) * width]).collect(); + if gray { + for (o, p) in out[0].iter_mut().zip(src.chunks_exact(channels)) { + *o = p[0] as f32 - 128.0; + } + continue; + } + if out.len() == 1 { + for (o, p) in out[0].iter_mut().zip(src.chunks_exact(channels)) { + *o = 0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32 - 128.0; + } + continue; + } + for (x, p) in src.chunks_exact(channels).enumerate() { + let (r, g, b) = (p[0] as f32, p[1] as f32, p[2] as f32); + out[0][x] = 0.299 * r + 0.587 * g + 0.114 * b - 128.0; + out[1][x] = -0.168_736 * r - 0.331_264 * g + 0.5 * b; + out[2][x] = 0.5 * r - 0.418_688 * g - 0.081_312 * b; + } + } + let mut planes: Vec = full.into_iter().map(|data| Plane { w: width, h: rows.len(), data }).collect(); + if !gray && hs == 2 { + let (mut cb, mut cr) = (vec![0f32; cw * crows.len()], vec![0f32; cw * crows.len()]); + for (cy, (ob, or)) in crows.clone().zip(cb.chunks_mut(cw).zip(cr.chunks_mut(cw))) { + for cx in 0..cw { + let s = |k: usize| { + let mut sum = 0.0; + for dy in 0..vs { + for dx in 0..hs { + let y = (cy * vs + dy).min(height - 1); + let x = (cx * hs + dx).min(width - 1); + sum += data[(y * width + x) * channels + k] as f32; + } + } + sum / (hs * vs) as f32 + }; + let (r, g, b) = (s(0), s(1), s(2)); + ob[cx] = -0.168_736 * r - 0.331_264 * g + 0.5 * b; + or[cx] = 0.5 * r - 0.418_688 * g - 0.081_312 * b; + } + } + planes.push(Plane { w: cw, h: crows.len(), data: cb }); + planes.push(Plane { w: cw, h: crows.len(), data: cr }); + } + planes + }; + + let ql = scaled_quant(&Q_LUMA, quality); + let qc = scaled_quant(&Q_CHROMA, quality); + let (rl, rc) = (recip_table(&ql), recip_table(&qc)); + let (mcu_w, mcu_h) = (8 * hs, 8 * vs); + let (mx, my) = (width.div_ceil(mcu_w), height.div_ceil(mcu_h)); + // restart interval: whole MCU rows per band, ≤ 65535 MCUs, enough bands to keep all cores busy + let rows_per_band = (my / 64).clamp(1, (65_535 / mx.max(1)).max(1)); + let bands: Vec = (0..my.div_ceil(rows_per_band)).collect(); + // first pass: each band's quantized blocks as symbols, with their counts per table (DC + // prediction restarts per band, as the restart markers say) + let tokenize_band = |band: &usize| -> (Vec, [Freq; 4]) { + let (mut blk, mut q) = ([0f32; 64], [0i16; 64]); + let (mut tokens, mut freq) = (Vec::new(), [[0u64; 256]; 4]); + let mut pred = [0i32; 3]; + let (m0, m1) = (band * rows_per_band, ((band + 1) * rows_per_band).min(my)); + // the band's planes, its MCU row `m0` at their top (blocks past the image's bottom repeat its last row, + // which is the band's last row then) + let planes = convert(m0 * mcu_h..(m1 * mcu_h).min(height), m0 * 8..(m1 * 8).min(ch)); + for mcu_y in m0..m1 { + let mcu_y = mcu_y - m0; + for mcu_x in 0..mx { + for vy in 0..vs { + for hx in 0..hs { + planes[0].block(mcu_x * hs + hx, mcu_y * vs + vy, &mut blk); + fdct_quant(&blk, &rl, &mut q); + tokenize_block(&q, &mut pred[0], false, &mut tokens, &mut freq); + } + } + if !gray { + for (plane, pred) in planes.iter().zip(pred.iter_mut()).take(3).skip(1) { + plane.block(mcu_x, mcu_y, &mut blk); + fdct_quant(&blk, &rc, &mut q); + tokenize_block(&q, pred, true, &mut tokens, &mut freq); + } + } + } + } + (tokens, freq) + }; + #[cfg(feature = "parallel")] + let tokenized: Vec<(Vec, [Freq; 4])> = bands.par_iter().map(tokenize_band).collect(); + #[cfg(not(feature = "parallel"))] + let tokenized: Vec<(Vec, [Freq; 4])> = bands.iter().map(tokenize_band).collect(); + // the tables: DC luma, AC luma, DC chroma, AC chroma + let tables: [([u8; 16], Vec); 4] = if optimize { + let mut total = [[0u64; 256]; 4]; + for (_, f) in &tokenized { + for (t, f) in total.iter_mut().zip(f) { + for (t, f) in t.iter_mut().zip(f) { + *t = t.saturating_add(*f); + } + } + } + total.each_ref().map(optimal_table) + } else { + [ + (DC_LUMA_BITS, DC_VALS.to_vec()), + (AC_LUMA_BITS, AC_LUMA_VALS.to_vec()), + (DC_CHROMA_BITS, DC_VALS.to_vec()), + (AC_CHROMA_BITS, AC_CHROMA_VALS.to_vec()), + ] + }; + let huff = tables.each_ref().map(|(bits, vals)| Huff::new(bits, vals)); + // second pass: code the symbols + #[cfg(feature = "parallel")] + let coded: Vec> = tokenized.into_par_iter().map(|(t, _)| write_tokens(&t, &huff)).collect(); + #[cfg(not(feature = "parallel"))] + let coded: Vec> = tokenized.into_iter().map(|(t, _)| write_tokens(&t, &huff)).collect(); + + // headers + let mut out = Vec::with_capacity(coded.iter().map(Vec::len).sum::() + 4096); + out.extend_from_slice(&[0xFF, 0xD8]); + // JFIF APP0 first (callers may pass their own, e.g. with a print density) + if !app_segments.iter().any(|(m, _)| *m == 0xE0) { + segment(&mut out, 0xE0, &[b'J', b'F', b'I', b'F', 0, 1, 2, 0, 0, 1, 0, 1, 0, 0]); + } + for (marker, payload) in app_segments { + segment(&mut out, *marker, payload); + } + let dqt = |id: u8, q: &[u16; 64]| -> Vec { + let mut p = vec![id]; + p.extend(ZIGZAG.iter().map(|&i| q[i] as u8)); + p + }; + segment(&mut out, 0xDB, &dqt(0, &ql)); + if !gray { + segment(&mut out, 0xDB, &dqt(1, &qc)); + } + let mut sof = vec![8]; + sof.extend_from_slice(&(height as u16).to_be_bytes()); + sof.extend_from_slice(&(width as u16).to_be_bytes()); + if gray { + sof.extend_from_slice(&[1, 1, 0x11, 0]); + } else { + sof.extend_from_slice(&[3, 1, ((hs as u8) << 4) | vs as u8, 0, 2, 0x11, 1, 3, 0x11, 1]); + } + segment(&mut out, 0xC0, &sof); + let [(dlb, dlv), (alb, alv), (dcb, dcv), (acb, acv)] = &tables; + dht(&mut out, 0x00, dlb, dlv); + dht(&mut out, 0x10, alb, alv); + if !gray { + dht(&mut out, 0x01, dcb, dcv); + dht(&mut out, 0x11, acb, acv); + } + let interval = (rows_per_band * mx) as u16; + if coded.len() > 1 { + segment(&mut out, 0xDD, &interval.to_be_bytes()); + } + if gray { + segment(&mut out, 0xDA, &[1, 1, 0x00, 0, 63, 0]); + } else { + segment(&mut out, 0xDA, &[3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 63, 0]); + } + let last = coded.len().saturating_sub(1); + for (i, c) in coded.iter().enumerate() { + out.extend_from_slice(c); + if i < last { + out.extend_from_slice(&[0xFF, 0xD0 + (i % 8) as u8]); + } + } + out.extend_from_slice(&[0xFF, 0xD9]); + out +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn hostile_dimensions_give_no_output_instead_of_a_panic_or_allocation() { + for (w, h, c) in [(1usize << 40, 1usize << 40, 3usize), (0, 8, 3), (70_000, 2, 3), (8, 8, 7), (8, 8, 3)] { + assert!(encode(&[0u8; 16], w, h, c, 90, ChromaSubsampling::S444, &[]).is_empty(), "{w} x {h} x {c}"); + } + } + + #[test] + fn checked_entry_point_reports_invalid_input() { + assert!(matches!(encode_baseline(&[0; 16], 8, 8, 3, 90, ChromaSubsampling::S444, &[]), Err(EncodeError::InvalidInput(_)))); + assert!(matches!( + encode_baseline(&[0; 192], 8, 8, 3, 90, ChromaSubsampling::S422, &[]), + Ok(bytes) if bytes.starts_with(&[0xFF, 0xD8]) + )); + let too_large_app = [(0xE1, vec![0; 65_534])]; + assert!(matches!(encode_baseline(&[0; 192], 8, 8, 3, 90, ChromaSubsampling::S444, &too_large_app), Err(EncodeError::InvalidInput(_)))); + } + + #[test] + fn requested_chroma_subsampling_is_written_in_the_frame_header() { + let src = test_rgb(19, 9); + for (sub, expected) in [(ChromaSubsampling::S444, 0x11), (ChromaSubsampling::S422, 0x21), (ChromaSubsampling::S420, 0x22)] { + let jpeg = encode(&src, 19, 9, 3, 90, sub, &[]); + let sof = jpeg.windows(2).position(|w| w == [0xFF, 0xC0]).expect("SOF0 marker"); + assert_eq!(jpeg.get(sof + 11), Some(&expected), "{sub:?}"); + } + } + + fn test_rgb(w: usize, h: usize) -> Vec { + let mut v = Vec::with_capacity(w * h * 3); + for y in 0..h { + for x in 0..w { + let t = ((x as f32 / 13.0).sin() * 0.5 + 0.5) * 255.0; + v.extend_from_slice(&[(x * 255 / w) as u8, (y * 255 / h) as u8, t as u8]); + } + } + v + } + + fn psnr(a: &[u8], b: &[u8]) -> f64 { + let mse = a.iter().zip(b).map(|(x, y)| (*x as f64 - *y as f64).powi(2)).sum::() / a.len() as f64; + 10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10() + } + + /// The AAN path matches the direct DCT-II definition. + #[test] + fn aan_matches_reference_dct() { + let block: [f32; 64] = std::array::from_fn(|i| ((i * 37 % 255) as f32) - 128.0); + let q = [1u16; 64]; + let mut out = [0i16; 64]; + fdct_quant(&block, &recip_table(&q), &mut out); + for v in 0..8 { + for u in 0..8 { + let c = |k: usize| if k == 0 { std::f64::consts::FRAC_1_SQRT_2 } else { 1.0 }; + let mut s = 0.0; + for y in 0..8 { + for x in 0..8 { + s += block[y * 8 + x] as f64 + * (((2 * x + 1) * u) as f64 * std::f64::consts::PI / 16.0).cos() + * (((2 * y + 1) * v) as f64 * std::f64::consts::PI / 16.0).cos(); + } + } + let f = 0.25 * c(u) * c(v) * s; + assert!((out[v * 8 + u] as f64 - f).abs() <= 0.51, "({u},{v}): {} vs {f}", out[v * 8 + u]); + } + } + } + + #[test] + fn huffman_tables_are_consistent() { + for (bits, n) in [(&AC_LUMA_BITS, AC_LUMA_VALS.len()), (&AC_CHROMA_BITS, AC_CHROMA_VALS.len()), (&DC_LUMA_BITS, 12), (&DC_CHROMA_BITS, 12)] { + assert_eq!(bits.iter().map(|&b| b as usize).sum::(), n); + } + } + + #[test] + fn decodes_with_independent_decoders_at_odd_sizes() { + for (w, h, sub) in [ + (1, 1, ChromaSubsampling::S444), + (37, 23, ChromaSubsampling::S420), + (37, 23, ChromaSubsampling::S422), + (640, 1031, ChromaSubsampling::S420), + (803, 600, ChromaSubsampling::S444), + ] { + let src = test_rgb(w, h); + let jpg = encode(&src, w, h, 3, 92, sub, &[]); + let mut d = jpeg_decoder::Decoder::new(&jpg[..]); + let px = d.decode().expect("jpeg-decoder"); + let info = d.info().unwrap(); + assert_eq!((info.width as usize, info.height as usize), (w, h)); + if w * h > 64 { + assert!(psnr(&src, &px) > 30.0, "{w}x{h} {sub:?}: psnr {}", psnr(&src, &px)); + } + let z = zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&jpg[..])).decode().expect("zune-jpeg"); + assert_eq!(z.len(), px.len()); + } + } + + /// The code lengths of `(bits, vals)`, checked: every listed symbol once, at most 16 bits, + /// and room left in the code space (the all-ones code is never assigned, Kraft sum < 1). + fn check_table(bits: &[u8; 16], vals: &[u8]) { + assert_eq!(bits.iter().map(|&b| b as usize).sum::(), vals.len()); + let mut seen = [false; 256]; + for &v in vals { + assert!(!seen[v as usize], "symbol {v} listed twice"); + seen[v as usize] = true; + } + let kraft: f64 = bits.iter().enumerate().map(|(i, &n)| n as f64 / 2f64.powi(i as i32 + 1)).sum(); + assert!(kraft < 1.0, "code space full: {kraft}"); + let h = Huff::new(bits, vals); + for &v in vals { + let (c, l) = h.code[v as usize]; + assert!((1..=16).contains(&l)); + assert_ne!(c as u32, (1u32 << l) - 1, "symbol {v} has the all-ones code"); + } + } + + #[test] + fn optimal_tables_are_valid_and_bounded() { + // one symbol, two, a typical spread and every symbol + let mut one = [0u64; 256]; + one[7] = 5; + let mut two = [0u64; 256]; + two[0] = 1; + two[0xF0] = 1_000_000; + let typical: Freq = std::array::from_fn(|s| if s % 3 == 0 { (s as u64 * 7919) % 1000 + 1 } else { 0 }); + let all: Freq = std::array::from_fn(|s| s as u64 + 1); + // Fibonacci counts make an unbounded Huffman tree ~40 levels deep: the 16-bit limit applies + let mut fib = [0u64; 256]; + let (mut a, mut b) = (1u64, 1u64); + for f in fib.iter_mut().take(40) { + *f = a; + (a, b) = (b, a + b); + } + for (name, f) in [("one", one), ("two", two), ("typical", typical), ("all", all), ("fib", fib), ("none", [0; 256])] { + let (bits, vals) = optimal_table(&f); + check_table(&bits, &vals); + for (s, &count) in f.iter().enumerate() { + assert_eq!(vals.contains(&(s as u8)), count > 0 || (name == "none" && s == 0), "{name}: symbol {s}"); + } + } + // more frequent symbols never get longer codes + let (bits, vals) = optimal_table(&typical); + let h = Huff::new(&bits, &vals); + for &x in &vals { + for &y in &vals { + if typical[x as usize] > typical[y as usize] { + assert!(h.code[x as usize].1 <= h.code[y as usize].1, "{x} vs {y}"); + } + } + } + // the Annex K example tables pass the same checks + check_table(&AC_LUMA_BITS, &AC_LUMA_VALS); + check_table(&DC_CHROMA_BITS, &DC_VALS); + } + + /// Issue #1373: tables made for the image give a smaller file with exactly the same pixels as + /// the Annex K example tables (the quantized coefficients are the same), at every quality and + /// subsampling, and both decoders read it. + #[test] + fn optimized_tables_shrink_files_without_changing_pixels() { + let (w, h) = (517, 333); + // gradients plus deterministic noise, like a photo's grain + let mut seed = 0x2545_f491_u32; + let src: Vec = test_rgb(w, h) + .into_iter() + .map(|v| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + v.saturating_add((seed % 23) as u8) + }) + .collect(); + for (q, sub) in [ + (100, ChromaSubsampling::S444), + (92, ChromaSubsampling::S444), + (75, ChromaSubsampling::S420), + (30, ChromaSubsampling::S420), + (85, ChromaSubsampling::S422), + ] { + let std = encode_with(&src, w, h, 3, q, sub, &[], false); + let opt = encode(&src, w, h, 3, q, sub, &[]); + assert!(opt.len() < std.len(), "q{q} {sub:?}: {} ≥ {}", opt.len(), std.len()); + let a = jpeg_decoder::Decoder::new(&std[..]).decode().expect("standard tables"); + let b = jpeg_decoder::Decoder::new(&opt[..]).decode().expect("optimized tables"); + assert_eq!(a, b, "q{q} {sub:?}: pixels differ"); + let z = zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&opt[..])).decode().expect("zune-jpeg"); + assert_eq!(z.len(), b.len()); + } + // grayscale too + let gray: Vec = src.iter().step_by(3).copied().collect(); + let std = encode_with(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[], false); + let opt = encode(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[]); + assert!(opt.len() < std.len()); + assert_eq!(jpeg_decoder::Decoder::new(&std[..]).decode().unwrap(), jpeg_decoder::Decoder::new(&opt[..]).decode().unwrap()); + } + + /// The bytes written for 4:4:4, 4:2:0, grayscale and RGBA input at a size cut into many bands, with partial MCUs + /// at the right and bottom edges, pinned: each band converts its own rows to YCbCr, which must not change a bit. + #[test] + fn encoded_bytes_are_pinned() { + let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3)); + let (w, h) = (1203, 1037); + let rgb = test_rgb(w, h); + let gray: Vec = rgb.as_chunks::<3>().0.iter().map(|p| p[1]).collect(); + let rgba: Vec = rgb.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect(); + let got = [ + fnv(&encode(&rgb, w, h, 3, 90, ChromaSubsampling::S444, &[])), + fnv(&encode(&rgb, w, h, 3, 75, ChromaSubsampling::S420, &[])), + fnv(&encode(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[])), + fnv(&encode(&rgba, w, h, 4, 85, ChromaSubsampling::S444, &[])), + ]; + assert_eq!(got, PINNED, "{got:#x?}"); + } + /// [`round_i16`] against `f32::round` at the halves, the ends of `i16`, NaN and infinities, and a spread of every + /// magnitude (all 2^32 inputs were compared once, offline). + #[test] + fn round_i16_is_round_as_i16() { + let special = [0.5f32, -0.5, 1.5, -1.5, 2.5, -2.5, 0.499_999_97, -0.499_999_97, 32767.5, -32768.5, 32766.5, 1e9, -1e9]; + let all = special.into_iter().chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).chain((0..=u32::MAX).step_by(9973).map(f32::from_bits)); + for x in all { + assert_eq!(round_i16(x), x.round() as i16, "{x:e}"); + } + } + const PINNED: [u64; 4] = [0x52ba_772a_589c_1430, 0x013f_8364_821f_1dde, 0xb2a3_b5e5_aef3_7402, 0x08df_d6dc_aa2f_1c78]; + #[test] + fn grayscale_and_quality_monotone() { + let (w, h) = (300, 200); + let src: Vec = (0..w * h).map(|i| ((i % w) * 255 / w) as u8 ^ ((i / w) as u8 & 0x10)).collect(); + let lo = encode(&src, w, h, 1, 30, ChromaSubsampling::S444, &[]); + let hi = encode(&src, w, h, 1, 95, ChromaSubsampling::S444, &[]); + assert!(lo.len() < hi.len()); + let px = jpeg_decoder::Decoder::new(&hi[..]).decode().unwrap(); + assert!(psnr(&src, &px) > 35.0); + } +} diff --git a/crates/jpeg/src/lib.rs b/crates/jpeg/src/lib.rs index 185bf3ec55..50e1bd6253 100644 --- a/crates/jpeg/src/lib.rs +++ b/crates/jpeg/src/lib.rs @@ -1,6 +1,5 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! Clean-room decoder for the JPEG processes most Rust JPEG decoders don't handle, written from -//! ITU-T T.81 (ISO/IEC 10918-1). +//! Clean-room JPEG decoding and baseline encoding, written from ITU-T T.81 (ISO/IEC 10918-1). //! //! [`decode`] supports these frames: //! @@ -1703,3 +1702,7 @@ pub use bands::{Band, Bands, Reader}; #[cfg(test)] mod tests; + +/// Baseline JPEG encoder (8-bit, Huffman-coded sequential DCT). +mod encode; +pub use encode::{ChromaSubsampling, EncodeError, encode_baseline}; diff --git a/crates/kra/README.md b/crates/kra/README.md index 363455bdf4..582a0117dc 100644 --- a/crates/kra/README.md +++ b/crates/kra/README.md @@ -31,6 +31,7 @@ here. There is no writer. | `` nodes | 8192 (`MAX_NODES`) | | `maindoc.xml` | 32 MiB, 512 levels of nesting, no internal DTD subset | | A pixel file, inflated | 1 GiB (`MAX_LAYER_FILE`) | +| All entries read from one archive | 4 GiB (`MAX_TOTAL`) | | ICC profile | 16 MiB | | Tile | 1024 × 1024 px, 64 bytes per pixel, header lines of 256 bytes | diff --git a/crates/kra/src/lib.rs b/crates/kra/src/lib.rs index f59bd95cdc..e2dfb1f645 100644 --- a/crates/kra/src/lib.rs +++ b/crates/kra/src/lib.rs @@ -56,6 +56,10 @@ pub const MAX_MAINDOC: usize = 32 << 20; pub const MAX_LAYER_FILE: usize = 1 << 30; /// Most entries the archive may declare; checked before the archive is indexed. pub const MAX_ENTRIES: u64 = 100_000; +/// Most bytes all the entries read from one archive may expand to together. Each pixel file may be +/// [`MAX_LAYER_FILE`] on its own, so without a total a document of many layers could spend far more +/// than one open should. +pub const MAX_TOTAL: u64 = 4 << 30; /// Largest ICC profile. pub const MAX_ICC: usize = 16 << 20; /// Deepest element nesting of `maindoc.xml`. @@ -287,8 +291,13 @@ pub struct Archive<'a> { impl<'a> Archive<'a> { /// Opens the archive, checks its `mimetype` and reads `maindoc.xml`. pub fn open(bytes: &'a [u8]) -> Result> { - let mut zip = - craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: u64::MAX }).map_err(zip_error)?; + Self::open_with(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: MAX_TOTAL }) + } + + /// [`Archive::open`] with explicit zip limits, so a test can set a small document-wide total + /// ([`MAX_TOTAL`] is what [`Archive::open`] passes). + pub(crate) fn open_with(bytes: &'a [u8], limits: craft_zip::Limits) -> Result> { + let mut zip = craft_zip::Archive::open(bytes, limits).map_err(zip_error)?; // `zip` keeps one entry of a repeated name; which one the writer meant is not known. if zip.has_duplicate_names() { return Err(invalid("two entries of the archive share a name")); diff --git a/crates/kra/src/tests.rs b/crates/kra/src/tests.rs index 31656e4e19..b6dfd4b720 100644 --- a/crates/kra/src/tests.rs +++ b/crates/kra/src/tests.rs @@ -386,6 +386,23 @@ fn an_archive_declaring_too_many_entries_is_refused_before_it_is_indexed() { ); } +/// Every entry read is charged to one document-wide total: each pixel file may be +/// [`MAX_LAYER_FILE`] on its own, but a document with many of them still has one budget. +#[test] +fn pixel_files_share_one_document_wide_budget() { + let doc = maindoc("RGBA", ""); + // `layer_file("x")` reads `/layers/x`. + let (first, second) = ("img/layers/x", "img/layers/y"); + let files: Vec<(&str, Vec)> = vec![(first, vec![3; 64]), (second, vec![4; 64])]; + let bytes = archive(&doc, &files); + // The mimetype and maindoc reads are charged too: room for one 64-byte pixel file and 16 bytes. + let total = doc.len() as u64 + MIMETYPE.len() as u64 + 64 + 16; + let limits = craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: total }; + let mut archive = Archive::open_with(&bytes, limits).unwrap(); + assert_eq!(archive.layer_file("x").unwrap().unwrap(), vec![3; 64]); + assert!(matches!(archive.layer_file("y"), Err(Error::Invalid(_))), "the second pixel file is past the total"); +} + /// Two entries of one name: `zip` keeps one, and which one the writer meant is not known. #[test] fn two_entries_of_one_name_are_refused() { diff --git a/crates/media/README.md b/crates/media/README.md index 8eca6ecb5c..b7ad5be7ad 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -243,6 +243,10 @@ let bytes = w.finish_faststart()?.into_inner(); // or finish() for moov-at-end `ipcm`/`fpcm` + `pcmC` in MP4. A PCM `write_sample` call can hold any whole number of frames, and the track timescale must equal the sample rate. - Edit lists: set `TrackConfig::edits` explicitly, or use `media_start` to get a single edit. +- Audio pre-roll: `TrackConfig::roll_distance` puts every sample in a `roll` sample group (`sgpd` + + `sbgp`). Set -1 for AAC with `media_start` at the priming: Apple's decoders apply that edit only + when the track has the group. +- A file starts at the writer's position: chunk offsets count from there. - Timecode: `add_timecode_track(video, TimecodeConfig, start_frame)` adds a `tmcd` track (with `gmhd`) and a `tref/tmcd` link from the video track. - `WriterOptions::metadata` writes `©xxx` text atoms to `udta`. diff --git a/crates/media/src/isobmff/mux.rs b/crates/media/src/isobmff/mux.rs index e38186e9f4..bcadfbaeb1 100644 --- a/crates/media/src/isobmff/mux.rs +++ b/crates/media/src/isobmff/mux.rs @@ -51,11 +51,17 @@ pub struct TrackConfig { pub media_start: Option, /// `hdlr` name; a sensible default is used when `None`. pub handler_name: Option, + /// Audio pre-roll: puts every sample in a `roll` sample group (`sgpd` + `sbgp`, ISO/IEC + /// 14496-12 §10.1) with this roll distance, the number of samples a decoder must decode before + /// (negative) a sample for its output to be correct; -1 for AAC. Apple's decoders take an AAC + /// track's priming from the edit list only when the track has this group. Written by + /// [`Mp4Writer`]; [`FragmentedWriter`] ignores it. + pub roll_distance: Option, } impl TrackConfig { pub fn new(entry: SampleEntry, timescale: u32) -> Self { - TrackConfig { entry, timescale, language: "und".into(), edits: Vec::new(), media_start: None, handler_name: None } + TrackConfig { entry, timescale, language: "und".into(), edits: Vec::new(), media_start: None, handler_name: None, roll_distance: None } } } @@ -543,6 +549,23 @@ fn write_stbl(b: &mut BoxBuf, t: &WTrack, qt: bool, shift: u64, force_co64: bool } } b.end(m); + if let Some(distance) = t.cfg.roll_distance + && sample_count > 0 + { + // One description, which every sample maps to. + let m = b.start_full(b"sgpd", 1, 0); + b.bytes(b"roll"); + b.u32(2); + b.u32(1); + b.i16(distance); + b.end(m); + let m = b.start_full(b"sbgp", 0, 0); + b.bytes(b"roll"); + b.u32(1); + b.u32(sample_count); + b.u32(1); + b.end(m); + } b.end(stbl); Ok(()) } @@ -592,12 +615,21 @@ fn validate_track(entry: &SampleEntry, timescale: u32) -> Result> { Ok(None) } +/// The position after `bytes` more. A writer that takes bytes past the last position a file can +/// have is an error here, not an overflow. +fn advance(pos: u64, bytes: usize) -> Result { + pos.checked_add(bytes as u64).ok_or_else(|| Error::Mux("the file would end past the last position".into())) +} + /// Progressive MP4/MOV writer: `ftyp`, then one `mdat` streamed to `W`, then `moov` at [`finish`](Self::finish) /// (or moved in front of `mdat` by [`finish_faststart`](Self::finish_faststart)). pub struct Mp4Writer { w: W, opts: WriterOptions, tracks: Vec, + /// The writer's position when the file was begun: chunk offsets count from here, the first + /// byte of the file, wherever in the writer that is. + start: u64, /// Offset of the placeholder box (8 bytes) preceding the mdat header. pad_pos: u64, mdat_pos: u64, @@ -608,18 +640,22 @@ pub struct Mp4Writer { } impl Mp4Writer { - /// Start a file: writes `ftyp`, a placeholder box and the `mdat` header. + /// Start a file at the writer's current position: writes `ftyp`, a placeholder box and the + /// `mdat` header. pub fn new(mut w: W, opts: WriterOptions) -> Result { let start = w.stream_position()?; let mut b = BoxBuf::new(); write_ftyp(&mut b, opts.brand); - let pad_pos = start + b.len() as u64; + let pad = b.len() as u64; b.leaf(if opts.brand == Brand::Mov { b"wide" } else { b"free" }, &[]); - let mdat_pos = start + b.len() as u64; + let mdat = b.len() as u64; b.leaf(b"mdat", &[]); + // A writer positioned at the very end of what a position can count has no room for the + // header; the positions below are sums that would overflow. + let pos = start.checked_add(b.len() as u64).ok_or_else(|| Error::Mux("the writer's position leaves no room for a file".into()))?; + let (pad_pos, mdat_pos) = (start + pad, start + mdat); w.write_all(&b.buf)?; - let pos = start + b.len() as u64; - Ok(Mp4Writer { w, opts, tracks: Vec::new(), pad_pos, mdat_pos, pos, last_track: None, chapters: Vec::new() }) + Ok(Mp4Writer { w, opts, tracks: Vec::new(), start, pad_pos, mdat_pos, pos, last_track: None, chapters: Vec::new() }) } /// Add a track; returns its index (track ids are index + 1). @@ -708,8 +744,8 @@ impl Mp4Writer { return Err(too_many_samples()); } self.w.write_all(s.data)?; - let offset = self.pos; - self.pos += s.data.len() as u64; + let offset = self.pos - self.start; + self.pos = advance(self.pos, s.data.len())?; let contiguous = self.last_track == Some(track); self.last_track = Some(track); let tr = &mut self.tracks[track]; @@ -749,8 +785,8 @@ impl Mp4Writer { }; let d = rescale(vd, vts, tts).max(tc_dur as u64).min(u32::MAX as u64) as u32; self.w.write_all(&start.to_be_bytes())?; - let off = self.pos; - self.pos += 4; + let off = self.pos - self.start; + self.pos = advance(self.pos, 4)?; self.last_track = None; let t = &mut self.tracks[i].t; t.stts.push((1, d)); @@ -807,13 +843,13 @@ impl Mp4Writer { } let id = self.tracks.len() as u32 + 1; let mut t = Tables::new(); - let off = self.pos; + let off = self.pos - self.start; for (i, c) in self.chapters.iter().enumerate() { let end = self.chapters.get(i + 1).map_or(duration, |n| n.start); let d = u32::try_from(end.saturating_sub(c.start)).map_err(|_| Error::Mux("chapter longer than 2^32 movie ticks".into()))?; let data = text_sample(&c.title); self.w.write_all(&data)?; - self.pos += data.len() as u64; + self.pos = advance(self.pos, data.len())?; Tables::push_run(&mut t.stts, 1, d); Tables::push_run(&mut t.ctts, 1, 0); t.sizes.push(data.len() as u32); @@ -1341,4 +1377,105 @@ mod tests { } assert_eq!(t.sync_sample_before(5), 3); } + + /// `roll_distance` puts every sample in one `roll` group; without it, or without samples, + /// the track has no sample group. + #[test] + fn roll_distance_is_a_sample_group_over_every_sample() { + let file = |roll: Option, samples: u32| { + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); + let mut cfg = TrackConfig::new(SampleEntry::aac(vec![0x11, 0x90], 2, 48_000), 48_000); + cfg.roll_distance = roll; + let t = w.add_track(cfg).unwrap(); + for _ in 0..samples { + w.write_sample(t, WriteSample { data: &[0; 8], duration: 1024, composition_offset: 0, is_sync: true }).unwrap(); + } + w.finish().unwrap().into_inner() + }; + let out = file(Some(-1), 5); + let f = crate::isobmff::open(out.as_slice()).unwrap(); + let groups = &f.tracks[0].sample_groups; + assert_eq!(groups.len(), 1); + assert_eq!((groups[0].grouping_type, groups[0].runs.as_slice()), (crate::isobmff::FourCc(*b"roll"), [(5, 1)].as_slice())); + assert_eq!(groups[0].descriptions, [(-1i16).to_be_bytes().to_vec()]); + assert_eq!(f.tracks[0].samples.len(), 5); + for out in [file(None, 5), file(Some(-1), 0)] { + assert!(crate::isobmff::open(out.as_slice()).unwrap().tracks[0].sample_groups.is_empty()); + } + // The boxes as ISO/IEC 14496-12 §8.9 has them (and ffmpeg writes them): `sgpd` version 1 + // with a default description length of 2, one description; `sbgp` version 0, one run. + let sgpd = [&26u32.to_be_bytes()[..], b"sgpd", &[1, 0, 0, 0], b"roll", &[0, 0, 0, 2, 0, 0, 0, 1, 0xFF, 0xFF]].concat(); + let sbgp = [&28u32.to_be_bytes()[..], b"sbgp", &[0, 0, 0, 0], b"roll", &[0, 0, 0, 1, 0, 0, 0, 5, 0, 0, 0, 1]].concat(); + let both = [sgpd, sbgp].concat(); + assert!(out.windows(both.len()).any(|w| w == both)); + } + + /// A writer positioned where the header's end would pass `u64::MAX` is refused, not overflowed. + #[test] + fn a_writer_at_the_end_of_the_position_range_is_refused() { + for back in [0, 1, 10, 27] { + let mut bytes = [0u8; 8]; + let mut sink = Cursor::new(&mut bytes[..]); + sink.set_position(u64::MAX - back); + assert!(matches!(Mp4Writer::new(sink, WriterOptions::new(Brand::Mp4)), Err(Error::Mux(_))), "{back} before the end"); + } + } + + /// A writer that keeps taking bytes where positions end makes writing fail, not overflow. + #[test] + fn samples_past_the_last_position_are_refused() { + struct Endless(u64); + impl Write for Endless { + fn write(&mut self, data: &[u8]) -> std::io::Result { + self.0 = self.0.wrapping_add(data.len() as u64); + Ok(data.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + impl Seek for Endless { + fn seek(&mut self, _: SeekFrom) -> std::io::Result { + Ok(self.0) + } + } + let mut w = Mp4Writer::new(Endless(u64::MAX - 100), WriterOptions::new(Brand::Mp4)).unwrap(); + let v = w.add_track(TrackConfig::new(avc_entry(), 1000)).unwrap(); + let sample = WriteSample { data: &[0; 40], duration: 40, composition_offset: 0, is_sync: true }; + w.write_sample(v, sample).unwrap(); + assert!(matches!(w.write_sample(v, sample), Err(Error::Mux(_)))); + } + + /// A file begun in the middle of a writer is a file from there: its chunk offsets count from + /// its own first byte, with `moov` at the end or in front, a timecode track and chapters. + #[test] + fn a_file_begun_mid_writer_has_offsets_from_its_start() { + let file = |prefix: usize, faststart: bool| { + let mut sink = Cursor::new(vec![0xAA; prefix]); + sink.set_position(prefix as u64); + let mut opts = WriterOptions::new(Brand::Mov); + opts.chapters = vec![Chapter { start: 0, title: "one".into() }]; + let mut w = Mp4Writer::new(sink, opts).unwrap(); + let v = w.add_track(TrackConfig::new(avc_entry(), 1000)).unwrap(); + let tc = TimecodeConfig { timescale: 1000, frame_duration: 40, frames_per_second: 25, ..Default::default() }; + w.add_timecode_track(v, tc, 7).unwrap(); + for i in 0..4u8 { + w.write_sample(v, WriteSample { data: &[i + 1; 10], duration: 40, composition_offset: 0, is_sync: true }).unwrap(); + } + let out = if faststart { w.finish_faststart() } else { w.finish() }.unwrap(); + assert_eq!(out.position(), out.get_ref().len() as u64); + out.into_inner() + }; + for faststart in [false, true] { + let (plain, offset) = (file(0, faststart), file(100, faststart)); + assert!(offset[..100].iter().all(|&b| b == 0xAA)); + assert!(offset[100..] == plain, "faststart {faststart}"); + let f = crate::isobmff::open(plain.as_slice()).unwrap(); + assert_eq!(f.tracks.len(), 3); + for i in 0..4 { + assert_eq!(f.read_sample(plain.as_slice(), 0, i).unwrap(), vec![i as u8 + 1; 10]); + } + assert_eq!(f.read_sample(plain.as_slice(), 1, 0).unwrap(), 7u32.to_be_bytes()); + } + } } diff --git a/crates/midi/src/smf.rs b/crates/midi/src/smf.rs index 442e27f0f2..fb6683a300 100644 --- a/crates/midi/src/smf.rs +++ b/crates/midi/src/smf.rs @@ -189,13 +189,14 @@ pub const MAX_WARNINGS: usize = 32; /// short is not believed when the track's End of Track says otherwise: the next chunk is looked /// for where the track's events ended; /// - bytes that are no chunk are skipped up to the next `MTrk`, and trailing bytes are ignored; -/// - past [`MAX_TRACKS`] tracks the rest is left out; +/// - past [`MAX_TRACKS`] tracks the rest is left out; this and the event limit set +/// [`LenientRead::over_limit`]; /// - lyrics are counted in a warning (they are not kept); a format-2 file gets a warning that its /// tracks are read side by side. pub fn read_smf_lenient(bytes: &[u8]) -> Result { let mut warnings = Vec::new(); let (smf, extra) = read(bytes, Some(&mut warnings))?; - Ok(LenientRead { smf, warnings, instruments: extra.instruments, end: extra.end }) + Ok(LenientRead { smf, warnings, instruments: extra.instruments, end: extra.end, over_limit: extra.over_limit }) } /// What [`read_smf_lenient`] makes of a file. @@ -209,12 +210,18 @@ pub struct LenientRead { pub instruments: Vec, /// The last tick any track reaches: its End of Track, or where its events stop. pub end: i64, + /// Whether the file goes past [`MAX_EVENTS`] events or [`MAX_TRACKS`] tracks, so what lies past + /// the limit was left out. It is set even when the warnings are already full, so a caller that + /// refuses such files (as [`read_smf`] does) can tell without reading the warnings. + pub over_limit: bool, } -/// What the reader finds beyond [`Smf`]: instrument names per kept track, and the end tick. +/// What the reader finds beyond [`Smf`]: instrument names per kept track, the end tick, and +/// whether a limit left part of the file out. struct Extra { instruments: Vec, end: i64, + over_limit: bool, } fn warn(warnings: &mut Option<&mut Vec>, what: String) { @@ -262,6 +269,7 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex let (mut tracks, mut instruments) = (Vec::new(), Vec::new()); let mut event_budget = MAX_EVENTS; let (mut end, mut seen, mut lyrics) = (0i64, 0usize, 0usize); + let mut over_limit = false; while !cur.is_empty() { let chunk_at = cur.at(); @@ -306,6 +314,7 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex return Err(MidiError::TooManyTracks(MAX_TRACKS)); } warn(&mut warnings, format!("more than {MAX_TRACKS} tracks: the rest was left out")); + over_limit = true; break; } let (body_at, body_start) = (cur.at(), cur.pos); @@ -319,7 +328,10 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex end = end.max(read.end); match read.stop { Some(e) if !lenient => return Err(e), - Some(e) => warn(&mut warnings, format!("track {seen} {}: what came before is kept", stop_reason(&e))), + Some(e) => { + over_limit |= matches!(e, MidiError::TooManyEvents(_)); + warn(&mut warnings, format!("track {seen} {}: what came before is kept", stop_reason(&e))); + } None if !read.ended && lenient => warn(&mut warnings, format!("track {seen} has no End of Track: what came before is kept")), None => {} } @@ -363,7 +375,7 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex Ok(( Smf { format, tracks, tempos: globals.tempos, meters: globals.meters, markers: globals.markers, key_sigs: globals.key_sigs }, - Extra { instruments, end }, + Extra { instruments, end, over_limit }, )) } diff --git a/crates/midi/tests/it/lenient.rs b/crates/midi/tests/it/lenient.rs index 3d02995bc1..0556c3859c 100644 --- a/crates/midi/tests/it/lenient.rs +++ b/crates/midi/tests/it/lenient.rs @@ -33,8 +33,8 @@ const TWO: &[u8] = &[0x00, 0x91, 62, 100, 0x60, 0x81, 62, 0]; #[test] fn a_sound_file_reads_the_same_either_way_without_warnings() { let good = file(1, 96, &[ONE, TWO]); - let LenientRead { smf, warnings, end, .. } = read_smf_lenient(&good).unwrap(); - assert_eq!((keys(&smf), warnings.len()), (vec![vec![60], vec![62]], 0)); + let LenientRead { smf, warnings, end, over_limit, .. } = read_smf_lenient(&good).unwrap(); + assert_eq!((keys(&smf), warnings.len(), over_limit), (vec![vec![60], vec![62]], 0, false)); assert_eq!(smf, read_smf(&good).unwrap()); assert_eq!(end, 960, "the End of Track tick, at 960 ticks a quarter"); } @@ -122,15 +122,34 @@ fn a_file_of_any_size_is_read_into_a_bounded_number_of_events_and_warnings() { // Three bytes a note-on under running status: more events than are read. let mut body = vec![0x00, 0x90, 60, 100]; body.extend((0..MAX_EVENTS + 1000).flat_map(|i| [0x00, (i % 128) as u8, 1])); - let LenientRead { smf, warnings, .. } = read_smf_lenient(&file(1, 96, &[&body])).unwrap(); + let LenientRead { smf, warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &[&body])).unwrap(); assert_eq!(smf.tracks[0].sequence.notes.len(), MAX_EVENTS); assert!(warnings.iter().any(|w| w.contains("more events")), "{warnings:?}"); + assert!(over_limit, "the event limit left events out"); // Tracks of nothing, by the thousand: the count stops the reading. - let LenientRead { smf, warnings, .. } = read_smf_lenient(&file(1, 96, &vec![&[][..]; MAX_TRACKS + 5])).unwrap(); + let LenientRead { smf, warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &vec![&[][..]; MAX_TRACKS + 5])).unwrap(); assert!(smf.tracks.len() < MAX_TRACKS && warnings.iter().any(|w| w.contains("tracks"))); - // Every track damaged: never more than MAX_WARNINGS words. - let LenientRead { warnings, .. } = read_smf_lenient(&file(1, 96, &vec![&[0x00, 60][..]; 100])).unwrap(); + assert!(over_limit, "the track limit left tracks out"); + // Every track damaged: never more than MAX_WARNINGS words, and no limit was reached. + let LenientRead { warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &vec![&[0x00, 60][..]; 100])).unwrap(); assert_eq!(warnings.len(), MAX_WARNINGS); + assert!(!over_limit); +} + +#[test] +fn a_limit_reached_after_the_warnings_are_full_is_still_reported() { + // MAX_WARNINGS damaged tracks fill the warnings; the track after them holds more events than are + // read, so its warning is dropped, and over_limit is what says the file was cut. + let mut body = vec![0x00, 0x90, 60, 100]; + body.extend((0..MAX_EVENTS + 1000).flat_map(|i| [0x00, (i % 128) as u8, 1])); + let mut tracks = vec![&[0x00, 60][..]; MAX_WARNINGS]; + tracks.push(&body); + let LenientRead { warnings, over_limit, .. } = read_smf_lenient(&file(1, 96, &tracks)).unwrap(); + assert_eq!(warnings.len(), MAX_WARNINGS); + assert!(!warnings.iter().any(|w| w.contains("more events")), "the test needs the limit's warning dropped: {warnings:?}"); + assert!(over_limit); + // The strict reader stops at the first damaged track, before the limit. + assert!(!matches!(read_smf(&file(1, 96, &tracks)), Err(MidiError::TooManyEvents(_)) | Ok(_))); } #[test] diff --git a/crates/ora/README.md b/crates/ora/README.md index 70cdbd9320..488268b3c2 100644 --- a/crates/ora/README.md +++ b/crates/ora/README.md @@ -29,6 +29,7 @@ means. `SVG_COMPOSITE_OPS` lists the names the specification defines. | Elements under the root stack | 8192 (`MAX_NODES`) | | `stack.xml` | 16 MiB, 512 levels of nesting, no document type declaration | | An entry | the caller's limit; `MAX_ENTRY` (512 MiB) is the suggested one for a layer image | +| All entries read from one archive | 4 GiB (`MAX_TOTAL`) | ## ZIP diff --git a/crates/ora/src/lib.rs b/crates/ora/src/lib.rs index 69d494d0dc..f39d13f061 100644 --- a/crates/ora/src/lib.rs +++ b/crates/ora/src/lib.rs @@ -51,6 +51,10 @@ pub const MAX_STACK_XML: usize = 16 << 20; pub const MAX_ENTRY: usize = 512 << 20; /// Most entries the archive may declare; checked before the archive is indexed. pub const MAX_ENTRIES: u64 = 100_000; +/// Most bytes all the entries read from one archive may expand to together. Each layer image may +/// be [`MAX_ENTRY`] on its own, so without a total a document of many layers could spend far more +/// than one open should. +pub const MAX_TOTAL: u64 = 4 << 30; /// Deepest element nesting of `stack.xml`. pub const MAX_XML_DEPTH: usize = 512; @@ -363,8 +367,13 @@ pub struct Archive<'a> { impl<'a> Archive<'a> { /// Opens the archive, checks its `mimetype` and reads `stack.xml`. pub fn open(bytes: &'a [u8]) -> Result> { - let mut zip = - craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: u64::MAX }).map_err(zip_error)?; + Self::open_with_total(bytes, MAX_TOTAL) + } + + /// [`Archive::open`], allowing the entries read from the archive to expand to + /// `max_total_bytes` together ([`MAX_TOTAL`] is the default). + pub(crate) fn open_with_total(bytes: &'a [u8], max_total_bytes: u64) -> Result> { + let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes }).map_err(zip_error)?; // `zip` keeps one entry of a repeated name; which one the writer meant is not known. if zip.has_duplicate_names() { return Err(invalid("two entries of the archive share a name")); diff --git a/crates/ora/src/tests.rs b/crates/ora/src/tests.rs index cfaac7c418..f8773f79c6 100644 --- a/crates/ora/src/tests.rs +++ b/crates/ora/src/tests.rs @@ -315,6 +315,19 @@ fn an_archive_declaring_too_many_entries_is_refused_before_it_is_indexed() { ); } +/// Every entry read is charged to one document-wide total, so an archive of many individually +/// allowed entries cannot spend an unbounded amount of memory in one open. +#[test] +fn entries_are_charged_to_one_document_wide_total() { + let stack = ""; + let bytes = archive(stack, &[("a.png", vec![1; 100]), ("b.png", vec![2; 100])]); + // Room for `stack.xml` and one image, not two. + let mut a = Archive::open_with_total(&bytes, stack.len() as u64 + 120).unwrap(); + assert_eq!(a.entry("a.png", MAX_ENTRY).unwrap().unwrap(), vec![1; 100]); + let err = a.entry("b.png", MAX_ENTRY).unwrap_err(); + assert!(matches!(&err, Error::Invalid(m) if m.contains("b.png") && m.contains("may expand to")), "{err:?}"); +} + /// Two entries of one name: `zip` keeps one, and which one the writer meant is not known. #[test] fn two_entries_of_one_name_are_refused() { diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index ff94c6d8e8..266297f423 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -17,6 +17,7 @@ interpret = ["read", "dep:hayro-interpret"] paths = ["interpret", "dep:kurbo"] raster = ["interpret", "dep:hayro", "dep:bytemuck"] write = ["dep:krilla", "dep:thiserror"] +write-svg = ["write", "dep:craft-svg", "dep:krilla-svg", "dep:usvg", "craft-svg/tree-text"] write-pdf = ["write", "krilla/pdf"] write-raster = ["dep:flate2", "dep:roxmltree"] write-simple-text = ["write", "krilla/simple-text"] @@ -30,6 +31,9 @@ hayro-interpret = { workspace = true, optional = true } hayro = { workspace = true, optional = true } bytemuck = { workspace = true, optional = true } krilla = { workspace = true, optional = true } +craft-svg = { workspace = true, optional = true } +krilla-svg = { version = "=0.8.1", optional = true } +usvg = { version = "=0.47.0", features = ["text"], optional = true } thiserror = { workspace = true, optional = true } flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"], optional = true } roxmltree = { version = "0.21", optional = true } diff --git a/crates/pdf/README.md b/crates/pdf/README.md index 18d3d25a9b..210b798495 100644 --- a/crates/pdf/README.md +++ b/crates/pdf/README.md @@ -10,6 +10,7 @@ No feature is enabled by default. | `interpret` | `read` plus an app-owned Device interpreter, fonts and CMaps | | `raster` | `interpret` plus premultiplied RGBA8 rendering | | `write` | Guarded Krilla authoring; no shared reader dependency | +| `write-svg` | `write` plus bounded SVG-to-PDF vector drawing | | `write-pdf` | `write` plus Krilla's embedded-PDF support | | `write-simple-text` | `write` plus Krilla's optional text shaper and `draw_text` | | `filters` | The `/Filter` chain for editing and writing PDF files: decode and encode, with limits and accounting. No reader or writer dependency | @@ -201,9 +202,12 @@ PDF files. The reader decrypts on its own and does not use it. It covers revisio block is ignored and bad padding is left in. - `permissions()` gives the `/P` flags; for R5/R6 a permission counts only when `/Perms` grants it too. Owners have every permission. -- `create(&NewEncryption, id0)` builds the `/Encrypt` values for RC4-40, RC4-128, AES-128 or - AES-256. The caller supplies 32 bytes of entropy (`seed`), so the module needs no OS access - and builds for the web. `file_id` derives a file identifier from the same seed. +- `create(&NewEncryption, id0)` builds the `/Encrypt` values for AES-128 or AES-256. It refuses + the legacy RC4-40 and RC4-128 schemes, because RC4 is broken (RFC 7465); `create_legacy` + writes those, for a file that must stay readable by an old reader. `Document::set_encryption` + refuses them too, with `set_encryption_legacy` as the explicit way in. The caller supplies 32 + bytes of entropy (`seed`), so the module needs no OS access and builds for the web. `file_id` + derives a file identifier from the same seed. - `EncryptDict` holds the dictionary's values. The caller reads them from, and writes them to, its own object model; the module does not parse PDF syntax. Keys and prepared passwords are zeroized when dropped. @@ -240,6 +244,9 @@ serialization uses the same backend version as before extraction. It provides: refuses it. Apps build URI links with it instead of `backend::action::LinkAction`, so a link target from someone else's document becomes a PDF link only when it is an `http`/`https` URL with a host or a `mailto` address. A refused target writes no link annotation. +- `write::svg` (feature `write-svg`): bounded SVG/SVGZ text preflight, data-only image + resolution, and vector drawing through krilla-svg. Callers provide font and fallback options; + the adapter enforces input, nesting, embedded-image, destination-area and filter budgets. - `safe_url` (crate root, any feature): the same rule, for apps that open links themselves, such as a slide show. diff --git a/crates/pdf/examples/cos_protect.rs b/crates/pdf/examples/cos_protect.rs index c40bccdce5..b12c700cfc 100644 --- a/crates/pdf/examples/cos_protect.rs +++ b/crates/pdf/examples/cos_protect.rs @@ -22,7 +22,8 @@ fn main() { _ => craft_pdf::cos::Algorithm::Aes256, }; let mut doc = craft_pdf::cos::Document::open(std::sync::Arc::new(std::fs::read(input).unwrap())).unwrap(); - doc.set_encryption(&craft_pdf::cos::NewEncryption { + // `rc4-40` and `rc4-128` are the legacy schemes, which `set_encryption` refuses. + doc.set_encryption_legacy(&craft_pdf::cos::NewEncryption { algorithm, user_password: user, owner_password: owner, diff --git a/crates/pdf/src/cos/document/open.rs b/crates/pdf/src/cos/document/open.rs index 46a6423a9d..4991412ce3 100644 --- a/crates/pdf/src/cos/document/open.rs +++ b/crates/pdf/src/cos/document/open.rs @@ -414,7 +414,20 @@ impl Document { /// Protect the document with a password (§7.6.4). Takes effect on the next save, which is /// always a full rewrite. Returns the handler (authenticated as owner). + /// + /// The legacy RC4 schemes are refused (RC4 is broken, `RFC 7465`): [`Self::set_encryption_legacy`] + /// writes them for a file an old reader must open. pub fn set_encryption(&mut self, params: &crate::crypt::NewEncryption) -> Result<(), CosError> { + self.set_encryption_with(params, false) + } + + /// [`Self::set_encryption`] with the legacy RC4-40 and RC4-128 schemes allowed. Pass it only + /// for a file that must stay readable by a reader without AES. + pub fn set_encryption_legacy(&mut self, params: &crate::crypt::NewEncryption) -> Result<(), CosError> { + self.set_encryption_with(params, true) + } + + fn set_encryption_with(&mut self, params: &crate::crypt::NewEncryption, legacy: bool) -> Result<(), CosError> { // The file identifier is part of the key; make sure it exists and keep it. let id = self.trailer.get(b"ID").map(|id| self.resolve(id)); let id0 = match id.as_deref() { @@ -426,7 +439,8 @@ impl Document { id } }; - let h = crate::crypt::create(params, &id0).map_err(|e| CosError::Security(e.to_string()))?; + let built = if legacy { crate::crypt::create_legacy(params, &id0) } else { crate::crypt::create(params, &id0) }; + let h = built.map_err(|e| CosError::Security(e.to_string()))?; let d = h.dict(); let s = |b: &[u8]| Object::String(crate::cos::PdfString { bytes: b.to_vec(), hex: true }); let mut e = Dict::new(); diff --git a/crates/pdf/src/crypt.rs b/crates/pdf/src/crypt.rs index 069627db92..c516fa86e1 100644 --- a/crates/pdf/src/crypt.rs +++ b/crates/pdf/src/crypt.rs @@ -283,7 +283,7 @@ impl SecurityHandler { /// different key is refused too. pub fn authenticate_owner(&self, id0: &[u8], password: &str) -> Result { let owner = Self::open(self.dict.clone(), id0, Some(password))?; - if owner.auth != Auth::Owner || owner.key != self.key { + if owner.auth != Auth::Owner || !same(owner.key.as_slice(), self.key.as_slice()) { return Err(CryptError::WrongPassword); } Ok(owner) @@ -539,6 +539,12 @@ fn u_value_r4(d: &EncryptDict, id0: &[u8], key: &[u8]) -> Vec { x } +/// Whether `a` and `b` are equal, in time that depends only on their lengths: password-derived +/// digests, keys and verifiers are compared without stopping at the first differing byte. +fn same(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + /// Algorithm 6: authenticate a user password; returns the file key. /// /// Some producers ignore `/EncryptMetadata false` when deriving the key (they omit the @@ -549,7 +555,7 @@ fn user_key_r4(d: &EncryptDict, id0: &[u8], pw: &[u8]) -> Option= n && u[..n] == d.u[..n]).then_some(key) + (d.u.len() >= n && same(&u[..n], &d.u[..n])).then_some(key) }; check(d).or_else(|| (d.r >= 4 && !d.encrypt_metadata).then(|| check(&EncryptDict { encrypt_metadata: true, ..d.clone() })).flatten()) } @@ -636,7 +642,8 @@ fn key_r6(d: &EncryptDict, pw: &[u8], owner: bool) -> Result Result bool { + matches!(self, Algorithm::Rc4_40 | Algorithm::Rc4_128) + } +} + /// A password as [`create`] prepares it: for R2–R4 its PDFDocEncoding (characters it lacks /// dropped), at most 32 bytes; for R6 its SASLprep (RFC 4013: soft hyphens and the like removed, /// other spaces made plain, then NFKC; the password as given if SASLprep refuses it), in UTF-8, @@ -725,7 +740,23 @@ pub fn file_id(seed: &[u8; 32]) -> Vec { } /// Build the `/Encrypt` values and an authenticated (owner) handler for a new encryption. +/// +/// The legacy RC4 schemes are refused, because RC4 is broken (`RFC 7465`) and a file written with +/// it protects nothing: [`create_legacy`] is the explicit way to write them. pub fn create(params: &NewEncryption, id0: &[u8]) -> Result { + if params.algorithm.is_legacy() { + return Err(CryptError::Unsupported("RC4 encryption is legacy (RFC 7465); use create_legacy for a file an old reader must open".into())); + } + create_any(params, id0) +} + +/// [`create`] without the RC4 gate: writes RC4-40 and RC4-128 too. For a file that must stay +/// readable by a reader without AES, and for tests that read and write every algorithm. +pub fn create_legacy(params: &NewEncryption, id0: &[u8]) -> Result { + create_any(params, id0) +} + +fn create_any(params: &NewEncryption, id0: &[u8]) -> Result { // R2 reserves bits 7-32; later revisions reserve bits 7-8 and 13-32. // Reserved bits must be 1, and bits 1-2 must be 0 (§7.6.4.2). let reserved = if params.algorithm == Algorithm::Rc4_40 { !0x3F } else { !0xFFF | 0xC0 }; diff --git a/crates/pdf/src/crypt/tests.rs b/crates/pdf/src/crypt/tests.rs index 04bb7c61e5..08878c8be9 100644 --- a/crates/pdf/src/crypt/tests.rs +++ b/crates/pdf/src/crypt/tests.rs @@ -52,13 +52,45 @@ fn aes_padding_is_added_and_tolerantly_removed() { const ID: &[u8] = b"0123456789abcdef"; fn new(alg: Algorithm, user: &str, owner: &str, perms: i32) -> SecurityHandler { - create( + // These tests read and write every algorithm, RC4 included. + create_legacy( &NewEncryption { algorithm: alg, user_password: user, owner_password: owner, permissions: perms, encrypt_metadata: true, seed: [42; 32] }, ID, ) .unwrap() } +/// New files are not written with RC4: `create` refuses it, and the explicitly named +/// `create_legacy` is the only way to write it. +#[test] +fn create_refuses_rc4_unless_asked() { + let params = |algorithm| NewEncryption { + algorithm, + user_password: "user", + owner_password: "owner", + permissions: -1, + encrypt_metadata: true, + seed: [42; 32], + }; + for (alg, revision) in [(Algorithm::Rc4_40, 2), (Algorithm::Rc4_128, 3)] { + assert!(matches!(create(¶ms(alg), ID), Err(CryptError::Unsupported(_))), "{alg:?}"); + assert_eq!(create_legacy(¶ms(alg), ID).unwrap().dict().r, revision, "{alg:?}"); + } + for alg in [Algorithm::Aes128, Algorithm::Aes256] { + assert!(create(¶ms(alg), ID).is_ok(), "AES is not legacy: {alg:?}"); + } +} + +/// Every verifier check goes through this comparison: it reads both sides in full and a value +/// that merely starts the same never matches. +#[test] +fn verifier_comparison_reads_every_byte() { + assert!(super::same(b"", b"")); + assert!(super::same(b"0123456789abcdef", b"0123456789abcdef")); + assert!(!super::same(b"0123456789abcdef", b"0123456789abcdee"), "difference in the last byte"); + assert!(!super::same(b"0123456789abcdef", b"0123456789abcde"), "shorter value"); +} + const ALL: [Algorithm; 4] = [Algorithm::Rc4_40, Algorithm::Rc4_128, Algorithm::Aes128, Algorithm::Aes256]; #[test] diff --git a/crates/pdf/src/write.rs b/crates/pdf/src/write.rs index 8114327d44..924910e25a 100644 --- a/crates/pdf/src/write.rs +++ b/crates/pdf/src/write.rs @@ -15,6 +15,8 @@ const _: bool = backend::CRAFT_PRINT_COLOR; const _: bool = backend::CRAFT_OPTIONAL_CONTENT; pub mod print; +#[cfg(feature = "write-svg")] +pub mod svg; use backend::configure::{Archival, Configuration, ConfigurationBuilder, ConfigurationError, PdfVersion}; use backend::text::{Font, Tag}; diff --git a/crates/pdf/src/write/svg.rs b/crates/pdf/src/write/svg.rs new file mode 100644 index 0000000000..eb6542c0a3 --- /dev/null +++ b/crates/pdf/src/write/svg.rs @@ -0,0 +1,176 @@ +//! Bounded SVG parsing and vector drawing on a PDF surface. +//! +//! This adapter owns the usvg version required by krilla-svg. Callers pass their font and +//! fallback options, while this module checks input, embedded SVGs, and output/filter budgets +//! before converting SVG to PDF drawing operations. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use krilla_svg::SurfaceExt; + +pub use krilla_svg::SvgSettings; +pub use usvg; + +/// Resource limits for parsing SVG and drawing it to PDF. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// Maximum decoded bytes in one SVG document. + pub input_bytes: usize, + /// Maximum SVG element and reference depth. + pub depth: usize, + /// Maximum XML nodes in one document. + pub xml_nodes: u32, + /// Maximum total decoded bytes of embedded SVGs. + pub embedded_svg_bytes: usize, + /// Maximum number of embedded SVG documents nested within one another. + pub embedded_svg_depth: usize, + /// Maximum encoded bytes retained for embedded raster images. + pub embedded_image_bytes: usize, + /// Maximum PDF surface area, measured in 96 dpi pixels. + pub vector_pixels: u64, + /// Maximum raster pixels used by filters after `filter_scale` is applied. + pub filter_pixels: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { + input_bytes: 16 * 1024 * 1024, + depth: 64, + xml_nodes: 100_000, + embedded_svg_bytes: 32 * 1024 * 1024, + embedded_svg_depth: 4, + embedded_image_bytes: 32 * 1024 * 1024, + vector_pixels: 256_000_000, + filter_pixels: 256_000_000, + } + } +} + +/// Why an SVG could not be parsed or drawn within its limits. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The bounded SVG text/XML preflight refused the input. + #[error("SVG preflight failed: {0}")] + Preflight(String), + /// usvg could not construct the SVG tree. + #[error("SVG parsing failed: {0}")] + Parse(String), + /// The requested PDF area or filter raster exceeds its budget. + #[error("SVG drawing exceeds the PDF area or filter budget")] + DrawLimit, + /// krilla-svg refused to draw the parsed tree. + #[error("krilla-svg could not draw the parsed tree")] + Draw, +} + +/// An SVG tree parsed within [`Limits`], ready to draw as PDF vectors. +pub struct Document { + tree: usvg::Tree, + limits: Limits, +} + +impl Document { + /// Parse SVG/SVGZ bytes after bounded shared preflight. `options` controls the caller's font + /// database, family selection, and fallback policy; its file-reading and image resolvers are + /// replaced with a data-only resolver governed by `limits`. + pub fn parse<'a>(bytes: &[u8], limits: Limits, mut options: usvg::Options<'a>) -> Result { + let text = bounded_text(bytes, limits.input_bytes, limits).map_err(|e| Error::Preflight(e.to_string()))?; + options.image_href_resolver = image_resolver(limits); + let tree = usvg::Tree::from_str(&text, &options).map_err(|e| Error::Parse(e.to_string()))?; + Ok(Self { tree, limits }) + } + + /// Draw the parsed tree as PDF vectors. The limits account for the destination size and the + /// renderer's filter scale before krilla-svg allocates filter rasters. + pub fn draw(&self, surface: &mut krilla::surface::Surface<'_>, size: krilla::geom::Size, settings: SvgSettings) -> Result<(), Error> { + let width = f64::from(size.width()); + let height = f64::from(size.height()); + let scale = f64::from(settings.filter_scale); + if !width.is_finite() || !height.is_finite() || !scale.is_finite() || width <= 0.0 || height <= 0.0 || scale <= 0.0 { + return Err(Error::DrawLimit); + } + let area = width * height * (96.0_f64 / 72.0).powi(2); + let filter_area = area * scale * scale; + if !area.is_finite() || !filter_area.is_finite() || area > self.limits.vector_pixels as f64 || filter_area > self.limits.filter_pixels as f64 + { + return Err(Error::DrawLimit); + } + surface.draw_svg(&self.tree, size, settings).ok_or(Error::Draw) + } +} + +#[derive(Default)] +struct Usage { + svg_bytes: AtomicUsize, + svg_depth: AtomicUsize, + image_bytes: AtomicUsize, +} + +fn shared_limits(bytes: usize, limits: Limits) -> craft_svg::tree::Limits { + craft_svg::tree::Limits { + bytes, + depth: limits.depth, + tree_depth: limits.depth, + refuse_entity_markup: true, + xml_nodes: limits.xml_nodes, + embedded_bytes: limits.embedded_svg_bytes, + embedded_depth: limits.embedded_svg_depth, + ..Default::default() + } +} + +fn bounded_text(bytes: &[u8], byte_limit: usize, limits: Limits) -> Result, craft_svg::tree::Error> { + craft_svg::tree::text(bytes, &shared_limits(byte_limit, limits)) +} + +fn reserve(counter: &AtomicUsize, amount: usize, limit: usize) -> bool { + counter.try_update(Ordering::Relaxed, Ordering::Relaxed, |used| used.checked_add(amount).filter(|next| *next <= limit)).is_ok() +} + +fn embedded_svg(usage: &Usage, limits: Limits, bytes: &[u8], options: &usvg::Options<'_>) -> Option { + let used = usage.svg_bytes.load(Ordering::Relaxed); + let remaining = limits.embedded_svg_bytes.saturating_sub(used); + let text = bounded_text(bytes, remaining.min(limits.input_bytes), limits).ok()?; + if !reserve(&usage.svg_bytes, text.len(), limits.embedded_svg_bytes) { + return None; + } + let depth = usage.svg_depth.fetch_add(1, Ordering::Relaxed); + if depth >= limits.embedded_svg_depth { + usage.svg_depth.fetch_sub(1, Ordering::Relaxed); + return None; + } + let parsed = usvg::Tree::from_str(&text, options).ok(); + usage.svg_depth.fetch_sub(1, Ordering::Relaxed); + parsed.map(usvg::ImageKind::SVG) +} + +fn image_resolver(limits: Limits) -> usvg::ImageHrefResolver<'static> { + let usage = Arc::new(Usage::default()); + let default_data = usvg::ImageHrefResolver::default_data_resolver(); + usvg::ImageHrefResolver { + resolve_data: Box::new(move |mime, bytes, options| { + if mime == "image/svg+xml" || (mime == "text/plain" && (craft_svg::sniff::is_svg(&bytes) || craft_svg::sniff::is_svgz(&bytes))) { + return embedded_svg(&usage, limits, &bytes, options); + } + if !reserve(&usage.image_bytes, bytes.len(), limits.embedded_image_bytes) { + return None; + } + default_data(mime, bytes, options) + }), + resolve_string: Box::new(|_, _| None), + } +} + +#[cfg(test)] +mod tests { + use super::{Limits, shared_limits}; + + #[test] + fn shared_depth_limit_also_bounds_svg_references() { + let limits = shared_limits(1024, Limits { depth: 7, ..Limits::default() }); + assert_eq!(limits.depth, 7); + assert_eq!(limits.tree_depth, 7); + } +} diff --git a/crates/pdf/tests/cos/bounded_writer.rs b/crates/pdf/tests/cos/bounded_writer.rs index b8fe79370c..5677ca542e 100644 --- a/crates/pdf/tests/cos/bounded_writer.rs +++ b/crates/pdf/tests/cos/bounded_writer.rs @@ -139,7 +139,8 @@ fn full_rewrites_preserve_graph_across_multiple_object_streams_and_evictions() { } fn protect(doc: &mut Document, algorithm: Algorithm) { - doc.set_encryption(&NewEncryption { + // Every algorithm, RC4 included, has to survive a rewrite. + doc.set_encryption_legacy(&NewEncryption { algorithm, user_password: "user", owner_password: "owner", diff --git a/crates/pdf/tests/cos/encryption.rs b/crates/pdf/tests/cos/encryption.rs index 923b04e39b..2ac53cb696 100644 --- a/crates/pdf/tests/cos/encryption.rs +++ b/crates/pdf/tests/cos/encryption.rs @@ -39,9 +39,11 @@ fn fixture_with(extra: &str) -> Vec { out } +/// Every algorithm, RC4-40 and RC4-128 included: those two are the legacy schemes, which +/// `set_encryption` refuses. fn protect(alg: Algorithm, user: &str, owner: &str, permissions: i32) -> Vec { let mut doc = Document::open(Arc::new(fixture())).unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: user, owner_password: owner, @@ -287,7 +289,7 @@ fn signature_contents_stay_unencrypted() { c.set(b"Test".to_vec(), Object::Array(vec![Object::Ref(sig), Object::Ref(untyped), Object::Ref(note)])) }) .unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: "", owner_password: "owner", @@ -423,7 +425,7 @@ fn an_earlier_revision_opens_with_the_documents_own_credentials() { // Another file, encrypted with other keys: the document's key is no use, and it says so. let other = { let mut doc = Document::open(Arc::new(fixture())).unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: "user", owner_password: "owner", @@ -444,7 +446,7 @@ fn an_earlier_revision_opens_with_the_documents_own_credentials() { /// instead of as an indirect object. fn protect_inline(alg: Algorithm, user: &str, owner: &str) -> Vec { let mut doc = Document::open(Arc::new(fixture())).unwrap(); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm: alg, user_password: user, owner_password: owner, diff --git a/crates/pdf/tests/cos/file_identifier.rs b/crates/pdf/tests/cos/file_identifier.rs index 551db4ebd2..5ca0f0f542 100644 --- a/crates/pdf/tests/cos/file_identifier.rs +++ b/crates/pdf/tests/cos/file_identifier.rs @@ -122,7 +122,8 @@ fn caller_entropy_makes_the_new_identifier_reproducible() { fn an_encrypted_rewrite_keeps_the_first_identifier_string_its_key_depends_on() { for algorithm in [Algorithm::Rc4_128, Algorithm::Aes128, Algorithm::Aes256] { let mut doc = reopen(source(true)); - doc.set_encryption(&NewEncryption { + // The loop covers RC4-128, which `set_encryption` refuses. + doc.set_encryption_legacy(&NewEncryption { algorithm, user_password: "user", owner_password: "owner", @@ -160,7 +161,7 @@ fn unusable_ids() -> Vec<(&'static str, Option)> { /// An encrypted file whose key is derived from the empty string, with its trailer `/ID` replaced by `id`. fn protected_with_id(algorithm: Algorithm, id: Option) -> Vec { let mut doc = reopen(source_with(Some("/ID [<> <>]"))); - doc.set_encryption(&NewEncryption { + doc.set_encryption_legacy(&NewEncryption { algorithm, user_password: "user", owner_password: "owner", diff --git a/crates/pdf/tests/crypt/permissions_revision.rs b/crates/pdf/tests/crypt/permissions_revision.rs index 06a5a5b98f..a58868637e 100644 --- a/crates/pdf/tests/crypt/permissions_revision.rs +++ b/crates/pdf/tests/crypt/permissions_revision.rs @@ -3,7 +3,7 @@ //! //! Bit n has the mask `1 << (n - 1)`. Readers use bits 3 to 6 and 9 to 12 and ignore the rest. -use craft_pdf::crypt::{Algorithm, Auth, NewEncryption, Permissions, SecurityHandler, create}; +use craft_pdf::crypt::{Algorithm, Auth, NewEncryption, Permissions, SecurityHandler, create_legacy}; const ID: &[u8] = b"0123456789abcdef"; const T: bool = true; @@ -18,7 +18,7 @@ fn cells(p: &Permissions) -> [bool; 8] { /// Creates a file with `flags` at revision `revision`, opens it with the user password, and /// returns the user's permissions. fn user_view(alg: Algorithm, revision: i64, flags: i32) -> Permissions { - let made = create( + let made = create_legacy( &NewEncryption { algorithm: alg, user_password: "user", owner_password: "owner", permissions: flags, encrypt_metadata: true, seed: [42; 32] }, ID, ) @@ -56,7 +56,7 @@ fn revision_three_rows_hold_through_a_created_and_reopened_file() { #[test] fn owner_access_gives_every_flag() { - let made = create( + let made = create_legacy( &NewEncryption { algorithm: Algorithm::Rc4_128, user_password: "user", diff --git a/crates/pdf/tests/crypt/proptests.rs b/crates/pdf/tests/crypt/proptests.rs index a81808ab9c..7b9ede4d3d 100644 --- a/crates/pdf/tests/crypt/proptests.rs +++ b/crates/pdf/tests/crypt/proptests.rs @@ -19,7 +19,7 @@ use craft_pdf::crypt::{ Algorithm, Auth, CryptError, Method, NewEncryption, PADDING, SecurityHandler, StreamKind, aes_cbc_decrypt, aes_cbc_encrypt, create, - effective_password, pdfdoc_byte, rc4, + create_legacy, effective_password, pdfdoc_byte, rc4, }; use proptest::prelude::*; @@ -92,8 +92,12 @@ fn expected_auth(algorithm: Algorithm, user_target: &[u8], owner_target: &[u8], } fn make(algorithm: Algorithm, user: &str, owner: &str) -> SecurityHandler { - create(&NewEncryption { algorithm, user_password: user, owner_password: owner, permissions: -1, encrypt_metadata: true, seed: [0x5e; 32] }, ID) - .unwrap() + // These properties read and write every algorithm, RC4 included. + create_legacy( + &NewEncryption { algorithm, user_password: user, owner_password: owner, permissions: -1, encrypt_metadata: true, seed: [0x5e; 32] }, + ID, + ) + .unwrap() } proptest! { @@ -457,7 +461,7 @@ proptest! { } // Revisions below 4 always encrypt metadata, whatever the caller asked for. - let legacy = create(&NewEncryption { algorithm: Algorithm::Rc4_128, user_password: "user", owner_password: "owner", permissions: -1, encrypt_metadata: false, seed: [0x5e; 32] }, ID).unwrap(); + let legacy = create_legacy(&NewEncryption { algorithm: Algorithm::Rc4_128, user_password: "user", owner_password: "owner", permissions: -1, encrypt_metadata: false, seed: [0x5e; 32] }, ID).unwrap(); prop_assert!(legacy.dict().encrypt_metadata && legacy.encrypts_metadata(), "V<4 always encrypts metadata, as create() documents"); } diff --git a/crates/pkcs7/src/pkcs12.rs b/crates/pkcs7/src/pkcs12.rs index f14b2297e0..ee245f3800 100644 --- a/crates/pkcs7/src/pkcs12.rs +++ b/crates/pkcs7/src/pkcs12.rs @@ -184,6 +184,12 @@ impl Cipher { } } +/// Whether `a` and `b` are equal, in time that depends only on their lengths: the MAC is derived +/// from the password, so it is compared without stopping at the first differing byte. +fn same(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + fn hmac(alg: DigestAlg, key: &[u8], data: &[u8]) -> Result, Error> { fn run(key: &[u8], data: &[u8]) -> Result, Error> where @@ -411,7 +417,8 @@ pub fn open(bytes: &[u8], password: &str) -> Result { let key_len = alg.digest(&[]).len(); let iterations = budget.spend(alg, iterations, key_len)?; let key = pkcs12_kdf(alg, &bmp(password), &salt, 3, iterations, key_len); - if hmac(alg, &key, &content)? != *expected { + let computed = hmac(alg, &key, &content)?; + if !same(&computed, &expected) { return Err(Error::WrongPassword); } } diff --git a/crates/prepress/src/lib.rs b/crates/prepress/src/lib.rs index 3fa4f472e7..1afc7cf6fa 100644 --- a/crates/prepress/src/lib.rs +++ b/crates/prepress/src/lib.rs @@ -12,6 +12,8 @@ pub mod flatten; pub mod ink; pub mod marks; pub mod output; +#[cfg(feature = "flatten")] +pub mod pdfx1a; pub mod plates; pub use cms::{CmsConversion, ProfileError}; diff --git a/crates/prepress/src/pdfx1a.rs b/crates/prepress/src/pdfx1a.rs new file mode 100644 index 0000000000..92110166b2 --- /dev/null +++ b/crates/prepress/src/pdfx1a.rs @@ -0,0 +1,913 @@ +//! PDF/X-1a:2003: the PDF/X-4 print file flattened by craft-prepress (no transparency left; RGB +//! and ICC color converted into the output intent's CMYK; inks, overprint and live text kept), +//! written by krilla as PDF 1.4, given the PDF/X-1a identification and output intent, then +//! checked. Apps use [`flatten_x1a`] to flatten and finalize in one step, and [`check_pdfx1a`] +//! to inspect an existing file. + +use std::collections::{HashMap, HashSet}; + +use crate::flatten::pdf::ReadOptions; +use crate::flatten::{FlattenDocumentOptions, FlattenOptions, FlattenTotals, flatten_document}; +use craft_pdf::syntax::content::UntypedIter; +use craft_pdf::syntax::object::{Array, Dict, Name, Object, ObjectIdentifier, Stream}; +use craft_pdf::syntax::page::Resources; +use craft_pdf::write::backend::configure::PdfVersion; + +const MAX_DEPTH: usize = 16; + +/// `GTS_PDFXVersion` of PDF/X-1a:2003 (ISO 15930-4): the base level, PDF/X-1:2003. +const VERSION: &str = "PDF/X-1:2003"; + +/// `GTS_PDFXConformance` of PDF/X-1a:2003 (ISO 15930-4): with [`VERSION`], it names the +/// conformance level. +const CONFORMANCE: &str = "PDF/X-1a:2003"; + +/// `/RegistryName` of the ICC's registry of characterized printing conditions. An output intent +/// naming one of them needs no `/DestOutputProfile` in PDF/X. +const ICC_REGISTRY: &str = "http://www.color.org"; +const REGISTERED_CONDITIONS: &[&str] = &["FOGRA39"]; +/// Largest classic cross-reference size accepted by the public finalizer. The rewritten table +/// emits one entry per object number, so this is also an output-allocation bound. +const MAX_XREF_SIZE: usize = 1 << 20; + +/// The graphics placed on one output page, to name in errors: the page's name and the graphics' +/// names. +#[derive(Clone, Debug, Default)] +pub struct PageGraphics { + pub label: String, + pub graphics: Vec, +} + +/// The PDF/X-1a file for `pdf`, the PDF/X-4 print file: flattened at `dpi`, written at PDF 1.4, +/// identified, checked. `pages` names each output page and its graphics for errors. Fails when +/// the flattener fails or leaves an image out, when the output intent's profile can't go into a +/// PDF 1.4 file, or when the result still has transparency or color outside DeviceCMYK, +/// DeviceGray, Separation and DeviceN; other check findings become warnings. +pub fn flatten_x1a(pdf: &[u8], dpi: f32, pages: &[PageGraphics]) -> Result<(Vec, Vec), String> { + let dpi = if dpi.is_finite() { dpi.clamp(36.0, 2400.0) } else { 300.0 }; + let opts = FlattenDocumentOptions { + read: ReadOptions { raster_dpi: dpi, ..ReadOptions::default() }, + flatten: FlattenOptions { raster_dpi: dpi, ..FlattenOptions::default() }, + producer: "DesignCraft".into(), + version: PdfVersion::Pdf14, + pdfx_version: Some(VERSION.into()), + ..FlattenDocumentOptions::default() + }; + let (bytes, report) = flatten_document(pdf, &opts).map_err(|e| format!("PDF/X-1a: the transparency flattener failed: {e}"))?; + let unread: Vec = report + .pages + .iter() + .filter(|(_, r)| r.read.unreadable_images > 0) + .map(|(page, r)| { + let n = r.read.unreadable_images; + let images = if n == 1 { "1 image".to_string() } else { format!("{n} images") }; + let fallback = PageGraphics { label: page.saturating_add(1).to_string(), graphics: Vec::new() }; + let at = pages.get(*page).unwrap_or(&fallback); + let names: Vec = at.graphics.iter().take(5).map(|g| format!("`{g}`")).collect(); + let more = if at.graphics.len() > 5 { ", …" } else { "" }; + let placed = if names.is_empty() { String::new() } else { format!(" (graphics on it: {}{more})", names.join(", ")) }; + format!("{images} on page {}{placed}", at.label) + }) + .collect(); + if !unread.is_empty() { + return Err(format!( + "PDF/X-1a: the transparency flattener couldn't read {}, and a PDF/X file can't leave images out: replace the graphic, or export without PDF/X-1a", + unread.join("; ") + )); + } + let mut warnings = flatten_warnings(&report.totals, dpi); + let bytes = finish_x1a(&bytes)?; + let (fatal, other) = checks(&bytes); + if !fatal.is_empty() { + return Err(format!("PDF/X-1a: after flattening, {}", fatal.join("; "))); + } + warnings.extend(other.into_iter().map(|issue| format!("PDF/X-1a: {issue}"))); + Ok((bytes, warnings)) +} + +/// What the flattener's `t` (at `dpi`) tells the user: rasterized transparency, and spot inks past +/// the ink set's capacity, whose tints the flattener drops. +pub fn flatten_warnings(t: &FlattenTotals, dpi: f32) -> Vec { + let mut out = Vec::new(); + if t.complex_regions > 0 || t.complex_groups > 0 { + let at = t.lowest_dpi.map(|d| format!(", some below {dpi:.0} ppi (lowest {d:.0} ppi)")).unwrap_or_default(); + out.push(format!("PDF/X-1a: transparency flattened: {} region(s) rasterized at {dpi:.0} ppi{at}", t.complex_regions + t.complex_groups)); + } + if t.dropped_inks > 0 { + out.push(format!( + "PDF/X-1a: the document has more spot inks than the flattener can separate: {} tint(s) in the inks past its limit were dropped and won't print", + t.dropped_inks + )); + } + out +} + +/// PDF/X-1a:2003 checks on an exported file (empty = passes them): PDF 1.4 or lower, the +/// identification (`GTS_PDFXVersion` and `GTS_PDFXConformance`), a CMYK `GTS_PDFX` output intent +/// whose profile, when it has one, is ICC v2 (and without one, names a registered printing +/// condition), `/Trapped` True or False, trim boxes, no encryption or interpolation; no +/// transparency (soft masks, transparency groups, constant opacity below 1, blend modes other +/// than Normal); only DeviceCMYK, DeviceGray, Separation and DeviceN (and Indexed and Pattern +/// spaces over them), a spot's alternate space process; every font embedded. +pub fn check_pdfx1a(pdf: &[u8]) -> Vec { + let (mut issues, other) = checks(pdf); + issues.extend(other); + issues +} + +/// [`check_pdfx1a`]'s findings: transparency and color spaces first, then the rest. +fn checks(pdf: &[u8]) -> (Vec, Vec) { + let mut issues = Vec::new(); + let file = craft_pdf::syntax::Pdf::new(pdf.to_vec()).ok(); + if !pdf.starts_with(b"%PDF-1.") || pdf.get(7).is_none_or(|v| *v > b'4') { + issues.push("the PDF version must be 1.4 or lower".into()); + } + if file.as_ref().is_none_or(|f| pdfx_intents(f).is_empty()) { + issues.push("no PDF/X output intent".into()); + } + let info = |key: &[u8]| file.as_ref().and_then(|f| info_text(f, key)); + if info(b"GTS_PDFXVersion").as_deref() != Some(VERSION) { + issues.push(format!("the document information doesn't name {VERSION}")); + } + if info(b"GTS_PDFXConformance").as_deref() != Some(CONFORMANCE) { + issues.push(format!("the document information doesn't name the conformance level {CONFORMANCE}")); + } + let trapped = file.as_ref().and_then(|f| f.info()).and_then(|info| info.get::>(b"Trapped")); + if !trapped.as_ref().is_some_and(|value| matches!(value.as_ref(), b"False" | b"True")) { + issues.push("the document information needs /Trapped True or False".into()); + } + if file.as_ref().is_some_and(|f| f.is_encrypted()) { + issues.push("the file is encrypted".into()); + } + if let Some(file) = file.as_ref() { + for (index, page) in file.pages().iter().enumerate() { + let raw = page.raw(); + let trim = raw.contains_key(b"TrimBox"); + let art = raw.contains_key(b"ArtBox"); + if trim == art { + issues.push(format!("page {} needs either a trim box or an art box, but not both", index + 1)); + } + } + } + let (content, fonts, scan_issues) = content(file.as_ref()); + issues.extend(fonts); + issues.extend(scan_issues); + (content, issues) +} + +/// Transparency and color spaces, then the output intent and fonts, walked through every page's +/// content and what it uses. +fn content(file: Option<&craft_pdf::syntax::Pdf>) -> (Vec, Vec, Vec) { + let Some(file) = file else { + return (vec!["the file couldn't be read to check its transparency and color spaces".into()], Vec::new(), Vec::new()); + }; + let mut fonts = intent_issues(file); + let mut found: Vec<(String, Vec)> = Vec::new(); + let mut font_found: Vec<(String, Vec)> = Vec::new(); + let mut scan_found: Vec<(String, Vec)> = Vec::new(); + for (i, page) in file.pages().iter().enumerate() { + let mut scan = Scan::default(); + let res = page.resources(); + if let Some(group) = page.raw().get::>(b"Group") { + scan.group(&group); + } + if let Some(content) = page.page_stream() { + scan.content(content, res, 0); + } + for (list, items) in [(&mut found, scan.found), (&mut font_found, scan.font_issues), (&mut scan_found, scan.other_issues)] { + for what in items { + match list.iter_mut().find(|(w, _)| *w == what) { + Some((_, pages)) => pages.push(i + 1), + None => list.push((what, vec![i + 1])), + } + } + } + } + let on_pages = |(what, pages): (String, Vec)| { + let list: Vec = pages.iter().take(10).map(|p| p.to_string()).collect(); + let more = if pages.len() > 10 { ", …" } else { "" }; + let s = if pages.len() == 1 { "" } else { "s" }; + format!("{what} on page{s} {}{more}", list.join(", ")) + }; + fonts.extend(font_found.into_iter().map(on_pages)); + (found.into_iter().map(on_pages).collect(), fonts, scan_found.into_iter().map(on_pages).collect()) +} + +/// A `GTS_PDFX` output intent, as PDF/X-1a judges it. +struct Intent { + /// Its object number, when it is an indirect object. + obj: Option, + /// `/OutputCondition`, else `/OutputConditionIdentifier`, for messages. + name: String, + /// An `/OutputConditionIdentifier` other than `Custom` in the ICC registry. + registered: bool, + /// Whether it has a `/DestOutputProfile`, and the profile's object number. + has_profile: bool, + profile_obj: Option, + /// The profile's `/N` and decoded bytes. + channels: Option, + profile: Option>, +} + +impl Intent { + /// The profile's ICC major version (byte 8 of its header). + fn major(&self) -> Option { + self.profile.as_deref()?.get(8).copied() + } + + /// "ICC v4", or what keeps the version from being read. + fn version(&self) -> String { + self.major().map_or_else(|| "unreadable".to_string(), |v| format!("ICC v{v}")) + } +} + +/// The catalog's `GTS_PDFX` output intents. +fn pdfx_intents(file: &craft_pdf::syntax::Pdf) -> Vec { + let number = |n: i32| usize::try_from(n).ok(); + raw_pdfx_intents(file) + .into_iter() + .map(|oi| { + let text = |key: &[u8]| { + oi.get::>(key) + .map(|s| String::from_utf8_lossy(s.as_bytes()).trim().to_string()) + .filter(|s| !s.is_empty()) + }; + let identifier = text(b"OutputConditionIdentifier"); + let registry = text(b"RegistryName"); + let profile = oi.get::>(b"DestOutputProfile"); + Intent { + obj: oi.obj_id().and_then(|id| number(id.obj_number)), + name: text(b"OutputCondition").or_else(|| identifier.clone()).unwrap_or_else(|| "?".into()), + registered: registry.is_some_and(|r| r.trim_end_matches('/') == ICC_REGISTRY) + && identifier.as_deref().is_some_and(|identifier| REGISTERED_CONDITIONS.contains(&identifier)), + has_profile: oi.contains_key(b"DestOutputProfile"), + profile_obj: oi.get_ref(b"DestOutputProfile").and_then(|r| number(r.obj_number)), + channels: profile.as_ref().and_then(|p| p.dict().get::(b"N")), + profile: profile.and_then(|p| p.decoded().ok()).map(|b| b.into_owned()), + } + }) + .collect() +} + +fn raw_pdfx_intents<'a>(file: &'a craft_pdf::syntax::Pdf) -> Vec> { + let xref = file.xref(); + let Some(catalog) = xref.get::>(xref.root_id()) else { return Vec::new() }; + let Some(intents) = catalog.get::>(b"OutputIntents") else { return Vec::new() }; + intents.iter::>().filter(|oi| oi.get::>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX")).collect() +} + +fn info_text(file: &craft_pdf::syntax::Pdf, key: &[u8]) -> Option { + file.info()?.get::>(key).map(|s| String::from_utf8_lossy(s.as_bytes()).trim().to_string()) +} + +/// What PDF/X-1a finds wrong with the file's output intent: a CMYK profile, ICC v2 (PDF 1.4 +/// allows no later version), or none for a registered printing condition. +fn intent_issues(file: &craft_pdf::syntax::Pdf) -> Vec { + let Some(oi) = pdfx_intents(file).into_iter().next() else { return Vec::new() }; + let mut issues = Vec::new(); + if oi.has_profile { + if oi.channels != Some(4) { + issues.push("the output intent has no CMYK destination profile".into()); + } + if oi.major() != Some(2) { + issues.push(format!("the output intent's profile is {}, and PDF/X-1a (PDF 1.4) allows only ICC v2 profiles", oi.version())); + } + } else if !oi.registered { + issues + .push(format!("the output intent has no destination profile and doesn't name a printing condition in the ICC registry ({ICC_REGISTRY})")); + } + issues +} + +/// krilla's PDF 1.4 file with what PDF/X-1a needs and krilla doesn't write, rewritten as one +/// revision: `GTS_PDFXConformance` in the document information and the XMP, and the output intent +/// of a registered printing condition without `/DestOutputProfile` (its profile is left out of +/// the file). An unregistered condition keeps its profile, which must then be ICC v2. +pub fn finish_x1a(pdf: &[u8]) -> Result, String> { + let unreadable = || "the flattened file couldn't be read to add the PDF/X-1a identification".to_string(); + let layout = Layout::read(pdf).ok_or_else(unreadable)?; + let file = craft_pdf::syntax::Pdf::new(pdf.to_vec()).map_err(|_| unreadable())?; + let mut bodies: HashMap> = HashMap::new(); + let info = file.info().and_then(|info| info.obj_id()).and_then(|id| usize::try_from(id.obj_number).ok()).ok_or_else(unreadable)?; + let body = layout.body(pdf, info).ok_or_else(unreadable)?; + let (head, close) = body.split_at_checked(rfind(body, b">>").ok_or_else(unreadable)?).ok_or_else(unreadable)?; + bodies.insert(info, [head, format!("/GTS_PDFXConformance({CONFORMANCE})").as_bytes(), close].concat()); + let xref = file.xref(); + if let Some(meta) = xref.get::>(xref.root_id()).and_then(|c| c.get_ref(b"Metadata")).and_then(|r| usize::try_from(r.obj_number).ok()) + && let Some(xmp) = layout.body(pdf, meta).and_then(xmp_with_conformance) + { + bodies.insert(meta, xmp); + } + let mut stripped: Vec = Vec::new(); + for oi in pdfx_intents(&file) { + if !oi.has_profile { + continue; + } + if !oi.registered { + if oi.major() != Some(2) { + return Err(format!( + "the output intent's profile `{}` is {}, and PDF/X-1a (PDF 1.4) allows only ICC v2 profiles: choose a CMYK working space with an ICC v2 profile, or Coated FOGRA39", + oi.name, + oi.version() + )); + } + continue; + } + let (Some(obj), Some(profile)) = (oi.obj, oi.profile_obj) else { return Err(unreadable()) }; + let body = match bodies.get(&obj) { + Some(b) => b.clone(), + None => layout.body(pdf, obj).ok_or_else(unreadable)?.to_vec(), + }; + let key = format!("/DestOutputProfile {profile} 0 R"); + let at = find(&body, key.as_bytes(), 0).ok_or_else(unreadable)?; + let (before, rest) = body.split_at_checked(at).ok_or_else(unreadable)?; + let after = rest.get(key.len()..).ok_or_else(unreadable)?; + bodies.insert(obj, [before, after].concat()); + stripped.push(profile); + } + // A profile only the stripped intents named goes too. + let dropped: HashSet = stripped.iter().copied().filter(|p| references(pdf, *p) == stripped.iter().filter(|q| *q == p).count()).collect(); + layout.write(pdf, &bodies, &dropped).ok_or_else(unreadable) +} + +/// How often `n 0 R` appears in `pdf` (a stream that happens to hold those bytes counts too, which +/// only ever keeps an object). +fn references(pdf: &[u8], n: usize) -> usize { + let needle = format!("{n} 0 R"); + let mut count = 0; + let mut from = 0; + while let Some(at) = find(pdf, needle.as_bytes(), from) { + let before = at.checked_sub(1).and_then(|i| pdf.get(i)).is_none_or(|c| !c.is_ascii_digit()); + let after = pdf.get(at + needle.len()).is_none_or(|c| !c.is_ascii_alphanumeric()); + if before && after { + count += 1; + } + from = at + needle.len(); + } + count +} + +/// The body of an uncompressed XMP metadata stream object with the Adobe `pdfx` properties of +/// the identification (`GTS_PDFXVersion`, `GTS_PDFXConformance`) added and its `/Length` updated; +/// `None` when the stream is filtered or isn't XMP. +fn xmp_with_conformance(body: &[u8]) -> Option> { + let s0 = find(body, b"stream", 0)?; + let dict = String::from_utf8_lossy(body.get(..s0)?).to_string(); + let s0 = s0 + b"stream".len(); + let s0 = s0 + body.get(s0..)?.iter().take_while(|c| **c == b'\r' || **c == b'\n').count(); + let s1 = rfind(body, b"endstream")?; + let xml = String::from_utf8_lossy(body.get(s0..s1)?).trim_end().to_string(); + if dict.contains("/Filter") || !xml.contains("") { + return None; + } + let ids = format!( + "{VERSION}\ + {CONFORMANCE}" + ); + let xml = xml.replacen("", &format!("{ids}"), 1); + let i = dict.find("/Length")?; + let rest = dict.get(i + 7..)?.trim_start(); + let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()); + let dict = format!("{}/Length {}{}", dict.get(..i)?, xml.len(), rest.get(end..)?); + Some(format!("\n{}\nstream\n{xml}\nendstream\n", dict.trim()).into_bytes()) +} + +fn find(bytes: &[u8], needle: &[u8], from: usize) -> Option { + (from <= bytes.len()).then(|| bytes.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|at| at + from))? +} + +fn rfind(bytes: &[u8], needle: &[u8]) -> Option { + bytes.windows(needle.len()).rposition(|w| w == needle) +} + +fn int_after(text: &str, key: &str) -> Option { + let at = text.find(key)? + key.len(); + text.get(at..)?.trim_start().split(|c: char| !c.is_ascii_digit()).next()?.parse().ok() +} + +/// Where the objects of a single-revision file with a classic cross-reference table are. +struct Layout { + /// (object number, start, end), by start: from `n 0 obj` up to the next object or the table. + objects: Vec<(usize, usize, usize)>, + /// Where the cross-reference table starts. + table: usize, + /// The trailer dictionary. + trailer: String, + size: usize, +} + +impl Layout { + fn read(pdf: &[u8]) -> Option { + let sx = rfind(pdf, b"startxref")?; + let table: usize = std::str::from_utf8(pdf.get(sx + b"startxref".len()..)?).ok()?.split_whitespace().next()?.parse().ok()?; + let section = pdf.get(table..sx)?; + let t = find(section, b"trailer", 0)?; + let trailer = String::from_utf8_lossy(section.get(t + b"trailer".len()..)?).trim().to_string(); + if trailer.contains("/Prev") || trailer.contains("/XRefStm") { + return None; + } + let size = int_after(&trailer, "/Size")?; + if size > MAX_XREF_SIZE { + return None; + } + let mut tokens = std::str::from_utf8(section.get(..t)?).ok()?.split_whitespace(); + if tokens.next()? != "xref" { + return None; + } + let mut starts: Vec<(usize, usize)> = Vec::new(); + let mut seen = HashSet::new(); + while let Some(first) = tokens.next() { + let first: usize = first.parse().ok()?; + let count: usize = tokens.next()?.parse().ok()?; + for i in 0..count { + let (offset, generation, kind) = (tokens.next()?, tokens.next()?, tokens.next()?); + if kind != "n" { + continue; + } + let n = first.checked_add(i)?; + let offset: usize = offset.parse().ok()?; + if generation != "00000" || offset >= table || n >= size || !seen.insert(n) { + return None; + } + starts.push((n, offset)); + } + } + // Free entries past the objects would only make the rewritten table longer. + let max = starts.iter().map(|(n, _)| *n).max().unwrap_or(0); + if size > max.saturating_mul(2).saturating_add(16) { + return None; + } + starts.sort_by_key(|(_, offset)| *offset); + let mut objects = Vec::with_capacity(starts.len()); + for (i, &(n, start)) in starts.iter().enumerate() { + let end = starts.get(i + 1).map_or(table, |(_, s)| *s); + if !pdf.get(start..end)?.starts_with(format!("{n} 0 obj").as_bytes()) { + return None; + } + objects.push((n, start, end)); + } + Some(Layout { objects, table, trailer, size }) + } + + /// Object `n` between `n 0 obj` and `endobj`. + fn body<'p>(&self, pdf: &'p [u8], n: usize) -> Option<&'p [u8]> { + let &(_, start, end) = self.objects.iter().find(|(m, _, _)| *m == n)?; + let obj = pdf.get(start..end)?; + obj.get(format!("{n} 0 obj").len()..rfind(obj, b"endobj")?) + } + + /// The file with the objects in `bodies` replaced and those in `dropped` left out, and a new + /// cross-reference table. + fn write(&self, pdf: &[u8], bodies: &HashMap>, dropped: &HashSet) -> Option> { + let first = self.objects.first().map_or(self.table, |o| o.1); + let mut out = pdf.get(..first)?.to_vec(); + let mut offsets = HashMap::new(); + for &(n, start, end) in &self.objects { + if dropped.contains(&n) { + continue; + } + offsets.insert(n, out.len()); + match bodies.get(&n) { + Some(body) => { + out.extend_from_slice(format!("{n} 0 obj").as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"endobj\n"); + } + None => out.extend_from_slice(pdf.get(start..end)?), + } + } + if !out.ends_with(b"\n") { + out.push(b'\n'); + } + let table = out.len(); + // The free entries, each pointing at the next. + let free: Vec = (1..self.size).filter(|n| !offsets.contains_key(n)).collect(); + let next: HashMap = free.iter().copied().zip(free.iter().skip(1).copied().chain([0])).collect(); + out.extend_from_slice(format!("xref\n0 {}\n{:010} 65535 f\r\n", self.size, free.first().copied().unwrap_or(0)).as_bytes()); + for n in 1..self.size { + let next = next.get(&n).copied().unwrap_or(0); + let entry = match offsets.get(&n) { + Some(offset) => format!("{offset:010} 00000 n\r\n"), + // A dropped object's number could be used again, at the next generation. + None if dropped.contains(&n) => format!("{next:010} 00001 f\r\n"), + None => format!("{next:010} 65535 f\r\n"), + }; + out.extend_from_slice(entry.as_bytes()); + } + out.extend_from_slice(format!("trailer\n{}\nstartxref\n{table}\n%%EOF\n", self.trailer).as_bytes()); + Some(out) + } +} + +/// Why a color space isn't allowed in PDF/X-1a, or `None` when it is. +fn disallowed(cs: &Object<'_>, res: &Resources<'_>, depth: usize) -> Option { + if depth > 4 { + return Some("a color space nested too deeply".into()); + } + match cs { + Object::Name(n) => match n.as_ref() { + b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" | b"Pattern" => None, + b"DeviceRGB" | b"RGB" => Some("DeviceRGB color".into()), + b"Indexed" | b"I" => None, + other => match res.get_color_space(&Name::new_unescaped(other)) { + Some(named) if !matches!(named, Object::Name(_)) => disallowed(&named, res, depth + 1), + Some(Object::Name(m)) if m.as_ref() != other => disallowed(&Object::Name(m), res, depth + 1), + _ => Some(format!("the color space /{}", String::from_utf8_lossy(other))), + }, + }, + Object::Array(a) => { + let mut items = a.iter::>(); + let family = match items.next() { + Some(Object::Name(n)) => n, + _ => return Some("an unreadable color space".into()), + }; + match family.as_ref() { + b"ICCBased" => Some("ICC-based color".into()), + b"CalRGB" | b"CalGray" => Some("CIE-based (CalRGB/CalGray) color".into()), + b"Lab" => Some("Lab color".into()), + b"DeviceRGB" | b"RGB" => Some("DeviceRGB color".into()), + b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" => None, + b"Indexed" | b"I" => items.next().and_then(|base| disallowed(&base, res, depth + 1)), + b"Pattern" => items.next().and_then(|base| disallowed(&base, res, depth + 1)), + b"Separation" | b"DeviceN" => { + let _names = items.next(); + let alt = items.next()?; + if !is_process_space(&alt, res, depth + 1) { + return Some("a spot color whose alternate space isn't a CMYK or gray process space".into()); + } + let _tint = items.next(); + // NChannel attributes are PDF 1.6, past the 1.4 that PDF/X-1a:2003 allows. + let attrs = items.next().and_then(|o| match o { + Object::Dict(d) => Some(d), + _ => None, + }); + attrs + .filter(|a| a.get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"NChannel") || a.contains_key(b"Process")) + .map(|_| "a DeviceN space with NChannel attributes (PDF 1.6)".into()) + } + other => Some(format!("the color space /{}", String::from_utf8_lossy(other))), + } + } + _ => Some("an unreadable color space".into()), + } +} + +fn is_process_space(cs: &Object<'_>, res: &Resources<'_>, depth: usize) -> bool { + if depth > 4 { + return false; + } + match cs { + Object::Name(name) => match name.as_ref() { + b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" => true, + other => match res.get_color_space(&Name::new_unescaped(other)) { + Some(Object::Name(alias)) if alias.as_ref() != other => is_process_space(&Object::Name(alias), res, depth + 1), + Some(named) if !matches!(named, Object::Name(_)) => is_process_space(&named, res, depth + 1), + _ => false, + }, + }, + Object::Array(array) => { + array.iter::>().next().is_some_and(|family| matches!(family.as_ref(), b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G")) + } + _ => false, + } +} + +/// What one page has that PDF/X-1a doesn't allow, in the order found. +#[derive(Default)] +struct Scan { + /// What was found, in the order found; `known` is the same as a set. + found: Vec, + known: HashSet, + font_issues: Vec, + other_issues: Vec, + seen: HashSet, + fonts: HashSet, +} + +impl Scan { + fn add(&mut self, what: String) { + if self.known.insert(what.clone()) { + self.found.push(what); + } + } + + fn space(&mut self, cs: &Object<'_>, res: &Resources<'_>) { + if let Some(why) = disallowed(cs, res, 0) { + self.add(why); + } + } + + fn content(&mut self, data: &[u8], res: &Resources<'_>, depth: usize) { + if depth > MAX_DEPTH { + self.add("content was not fully checked because nested resources exceed the scan limit".into()); + return; + } + let mut ops = UntypedIter::new(data); + while let Some(op) = ops.next() { + let operator: &[u8] = op.operator; + let last = op.operands().last().cloned(); + let name = || last.clone().and_then(Object::into_name); + match operator { + b"rg" | b"RG" => self.add("DeviceRGB color".into()), + b"cs" | b"CS" => { + if let Some(n) = name() { + self.space(&Object::Name(n), res); + } + } + b"sh" => { + if let Some(sh) = name().and_then(|n| res.get_shading(&n)) { + self.shading(sh, res); + } + } + b"scn" | b"SCN" => { + if let Some(p) = name().and_then(|n| res.get_pattern(&n)) { + self.pattern(p, res, depth); + } + } + b"gs" => { + if let Some(gs) = name().and_then(|n| res.get_ext_g_state(&n)) { + self.ext_g_state(&gs, res, depth); + } + } + b"Tf" => { + let font = op.operands().next().cloned().and_then(Object::into_name).and_then(|n| res.get_font(&n)); + if let Some(font) = font { + self.font(&font, res, depth); + } + } + b"Do" => { + if let Some(xo) = name().and_then(|n| res.get_x_object(&n)) { + match xo.dict().get::>(b"Subtype").as_deref() { + Some(b"Image") => self.image(&xo, res), + Some(b"Form") => self.form(&xo, res, depth), + _ => {} + } + } + } + b"BI" | b"EI" => { + if let Some(Object::Stream(img)) = last { + let dict = img.dict(); + if let Some(cs) = dict.get::>(b"CS").or_else(|| dict.get::>(b"ColorSpace")) { + self.space(&cs, res); + } + self.interpolation(dict); + } + } + _ => {} + } + } + } + + fn ext_g_state(&mut self, gs: &Dict<'_>, res: &Resources<'_>, depth: usize) { + match gs.get::>(b"SMask") { + None => {} + Some(Object::Name(n)) if n.as_ref() == b"None" => {} + Some(mask) => { + self.add("a soft mask (transparency)".into()); + if let Some(form) = match mask { + Object::Dict(d) => d.get::>(b"G"), + _ => None, + } { + self.form(&form, res, depth); + } + } + } + for key in [&b"CA"[..], b"ca"] { + if gs.get::(key).is_some_and(|a| a < 1.0) { + self.add("constant opacity below 100% (transparency)".into()); + } + } + let normal = |n: &[u8]| matches!(n, b"Normal" | b"Compatible"); + match gs.get::>(b"BM") { + Some(Object::Name(n)) if !normal(n.as_ref()) => { + self.add(format!("the blend mode /{} (transparency)", String::from_utf8_lossy(n.as_ref()))) + } + Some(Object::Array(a)) if a.iter::>().any(|n| !normal(n.as_ref())) => { + self.add("a blend mode other than Normal (transparency)".into()) + } + _ => {} + } + } + + fn image(&mut self, img: &Stream<'_>, res: &Resources<'_>) { + if !self.seen.insert(img.obj_id()) { + return; + } + let d = img.dict(); + self.interpolation(d); + if d.get::>(b"SMask").is_some() { + self.add(format!("an image with a soft mask (object {}, transparency)", img.obj_id().obj_number)); + } + if d.get::(b"SMaskInData").is_some_and(|v| v != 0) { + self.add(format!("an image with transparency in its data (object {})", img.obj_id().obj_number)); + } + if d.get::(b"ImageMask") == Some(true) { + return; + } + match d.get::>(b"ColorSpace") { + Some(cs) => { + if let Some(why) = disallowed(&cs, res, 0) { + let (w, h) = (d.get::(b"Width").unwrap_or(0), d.get::(b"Height").unwrap_or(0)); + self.add(format!("{why} in an image (object {}, {w} × {h} px)", img.obj_id().obj_number)); + } + } + // JPX images may carry their own space; X-1a doesn't allow them. + None => self.add(format!("an image without a color space (object {})", img.obj_id().obj_number)), + } + } + + fn interpolation(&mut self, dict: &Dict<'_>) { + if dict.get::(b"Interpolate") == Some(true) { + let message = "an image asks for interpolation".to_string(); + if !self.other_issues.contains(&message) { + self.other_issues.push(message); + } + } + } + + fn form(&mut self, form: &Stream<'_>, parent: &Resources<'_>, depth: usize) { + if depth >= MAX_DEPTH { + self.add("content was not fully checked because nested forms exceed the scan limit".into()); + return; + } + if !self.seen.insert(form.obj_id()) { + return; + } + let res = Resources::from_parent(form.dict().get::>(b"Resources").unwrap_or_default(), parent.clone()); + if let Some(group) = form.dict().get::>(b"Group") { + self.group(&group); + } + match form.decoded() { + Ok(data) => self.content(&data, &res, depth + 1), + Err(_) => self.add(format!("a form XObject could not be decoded (object {})", form.obj_id().obj_number)), + } + } + + fn group(&mut self, group: &Dict<'_>) { + if group.get::>(b"S").is_some_and(|s| s.as_ref() == b"Transparency") { + self.add("a transparency group".into()); + } + } + + fn shading(&mut self, sh: Object<'_>, res: &Resources<'_>) { + let dict = match sh { + Object::Dict(d) => d, + Object::Stream(s) => s.dict().clone(), + _ => return, + }; + if let Some(cs) = dict.get::>(b"ColorSpace") { + self.space(&cs, res); + } + } + + fn pattern(&mut self, p: Object<'_>, res: &Resources<'_>, depth: usize) { + match p { + Object::Dict(d) => { + if let Some(sh) = d.get::>(b"Shading") { + self.shading(sh, res); + } + if let Some(gs) = d.get::>(b"ExtGState") { + self.ext_g_state(&gs, res, depth); + } + } + Object::Stream(s) => self.form(&s, res, depth), + _ => {} + } + } + + /// Embedded: a simple font's descriptor, or a Type 0 font's descendant's, has a font file. A + /// Type 3 font's glyphs are content streams in the file, scanned like the page's. + fn font(&mut self, font: &Dict<'_>, parent: &Resources<'_>, depth: usize) { + if let Some(id) = font.obj_id() + && !self.fonts.insert(id) + { + return; + } + let name = font.get::>(b"BaseFont").map(|n| String::from_utf8_lossy(n.as_ref()).to_string()).unwrap_or_else(|| "?".into()); + let subtype = font.get::>(b"Subtype"); + let descriptor = match subtype.as_deref() { + Some(b"Type3") => return self.type3(font, parent, depth), + Some(b"Type0") => { + font.get::>(b"DescendantFonts").and_then(|a| a.iter::>().next()).and_then(|d| d.get::>(b"FontDescriptor")) + } + _ => font.get::>(b"FontDescriptor"), + }; + let embedded = descriptor.is_some_and(|d| [&b"FontFile"[..], b"FontFile2", b"FontFile3"].iter().any(|k| d.get::>(k).is_some())); + if !embedded { + self.font_issues.push(format!("the font {name} isn't embedded")); + } + } + + /// A Type 3 font's glyph procedures, with the font's resources over `parent`'s. + fn type3(&mut self, font: &Dict<'_>, parent: &Resources<'_>, depth: usize) { + if depth >= MAX_DEPTH { + self.add("content was not fully checked because nested Type 3 glyphs exceed the scan limit".into()); + return; + } + let res = Resources::from_parent(font.get::>(b"Resources").unwrap_or_default(), parent.clone()); + let Some(procs) = font.get::>(b"CharProcs") else { return }; + for key in procs.keys() { + if let Some(glyph) = procs.get::>(key.as_ref()) + && self.seen.insert(glyph.obj_id()) + { + match glyph.decoded() { + Ok(data) => self.content(&data, &res, depth + 1), + Err(_) => self.add(format!("a Type 3 glyph stream could not be decoded (object {})", glyph.obj_id().obj_number)), + } + } + } + } +} + +#[cfg(test)] +mod review_regressions { + use super::{Layout, check_pdfx1a, finish_x1a}; + fn pdf(page_boxes: &str, info: &str, content: &[u8], extra: &[(&str, &str)]) -> Vec { + let mut objects = vec![ + b"<< /Type /Catalog /Pages 2 0 R /OutputIntents [3 0 R] >>".to_vec(), + b"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_vec(), + b"<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (FOGRA39) /RegistryName (http://www.color.org) >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] {page_boxes} /Resources <<>> /Contents 5 0 R >>").into_bytes(), + [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(), + format!("<< {info} >>").into_bytes(), + ]; + for (key, body) in extra { + objects.push(format!("<< {key} {body} >>").into_bytes()); + } + let mut out = b"%PDF-1.4\n% parser regression fixture\n".to_vec(); + let mut offsets = Vec::new(); + for (index, body) in objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + for offset in offsets { + out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R /Info 6 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + out + } + + fn compliant_info() -> &'static str { + "/GTS_PDFXVersion (PDF/X-1:2003) /GTS_PDFXConformance (PDF/X-1a:2003) /Trapped /False" + } + + #[test] + fn parsed_info_values_are_required_even_when_comment_contains_expected_values() { + let bytes = pdf( + "/TrimBox [0 0 100 100]", + "/GTS_PDFXVersion (wrong) /GTS_PDFXConformance (wrong) /Trapped /False", + b"% /GTS_PDFXVersion (PDF/X-1:2003) /GTS_PDFXConformance (PDF/X-1a:2003)\n", + &[], + ); + let issues = check_pdfx1a(&bytes); + assert!(issues.iter().any(|issue| issue.contains("doesn't name PDF/X-1:2003")), "{issues:?}"); + assert!(issues.iter().any(|issue| issue.contains("doesn't name the conformance level")), "{issues:?}"); + } + + #[test] + fn either_trim_or_art_box_is_accepted_but_not_both() { + let art_only = pdf("/ArtBox [0 0 100 100]", compliant_info(), b"", &[]); + let both = pdf("/TrimBox [0 0 100 100] /ArtBox [0 0 100 100]", compliant_info(), b"", &[]); + assert!(!check_pdfx1a(&art_only).iter().any(|issue| issue.contains("either a trim box or an art box"))); + assert!(check_pdfx1a(&both).iter().any(|issue| issue.contains("either a trim box or an art box"))); + } + + #[test] + fn an_unknown_registry_identifier_cannot_replace_a_destination_profile() { + let mut bytes = pdf("/TrimBox [0 0 100 100]", compliant_info(), b"", &[]); + let known = b"FOGRA39"; + let at = bytes.windows(known.len()).position(|window| window == known); + assert!(at.is_some()); + if let Some(at) = at { + bytes[at..at + known.len()].copy_from_slice(b"NOTREAL"); + } + let issues = check_pdfx1a(&bytes); + assert!(issues.iter().any(|issue| issue.contains("doesn't name a printing condition in the ICC registry")), "{issues:?}"); + } + + #[test] + fn finalizer_rejects_unbounded_xref_size_before_allocating_the_table() { + let mut bytes = pdf("/TrimBox [0 0 100 100]", compliant_info(), b"", &[]); + let size = b"/Size 7"; + let at = bytes.windows(size.len()).position(|window| window == size); + assert!(at.is_some()); + if let Some(at) = at { + bytes.splice(at..at + size.len(), b"/Size 1048577".iter().copied()); + } + assert!(Layout::read(&bytes).is_none()); + assert!(finish_x1a(&bytes).is_err()); + } + + #[test] + fn trapped_must_be_a_pdf_name_with_a_boolean_name_value() { + for value in ["(False)", "true", "(True)"] { + let info = format!("/GTS_PDFXVersion (PDF/X-1:2003) /GTS_PDFXConformance (PDF/X-1a:2003) /Trapped {value}"); + let bytes = pdf("/TrimBox [0 0 100 100]", &info, b"", &[]); + assert!(check_pdfx1a(&bytes).iter().any(|issue| issue.contains("needs /Trapped True or False")), "{value}"); + } + } +} diff --git a/crates/prepress/tests/flatten_document.rs b/crates/prepress/tests/flatten_document.rs index 165a80e9ae..a24f5dfea9 100644 --- a/crates/prepress/tests/flatten_document.rs +++ b/crates/prepress/tests/flatten_document.rs @@ -116,7 +116,6 @@ fn three_pages(font_bytes: &[u8]) -> Vec { s.pop(); text(s, &font, &face, (20.0, 110.0), 12.0, "World"); }); - drop(page); writer.finish().unwrap() } diff --git a/crates/print/Cargo.toml b/crates/print/Cargo.toml index 36b8813f24..fca9d4a64b 100644 --- a/crates/print/Cargo.toml +++ b/crates/print/Cargo.toml @@ -13,14 +13,14 @@ description = "System PDF print spooler for the Craft apps: CUPS and Windows" # downstream GDI values a different Rust type identity even when the code is unchanged. # PDF loader updates below are independent of this public transport API. craft-winprint-gdi = { git = "https://github.com/storytold/winprint.rs", rev = "64e7afd4d1483512385012c340ecaaaf0f3beb7f" } +# Says why the printer list is empty when lpstat can't run (e.g. a Flatpak without CUPS tools), +# and why a job went on with the paper the request names while the driver reported only one side +# of it (storytold/craft-libs#7230). +log = "0.4" [lints] workspace = true -[target.'cfg(unix)'.dependencies] -# Says why the printer list is empty when lpstat can't run (e.g. a Flatpak without CUPS tools). -log = "0.4" - [target.'cfg(windows)'.dependencies] # Printing without starting anything (storytold/pdfcraft#1107): the printer list (EnumPrinters) # and the job (Windows.Data.Pdf drawn with Direct2D into the XPS print API, options as a diff --git a/crates/print/src/sheets.rs b/crates/print/src/sheets.rs index 0f013478b1..fa95d11c48 100644 --- a/crates/print/src/sheets.rs +++ b/crates/print/src/sheets.rs @@ -1136,6 +1136,21 @@ pub(crate) fn plan(sheets: &[Sheet], paper: (f64, f64), fit: Fit) -> Result= 1.0 && close((w, h), paper) { None } else { + // The matrix is written with at most four decimals and a PDF real has no + // exponent, so a scale that rounds away prints nothing at all and one that + // rounds up prints the wrong size. Refuse both, the way a nondefault + // UserUnit is refused: an error, never a job that spools a blank page. + let written = number(scale).parse::().unwrap_or(0.0); + if written <= 0.0 || (written - scale).abs() > scale * 0.01 { + return Err(Error::Spool(format!( + "shrink to fit cannot place sheet {} ({:.2} x {:.2} in) on the {:.2} x {:.2} in paper; nothing was sent", + i + 1, + w / 72.0, + h / 72.0, + pw / 72.0, + ph / 72.0 + ))); + } let [x0, y0, x1, y1] = sheet.bounds; let (cw, ch) = (x1 - x0, y1 - y0); // The paper in the page's unrotated space. diff --git a/crates/print/src/tests/windows_native.rs b/crates/print/src/tests/windows_native.rs index 7882a05785..12c480f221 100644 --- a/crates/print/src/tests/windows_native.rs +++ b/crates/print/src/tests/windows_native.rs @@ -555,3 +555,42 @@ fn windows_jobs_reach_the_spooler() { let missing = spool::submit(&mixed, &Job { printer: Some(name.into()), ..Job::default() }); assert!(matches!(missing, Err(Error::Spool(ref m)) if m.contains(name)), "{missing:?}"); } + +#[test] +fn shrink_to_fit_refuses_a_sheet_the_output_cannot_represent() { + use crate::sheets::{Fit, plan, read}; + // A runaway-zoom export: 16 000 000 pt wide. Written with four decimals the scale would be + // "0" -- a singular matrix, a blank page, reported back as a spooled job. + let huge = TestPage { media: Some([0.0, 0.0, 16_000_000.0, 792.0]), ..LETTER }; + let pdf = test_pdf(&[huge], false); + let sheets = read(&pdf).unwrap(); + let refused = plan(&sheets.sheets, (612.0, 792.0), Fit::Shrink { margin: 18.0 }); + assert!(matches!(refused, Err(Error::Spool(ref m)) if m.contains("shrink")), "{refused:?}"); +} + +#[test] +fn shrink_to_fit_holds_the_one_percent_scale_boundary() { + use crate::sheets::{Fit, plan, read}; + // The matrix carries the scale through the four-decimal formatter, so the plan refuses when + // what would be written is more than 1% off the real scale. Letter with an 18 pt margin gives + // 576 pt of printable width: a 118 700 pt wide, 120 000 pt tall sheet (no quarter turn) scales + // by 576 / 118 700 = 0.00485257, written 0.0049 -- 0.98% short, inside the bound, so it + // prints. + let inside = TestPage { media: Some([0.0, 0.0, 118_700.0, 120_000.0]), ..LETTER }; + let pdf = test_pdf(&[inside], false); + let sheets = read(&pdf).unwrap(); + let edits = plan(&sheets.sheets, (612.0, 792.0), Fit::Shrink { margin: 18.0 }).unwrap(); + let updated = sheets.update(&edits).unwrap(); + let frame = frame_of(&updated, pdf.len()); + let written: f64 = frame.split_whitespace().nth(1).unwrap().parse().unwrap(); + let real = edits[0].frame.as_ref().unwrap().matrix[0]; + assert!(written != real && (written - real).abs() < real * 0.01, "just inside the 1% bound the written scale is accepted: {frame}"); + + // A 118 750 pt wide sheet: 576 / 118 750 = 0.00485053, written 0.0049, 1.02% off -- refused as + // an error before anything is sent, rather than printed a percent too small. + let outside = TestPage { media: Some([0.0, 0.0, 118_750.0, 120_000.0]), ..LETTER }; + let pdf = test_pdf(&[outside], false); + let sheets = read(&pdf).unwrap(); + let refused = plan(&sheets.sheets, (612.0, 792.0), Fit::Shrink { margin: 18.0 }); + assert!(matches!(refused, Err(Error::Spool(ref m)) if m.contains("shrink") && m.contains("nothing was sent")), "{refused:?}"); +} diff --git a/crates/print/src/ticket.rs b/crates/print/src/ticket.rs index ddf2c39557..e6224df698 100644 --- a/crates/print/src/ticket.rs +++ b/crates/print/src/ticket.rs @@ -197,11 +197,24 @@ pub(crate) fn paper_names(width: f64, height: f64) -> &'static [&'static str] { } /// Whether a driver's paper name is `name`: it starts with it, ignoring case, and the name ends -/// there ("A4 210 x 297 mm", not "A4 Extra" for "A4" or "ARCH E1" for "ARCH E"). +/// there — either nothing follows ("arch d"), or a separator and the sheet's dimensions ("A4 +/// 210 x 297 mm"). After a separator, dimensions are a digit: a word is a modifier, another +/// paper ("A4 Extra", "A4 (Extra)"), and anything joined to the name without a separator is +/// another paper too ("A4Extra", "ARCH E1" for "ARCH E"). pub(crate) fn names_paper(display: Option<&str>, name: &str) -> bool { let Some(display) = display else { return false }; - display.get(..name.len()).is_some_and(|start| start.eq_ignore_ascii_case(name)) - && display.get(name.len()..).is_some_and(|rest| rest.chars().next().is_none_or(|c| !c.is_alphanumeric())) + let Some(rest) = display.get(name.len()..) else { return false }; + if !display.get(..name.len()).is_some_and(|start| start.eq_ignore_ascii_case(name)) { + return false; + } + let after = rest.trim_start_matches(|c: char| !c.is_alphanumeric()); + match after.chars().next() { + // The name ends here, or a separator introduces the sheet's dimensions. + None => true, + Some(c) if !c.is_alphabetic() => after.len() < rest.len(), + // A word, directly after the name or after a separator, is a modifier: another paper. + Some(_) => false, + } } /// A driver paper offered for the job: its size in micrometres (as the driver lists it), its @@ -218,6 +231,17 @@ pub(crate) struct Paper<'a> { /// The driver paper for a sheet of `width` × `height` points (either way round): within a /// quarter of a millimetre, preferring the one named like the standard size, then a Print Schema /// keyword, then the closest; on a tie the driver's own order. Its index in `papers`. +/// +/// An entry the driver keeps only one side of (the other reads zero, a legacy host-based driver's +/// DEVMODE metric, storytold/craft-libs#7230) is a candidate of last resort (INV-4): only when no +/// full entry matched, only a Print Schema keyword entry, and only while its known side agrees +/// with the sheet, either way round. A single such entry is still refused when its own name is +/// known and contradicts the requested standard sheet (INV-4): a known conflicting name is +/// evidence against the choice, and failing closed is safer than a guess. Without a name there is +/// nothing contradicting, so the agreement alone is enough. Several such entries that all agree +/// (a Letter and a Legal option share a width) are told apart by name, as full candidates are: +/// the one named like the requested standard sheet wins, and when that leaves more than one, or +/// none, nothing is chosen — a guess here would lay the sheets out for the wrong paper. pub(crate) fn matching_paper(papers: &[Paper<'_>], width: f64, height: f64) -> Option { let (w, h) = (micrometres(width.min(height))?, micrometres(width.max(height))?); let names = paper_names(width, height); @@ -231,7 +255,33 @@ pub(crate) fn matching_paper(papers: &[Paper<'_>], width: f64, height: f64) -> O }) .collect(); candidates.sort_by_key(|(_, p, off)| (!names.iter().any(|n| names_paper(p.name, n)), !p.keyword, *off)); - candidates.first().map(|(i, _, _)| *i) + if let Some(index) = candidates.first().map(|(i, _, _)| *i) { + return Some(index); + } + let agrees = |side: u32| side.abs_diff(w) <= PAPER_TOLERANCE || side.abs_diff(h) <= PAPER_TOLERANCE; + let partials: Vec = papers + .iter() + .enumerate() + .filter(|(_, p)| p.keyword && (p.width == 0) != (p.height == 0) && (p.width == 0 || agrees(p.width)) && (p.height == 0 || agrees(p.height))) + .map(|(i, _)| i) + .collect(); + match partials.as_slice() { + [only] => { + // INV-4: a known name that contradicts the requested standard sheet is evidence + // against this single partial record — refuse it; without a name, the known side's + // agreement is all the evidence there is, and the record stands. + let contradicts = papers[*only].name.is_some_and(|name| !names.iter().any(|n| names_paper(Some(name), n))); + (!contradicts).then_some(*only) + } + // Ambiguous by agreement alone: a partial named like the requested standard sheet wins. + _ => { + let named: Vec = partials.iter().copied().filter(|i| names.iter().any(|n| names_paper(papers[*i].name, n))).collect(); + match named.as_slice() { + [only] => Some(*only), + _ => None, + } + } + } } fn named(node: roxmltree::Node<'_, '_>, local: &str) -> bool { @@ -274,12 +324,32 @@ pub(crate) fn two_sided(xml: &str) -> Option { ) } -/// The integer value of the Print Schema element under `node` with this keyword name. -fn integer(node: roxmltree::Node<'_, '_>, tag: &str, name: &str) -> Option { +/// The `Value` of the Print Schema element `element`: its own, or one a `ParameterRef` names +/// through the `ParameterInit` under the document's root that sets it (a driver may keep a paper +/// side or a resolution this way). `None` when the element has neither, or names a parameter the +/// ticket does not set. +fn resolved_value<'a>(document: &'a roxmltree::Document<'a>, element: roxmltree::Node<'a, 'a>) -> Option> { + let value = element.children().find(|v| v.has_tag_name((NS_PSF, "Value")) || v.has_tag_name((NS_PSF, "ParameterRef")))?; + if value.has_tag_name((NS_PSF, "Value")) { + return Some(value); + } + let parameter = expanded(value, value.attribute("name")?); + document + .root_element() + .children() + .filter(|p| p.has_tag_name((NS_PSF, "ParameterInit"))) + .find(|p| p.attribute("name").is_some_and(|name| expanded(*p, name) == parameter))? + .children() + .find(|v| v.has_tag_name((NS_PSF, "Value"))) +} + +/// The integer value of the Print Schema element under `node` with this keyword name, direct or +/// through a `ParameterRef` the ticket resolves ([`resolved_value`]). +fn integer(document: &roxmltree::Document<'_>, node: roxmltree::Node<'_, '_>, tag: &str, name: &str) -> Option { node.descendants() .find(|n| n.has_tag_name((NS_PSF, tag)) && named(*n, name)) - .and_then(|n| n.children().find(|v| v.has_tag_name((NS_PSF, "Value")))) - .and_then(|n| n.text()) + .and_then(|element| resolved_value(document, element)) + .and_then(|value| value.text()) .and_then(|v| v.trim().parse::().ok()) } @@ -287,14 +357,35 @@ fn integer(node: roxmltree::Node<'_, '_>, tag: &str, name: &str) -> Option /// paper (when `paper` is given, that one, to a quarter of a millimetre). Returns the paper's /// width and height in micrometres as the driver lists it. Only those schema fields are read: /// some drivers return empty vendor parameters that a stricter parser would refuse. +/// +/// A zero or unreadable side (`MediaSizeWidth` gone) is roll-like only while the request itself +/// names no sheet (INV-2): a legacy host-based driver keeps the paper metric in its DEVMODE +/// extension and reads back a zero side for a real sheet (HP LaserJet P1102, storytold/craft-libs#7230), so +/// with a sheet named the job falls back to the size the request asked for (INV-1, +/// fail-closed: every refusal here is before anything reaches the spooler). A side the driver +/// did report must agree with the sheet asked for, either way round (INV-3); both sides gone is +/// refused whatever the request names (INV-5). The fallback is logged (INV-7). pub(crate) fn verify_ticket(xml: &str, paper: Option<(u32, u32)>, landscape: bool) -> Result<(u32, u32), Error> { let document = crate::xml::parse(xml).map_err(spool_error)?; let feature = |name: &str| document.root_element().children().find(|n| n.has_tag_name((NS_PSF, "Feature")) && named(*n, name)); let media = feature("PageMediaSize").ok_or_else(|| spool_error("the printer's driver did not confirm the paper size; nothing was sent"))?; - let size = integer(media, "ScoredProperty", "MediaSizeWidth") - .zip(integer(media, "ScoredProperty", "MediaSizeHeight")) - .filter(|(w, h)| *w > 0 && *h > 0) - .ok_or_else(|| spool_error("the printer's driver gave a paper without a size (a roll?); nothing was sent"))?; + let width = integer(&document, media, "ScoredProperty", "MediaSizeWidth").filter(|w| *w > 0); + let height = integer(&document, media, "ScoredProperty", "MediaSizeHeight").filter(|h| *h > 0); + let without_a_size = spool_error("the printer's driver gave a paper without a size (a roll?); nothing was sent"); + let size = match (width, height, paper) { + (Some(w), Some(h), _) => (w, h), + (None, None, _) | (_, _, None) => return Err(without_a_size), + (Some(reported), None, Some(wanted)) | (None, Some(reported), Some(wanted)) => { + let (w, h) = wanted; + // Either way round: the one side the driver did report against the sheet's width or height. + let agrees = |other: u32| reported.abs_diff(other) <= PAPER_TOLERANCE; + if !agrees(w) && !agrees(h) { + return Err(spool_error("the printer's driver changed the paper size; nothing was sent (choose a paper size it has)")); + } + log::warn!("the printer's driver reported only {reported} µm of the paper; going on with the requested {w} × {h} µm"); + (w, h) + } + }; if let Some((w, h)) = paper { let same = |a: (u32, u32), b: (u32, u32)| a.0.abs_diff(b.0) <= PAPER_TOLERANCE && a.1.abs_diff(b.1) <= PAPER_TOLERANCE; if !same(size, (w, h)) && !same(size, (h, w)) { @@ -384,7 +475,9 @@ pub(crate) fn one_job_sides(xml: &str) -> Option { _ => return None, } } - if features(&["JobNUpAllDocumentsContiguously", "DocumentNUp"]).any(|f| integer(f, "ScoredProperty", "PagesPerSheet").is_some_and(|n| n > 1)) { + if features(&["JobNUpAllDocumentsContiguously", "DocumentNUp"]) + .any(|f| integer(&document, f, "ScoredProperty", "PagesPerSheet").is_some_and(|n| n > 1)) + { return None; } if features(&["JobBindAllDocuments", "DocumentBinding", "JobStapleAllDocuments", "DocumentStaple"]) @@ -421,7 +514,7 @@ pub(crate) fn verify_job_options(xml: &str, job: &Job, pages: usize, offered: Of }; let refused = |field: &str| spool_error(format!("the printer's driver did not retain the requested {field}; nothing was sent")); let copies = job.copies.clamp(1, 999); - if integer(root, "ParameterInit", "JobCopiesAllDocuments") != Some(copies) { + if integer(&document, root, "ParameterInit", "JobCopiesAllDocuments") != Some(copies) { return Err(refused("copy count")); } if copies > 1 && pages > 1 && !option("DocumentCollate").is_some_and(|n| named(n, if job.collate { "Collated" } else { "Uncollated" })) { @@ -497,19 +590,7 @@ fn feature_option(document: &roxmltree::Document<'_>, feature: &str) -> Option value, - reference => { - let parameter = expanded(reference, reference.attribute("name")?); - document - .root_element() - .children() - .filter(|p| p.has_tag_name((NS_PSF, "ParameterInit"))) - .find(|p| p.attribute("name").is_some_and(|name| expanded(*p, name) == parameter))? - .children() - .find(|v| v.has_tag_name((NS_PSF, "Value")))? - } - }; + let value = resolved_value(document, n)?; let text = value.text()?.trim(); let value = match text.parse::() { _ if is_qname_value(value) => expanded(value, text), @@ -766,11 +847,11 @@ pub(crate) fn prefixes_unlike_the_drivers(ticket: &str, driver: &str) -> Option< pub(crate) fn imageable_margin(capabilities_xml: &str) -> Option { let document = crate::xml::parse(capabilities_xml).ok()?; let imageable = document.root_element().children().find(|n| n.has_tag_name((NS_PSF, "Property")) && named(*n, "PageImageableSize"))?; - let width = integer(imageable, "Property", "ImageableSizeWidth")?; - let height = integer(imageable, "Property", "ImageableSizeHeight")?; + let width = integer(&document, imageable, "Property", "ImageableSizeWidth")?; + let height = integer(&document, imageable, "Property", "ImageableSizeHeight")?; let area = imageable.children().find(|n| n.has_tag_name((NS_PSF, "Property")) && named(*n, "ImageableArea"))?; - let (x, y) = (integer(area, "Property", "OriginWidth")?, integer(area, "Property", "OriginHeight")?); - let (w, h) = (integer(area, "Property", "ExtentWidth")?, integer(area, "Property", "ExtentHeight")?); + let (x, y) = (integer(&document, area, "Property", "OriginWidth")?, integer(&document, area, "Property", "OriginHeight")?); + let (w, h) = (integer(&document, area, "Property", "ExtentWidth")?, integer(&document, area, "Property", "ExtentHeight")?); let right = width.checked_sub(x)?.checked_sub(w)?; let bottom = height.checked_sub(y)?.checked_sub(h)?; Some(x.max(y).max(right).max(bottom)) @@ -1058,6 +1139,89 @@ mod tests { assert!(verify_ticket(", height: Option) -> String { + let side = |name: &str, value: Option| { + value.map_or(String::new(), |v| { + format!(r#"{v}"#) + }) + }; + format!( + r#" +{}{} + + +"#, + side("MediaSizeWidth", width), + side("MediaSizeHeight", height) + ) + } + + /// storytold/craft-libs#7230: the driver reports one side of the paper as zero for a real + /// sheet. With the sheet the request names, the job goes on with the size it asked for; a + /// side the driver did report must still agree with it, and a request that names no sheet is + /// refused as before. + #[test] + fn a_legacy_v3_drivers_zero_side_falls_back_to_the_requested_paper() { + let a4 = (210_000, 297_000); + assert_eq!(verify_ticket(&validated_partial(None, Some(297_000)), Some(a4), false), Ok(a4)); + assert_eq!(verify_ticket(&validated_partial(Some(0), Some(297_000)), Some(a4), false), Ok(a4), "a zero side is a missing one"); + assert_eq!(verify_ticket(&validated_partial(Some(297_000), None), Some(a4), false), Ok(a4), "either way round"); + // 0.5 pt (176 µm) inside the tolerance still agrees. + assert_eq!(verify_ticket(&validated_partial(Some(0), Some(297_176)), Some(a4), false), Ok(a4)); + assert_eq!(verify_ticket(&validated_partial(Some(0), Some(297_250)), Some(a4), false), Ok(a4), "exactly the tolerance"); + // A side that disagrees means the driver changed the paper, not that it has a roll. + let changed = verify_ticket(&validated_partial(Some(0), Some(279_400)), Some(a4), false).unwrap_err(); + assert!(changed.to_string().contains("changed the paper size"), "{changed}"); + assert!(!changed.to_string().contains("roll"), "{changed}"); + assert!(verify_ticket(&validated_partial(Some(0), Some(297_251)), Some(a4), false).is_err(), "one µm past the tolerance"); + // Without a sheet named the zero side stays roll-like. + assert!(verify_ticket(&validated_partial(Some(0), Some(297_000)), None, false).is_err()); + assert!(verify_ticket(&validated_partial(None, Some(297_000)), None, false).is_err()); + // Both sides gone is refused whatever the request names. + for wanted in [Some(a4), None] { + for (width, height) in [(None, None), (Some(0), Some(0))] { + let refused = verify_ticket(&validated_partial(width, height), wanted, false).unwrap_err(); + assert!(refused.to_string().contains("roll"), "{refused}"); + } + } + } + + /// A validated ticket whose width the option refers to a parameter the ticket sets + /// (`MediaSizeWidth` a `ParameterRef`, storytold/craft-libs#1225), as a driver writes one. + fn validated_referenced(width: u32, height: u32) -> String { + format!( + r#" +{width} + + +{height} + + + +"# + ) + } + + /// A paper side a driver keeps in a `ParameterRef` is resolved through the `ParameterInit` + /// the ticket sets, and checked like a direct one: a referenced width that disagrees with the + /// sheet the request names is refused, one that agrees is taken. + #[test] + fn a_referenced_paper_side_is_resolved_through_the_parameter_it_names() { + let a4 = (210_000, 297_000); + assert_eq!(verify_ticket(&validated_referenced(210_000, 297_000), Some(a4), false), Ok(a4)); + assert_eq!(verify_ticket(&validated_referenced(209_750, 297_000), Some(a4), false), Ok((209_750, 297_000)), "exactly the tolerance"); + // A referenced size that disagrees is refused, not rewritten from the request. + let changed = verify_ticket(&validated_referenced(400_000, 297_000), Some(a4), false).unwrap_err(); + assert!(changed.to_string().contains("changed the paper size"), "{changed}"); + // A reference to a parameter the ticket does not set is a missing side, which falls back + // to the requested paper like any unreadable one. + let unset = + validated_referenced(400_000, 297_000).replace(r#"name="psk:PageMediaSizeWidth"> Some((m.size().width_in_micron(), m.size().height_in_micron())), + (Some(m), _) => { + let size = (m.size().width_in_micron(), m.size().height_in_micron()); + // INV-6: a driver that keeps one side of the paper metric in its DEVMODE extension + // (storytold/craft-libs#7230) reports a zero side; the wanted size then is the sheet + // the job asked for, not the zero record, which would poison the cross-check and hand + // `sheets::plan` a width of zero. + if size.0 == 0 || size.1 == 0 { + match (ticket::micrometres(sheet.0), ticket::micrometres(sheet.1)) { + (Some(w), Some(h)) => Some((w, h)), + _ => { + return Err(spool_error(format!( + "{} has no {:.2} × {:.2} inch paper; choose a paper size it has, or add this one in its driver", + device.name(), + sheet.0 / 72.0, + sheet.1 / 72.0 + ))); + } + } + } else { + Some(size) + } + } (None, Scaling::ShrinkToFit) => None, (None, Scaling::Exact) => { return Err(spool_error(format!( diff --git a/crates/ps/Cargo.toml b/crates/ps/Cargo.toml new file mode 100644 index 0000000000..baa9050e4d --- /dev/null +++ b/crates/ps/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "craft-ps" +description = "PostScript and EPS for Craft apps: an EPS interpreter that paints into PDF" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[features] +default = [] +read = ["dep:craft-eps", "dep:pdf-writer", "dep:miniz_oxide", "dep:weezl", "dep:skrifa", "dep:kurbo"] + +[dependencies] +craft-eps = { workspace = true, optional = true } +pdf-writer = { workspace = true, optional = true } +miniz_oxide = { workspace = true, optional = true } +weezl = { workspace = true, optional = true } +skrifa = { workspace = true, optional = true } +kurbo = { workspace = true, optional = true } + +[[example]] +name = "eps2pdf" +required-features = ["read"] diff --git a/crates/ps/README.md b/crates/ps/README.md new file mode 100644 index 0000000000..51deedcc2c --- /dev/null +++ b/crates/ps/README.md @@ -0,0 +1,50 @@ +# craft-ps + +PostScript and EPS for the Craft apps. No feature is enabled by default. + +| Feature | Provides | +| --- | --- | +| `read` | An EPS interpreter: runs the program and returns what it paints as a one-page PDF | + +Writing PostScript and EPS (craft-libs #115) is planned as a separate feature next to `read`. + +## Reading EPS + +`read::eps_to_pdf(bytes, limits)` runs an EPS (plain, or DOS EPS with a binary header) and +returns a one-page PDF 1.4 the size of its bounding box: vectors stay vectors, CMYK and spot +colours stay as they are, so an app can draw and export the result as a placed PDF. +`read::cached_pdf` converts with the default limits and remembers the result by content. +`is_eps`, `bounding_box` and `postscript_section` read the file without running it. +EPS binary sections and DSC comments are read by `craft-eps`. + +It is written from the PostScript Language Reference (third edition), the EPS specification, +the Type 1 Font Format and Adobe Technical Notes 5012 (Type 42), 5176 (CFF) and 5177 (Type 2 +charstrings); no GPL code was used. It covers what EPS files use: + +- the language: Level 3 operators, an explicit execution stack (no Rust recursion for + PostScript control flow), `stopped`, resources, `eexec`; +- graphics: paths, painting, clipping, `strokepath`, user paths and forms; +- colour: device spaces, Separation and DeviceN, Indexed, ICCBased, Lab; +- images, with filters decoded as they are read (ASCIIHex, ASCII85, RunLength, LZW, Flate with + predictors, SubFile, ReusableStream; JPEG is passed through); +- smooth shadings (types 1–7, meshes included), shading and tiling patterns; +- text in Type 1, Type 3, Type 42 and CFF fonts (`StartData`), CIDFonts and composite fonts + through CMaps, horizontal and vertical. + +Not covered: Level 2 binary tokens, CIDFontType 0 with Type 1 charstrings, CIDFontType 1 and +the old composite FMapTypes other than 2 and 9. + +## Limits + +`Limits { steps, memory, stack_overflow_noop, skip_images, keep_unpainted, zero_division_zero, fallback_font }` bounds one conversion. The optional font callback supplies host stand-ins for missing fonts; booleans let a host retain prior operand-overflow, image, partial-page, and numeric-coercion behavior. Every operator charges the work it does in +proportion to its operands (elements copied or searched, path segments, glyphs, samples) +against `steps` as it goes, and every byte read or decoded at any filter level counts too, so +the step limit bounds run time. `memory` bounds everything a conversion makes, copies +included. The defaults are 50 million steps and 1 GiB, or 20 million and 256 MiB on wasm32; +real EPS files use at most a few million steps and tens of megabytes, and a program that runs +into the limits ends within seconds. By default a program that fails or exceeds them before +painting anything gives `Err`; setting `keep_unpainted` returns a blank page with the warning. +One that fails later keeps what it painted (with a warning). + +`cargo run -p craft-ps --features read --example eps2pdf -- in.eps out.pdf` converts one file +and prints the steps and memory it used. diff --git a/crates/ps/examples/eps2pdf.rs b/crates/ps/examples/eps2pdf.rs new file mode 100644 index 0000000000..a3cbfe0cf0 --- /dev/null +++ b/crates/ps/examples/eps2pdf.rs @@ -0,0 +1,41 @@ +//! `cargo run -p craft-ps --features read --example eps2pdf -- in.eps out.pdf`: convert one EPS. + +fn main() -> std::process::ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let (Some(input), Some(output)) = (args.first(), args.get(1)) else { + eprintln!("usage: eps2pdf in.eps out.pdf"); + return std::process::ExitCode::FAILURE; + }; + let bytes = match std::fs::read(input) { + Ok(b) => b, + Err(e) => { + eprintln!("{input}: {e}"); + return std::process::ExitCode::FAILURE; + } + }; + let t = std::time::Instant::now(); + match craft_ps::read::eps_to_pdf(&bytes, craft_ps::read::Limits::default()) { + Ok(c) => { + eprintln!( + "{input}: {:.0} ms, bbox {:?}, {} warnings, {} steps, {} KiB", + t.elapsed().as_secs_f64() * 1000.0, + c.bbox, + c.warnings.len(), + c.steps, + c.memory / 1024 + ); + for w in c.warnings.iter().take(20) { + eprintln!(" {w}"); + } + if let Err(e) = std::fs::write(output, &c.pdf) { + eprintln!("{output}: {e}"); + return std::process::ExitCode::FAILURE; + } + std::process::ExitCode::SUCCESS + } + Err(e) => { + eprintln!("{input}: {e} ({:.0} ms)", t.elapsed().as_secs_f64() * 1000.0); + std::process::ExitCode::FAILURE + } + } +} diff --git a/crates/ps/src/lib.rs b/crates/ps/src/lib.rs new file mode 100644 index 0000000000..ab53832595 --- /dev/null +++ b/crates/ps/src/lib.rs @@ -0,0 +1,9 @@ +//! PostScript and EPS for the Craft apps. +//! +//! - [`read`] (feature `read`): runs an EPS and gives what it paints as a one-page vector PDF, +//! for apps that place EPS files as graphics. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(feature = "read")] +pub mod read; diff --git a/crates/ps/src/read/cff.rs b/crates/ps/src/read/cff.rs new file mode 100644 index 0000000000..bbf7c4c8de --- /dev/null +++ b/crates/ps/src/read/cff.rs @@ -0,0 +1,604 @@ +//! CFF font sets and Type 2 charstrings (Adobe Technical Notes 5176 and 5177): name-keyed and +//! CID-keyed fonts, as `StartData` defines them. + +use crate::read::gstate::Seg; +use crate::read::type1::Glyph; + +/// The most glyphs, subroutines or INDEX entries read. +const MAX_ENTRIES: usize = 200_000; +const MAX_OPS: usize = 200_000; +const MAX_DEPTH: usize = 10; + +#[derive(Debug, Clone, Default)] +struct Private { + subrs: Vec<(usize, usize)>, + default_width: f64, + nominal_width: f64, +} + +#[derive(Debug, Clone)] +pub struct Font { + pub name: Vec, + pub matrix: [f64; 6], + pub bbox: [f64; 4], + /// Glyph names (name-keyed) by glyph index. + pub names: Vec>, + /// Code → glyph index (name-keyed fonts). + pub encoding: Vec<(u8, u32)>, + /// CID by glyph index (CID-keyed fonts), and the registry/ordering/supplement. + pub cids: Option>, + pub ros: Option<(Vec, Vec, i64)>, + /// CID → glyph index, made on first lookup. + by_cid: std::cell::OnceCell>, + charstrings: Vec<(usize, usize)>, + privates: Vec, + fd_select: Vec, +} + +#[derive(Debug)] +pub struct FontSet { + pub data: Vec, + gsubrs: Vec<(usize, usize)>, + pub fonts: Vec, +} + +fn u16_at(d: &[u8], i: usize) -> Option { + Some(usize::from(u16::from_be_bytes([*d.get(i)?, *d.get(i + 1)?]))) +} + +fn offset(d: &[u8], i: usize, size: usize) -> Option { + let mut v = 0usize; + for k in 0..size { + v = v.checked_mul(256)?.checked_add(usize::from(*d.get(i + k)?))?; + } + Some(v) +} + +/// An INDEX at `at`: its entries as (start, end) in `d`, and where it ends. +fn index(d: &[u8], at: usize) -> Option<(Vec<(usize, usize)>, usize)> { + let count = u16_at(d, at)?; + if count == 0 { + return Some((Vec::new(), at + 2)); + } + if count > MAX_ENTRIES { + return None; + } + let size = usize::from(*d.get(at + 2)?); + if !(1..=4).contains(&size) { + return None; + } + let offs_at = at + 3; + let data_at = offs_at + (count + 1) * size - 1; + let mut out = Vec::with_capacity(count); + let mut prev = offset(d, offs_at, size)?; + for i in 1..=count { + let next = offset(d, offs_at + i * size, size)?; + let (s, e) = (data_at.checked_add(prev)?, data_at.checked_add(next)?); + if e < s || e > d.len() { + return None; + } + out.push((s, e)); + prev = next; + } + let end = data_at.checked_add(prev)?; + Some((out, end)) +} + +#[derive(Debug, Default)] +struct Dict { + entries: Vec<(u16, Vec)>, +} + +impl Dict { + fn get(&self, op: u16) -> Option<&[f64]> { + self.entries.iter().find(|(o, _)| *o == op).map(|(_, v)| v.as_slice()) + } + + fn num(&self, op: u16) -> Option { + self.get(op)?.first().copied() + } +} + +fn dict(d: &[u8]) -> Dict { + let mut out = Dict::default(); + let mut ops: Vec = Vec::new(); + let mut i = 0; + while let Some(&b) = d.get(i) { + i += 1; + match b { + 0..=21 => { + let op = if b == 12 { + let e = d.get(i).copied().unwrap_or(0); + i += 1; + 1200 + u16::from(e) + } else { + u16::from(b) + }; + out.entries.push((op, std::mem::take(&mut ops))); + } + 28 => { + let v = i16::from_be_bytes([d.get(i).copied().unwrap_or(0), d.get(i + 1).copied().unwrap_or(0)]); + i += 2; + ops.push(f64::from(v)); + } + 29 => { + let v = i32::from_be_bytes([0, 1, 2, 3].map(|k| d.get(i + k).copied().unwrap_or(0))); + i += 4; + ops.push(f64::from(v)); + } + 30 => { + // A real: nibbles. + let mut s = String::new(); + 'real: while let Some(&n) = d.get(i) { + i += 1; + for nib in [n >> 4, n & 15] { + match nib { + 0..=9 => s.push(char::from(b'0' + nib)), + 0xa => s.push('.'), + 0xb => s.push('E'), + 0xc => s.push_str("E-"), + 0xe => s.push('-'), + 0xf => break 'real, + _ => {} + } + } + } + ops.push(s.parse().unwrap_or(0.0)); + } + 32..=246 => ops.push(f64::from(b) - 139.0), + 247..=250 => { + let w = d.get(i).copied().unwrap_or(0); + i += 1; + ops.push((f64::from(b) - 247.0) * 256.0 + f64::from(w) + 108.0); + } + 251..=254 => { + let w = d.get(i).copied().unwrap_or(0); + i += 1; + ops.push(-(f64::from(b) - 251.0) * 256.0 - f64::from(w) - 108.0); + } + _ => {} + } + if ops.len() > 64 { + break; + } + } + out +} + +fn private(d: &[u8], top: &Dict) -> Private { + let Some(v) = top.get(18) else { return Private::default() }; + let (size, off) = (v.first().copied().unwrap_or(0.0).max(0.0) as usize, v.get(1).copied().unwrap_or(0.0).max(0.0) as usize); + let Some(bytes) = off.checked_add(size).and_then(|e| d.get(off..e)) else { return Private::default() }; + let p = dict(bytes); + let subrs = p.num(19).and_then(|rel| index(d, off.checked_add(rel.max(0.0) as usize)?)).map(|(v, _)| v).unwrap_or_default(); + Private { subrs, default_width: p.num(20).unwrap_or(0.0), nominal_width: p.num(21).unwrap_or(0.0) } +} + +/// The glyph index → SID (or CID) charset. +fn charset(d: &[u8], at: usize, glyphs: usize) -> Vec { + let mut out = vec![0u32]; + // Predefined charsets (ISOAdobe and the expert ones): glyph index = SID. + if at <= 2 { + return (0..glyphs as u32).collect(); + } + let Some(&format) = d.get(at) else { return out }; + let mut i = at + 1; + while out.len() < glyphs { + match format { + 0 => match u16_at(d, i) { + Some(s) => { + out.push(s as u32); + i += 2; + } + None => break, + }, + 1 | 2 => { + let (Some(first), Some(n)) = (u16_at(d, i), if format == 1 { d.get(i + 2).map(|v| usize::from(*v)) } else { u16_at(d, i + 2) }) + else { + break; + }; + i += if format == 1 { 3 } else { 4 }; + for k in 0..=n { + if out.len() >= glyphs { + break; + } + out.push((first + k) as u32); + } + } + _ => break, + } + } + out +} + +fn fd_select(d: &[u8], at: usize, glyphs: usize) -> Vec { + let mut out = vec![0u8; glyphs]; + match d.get(at) { + Some(0) => { + for (g, slot) in out.iter_mut().enumerate() { + *slot = d.get(at + 1 + g).copied().unwrap_or(0); + } + } + Some(3) => { + let n = u16_at(d, at + 1).unwrap_or(0); + for r in 0..n { + let base = at + 3 + r * 3; + let (Some(first), Some(fd), Some(next)) = (u16_at(d, base), d.get(base + 2), u16_at(d, base + 3)) else { break }; + for g in first..next.min(glyphs) { + if let Some(slot) = out.get_mut(g) { + *slot = *fd; + } + } + } + } + _ => {} + } + out +} + +fn sid_name(sid: u32, strings: &[(usize, usize)], d: &[u8]) -> Vec { + let sid = sid as usize; + match crate::read::cff_strings::standard(sid) { + Some(n) => n.into_bytes(), + None => strings + .get(sid - crate::read::cff_strings::COUNT) + .and_then(|(s, e)| d.get(*s..*e)) + .map(<[u8]>::to_vec) + .unwrap_or_else(|| b".notdef".to_vec()), + } +} + +pub fn parse(data: Vec) -> Option { + let d = &data; + let hdr = usize::from(*d.get(2)?); + let (names, after_names) = index(d, hdr)?; + let (tops, after_tops) = index(d, after_names)?; + let (strings, after_strings) = index(d, after_tops)?; + let (gsubrs, _) = index(d, after_strings)?; + let mut fonts = Vec::new(); + for (k, &(ts, te)) in tops.iter().enumerate() { + let top = dict(d.get(ts..te)?); + let name = names.get(k).and_then(|(s, e)| d.get(*s..*e)).map(<[u8]>::to_vec).unwrap_or_default(); + let (charstrings, _) = index(d, top.num(17)?.max(0.0) as usize)?; + let glyphs = charstrings.len(); + let matrix = + top.get(1207).filter(|m| m.len() == 6).map(|m| [m[0], m[1], m[2], m[3], m[4], m[5]]).unwrap_or([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]); + let bbox = top.get(5).filter(|b| b.len() == 4).map(|b| [b[0], b[1], b[2], b[3]]).unwrap_or([0.0, 0.0, 1000.0, 1000.0]); + let cs = charset(d, top.num(15).unwrap_or(0.0).max(0.0) as usize, glyphs); + let ros = top.get(1230).map(|v| { + let s = |i: usize| sid_name(v.get(i).copied().unwrap_or(0.0) as u32, &strings, d); + (s(0), s(1), v.get(2).copied().unwrap_or(0.0) as i64) + }); + let (privates, fds, names_out, cids) = if ros.is_some() { + let fdarray = top.num(1236).and_then(|o| index(d, o.max(0.0) as usize)).map(|(v, _)| v).unwrap_or_default(); + let privates = fdarray.iter().map(|(s, e)| d.get(*s..*e).map(|b| private(d, &dict(b))).unwrap_or_default()).collect(); + let fds = top.num(1237).map(|o| fd_select(d, o.max(0.0) as usize, glyphs)).unwrap_or_else(|| vec![0; glyphs]); + (privates, fds, Vec::new(), Some(cs)) + } else { + let names_out: Vec> = cs.iter().map(|sid| sid_name(*sid, &strings, d)).collect(); + (vec![private(d, &top)], Vec::new(), names_out, None) + }; + // Encoding (name-keyed): predefined Standard, or format 0/1 code lists. + let mut encoding = Vec::new(); + if cids.is_none() { + match top.num(16).unwrap_or(0.0) as usize { + 0 => { + let std = crate::read::encodings::standard(); + for (code, n) in std.iter().enumerate() { + if let Some(g) = names_out.iter().position(|x| x == n.as_bytes()) { + encoding.push((code as u8, g as u32)); + } + } + } + 1 => {} + at => { + let fmt = d.get(at).copied().unwrap_or(0) & 0x7f; + let n = usize::from(d.get(at + 1).copied().unwrap_or(0)); + if fmt == 0 { + for g in 0..n { + if let Some(c) = d.get(at + 2 + g) { + encoding.push((*c, g as u32 + 1)); + } + } + } else { + let mut g = 1u32; + for r in 0..n { + let (Some(first), Some(left)) = (d.get(at + 2 + r * 2), d.get(at + 3 + r * 2)) else { break }; + for k in 0..=u32::from(*left) { + encoding.push((first.wrapping_add(k as u8), g)); + g += 1; + } + } + } + } + } + } + fonts.push(Font { + name, + matrix, + bbox, + names: names_out, + encoding, + cids, + ros, + by_cid: std::cell::OnceCell::new(), + charstrings, + privates, + fd_select: fds, + }); + } + Some(FontSet { data, gsubrs, fonts }) +} + +fn bias(n: usize) -> i64 { + if n < 1240 { + 107 + } else if n < 33900 { + 1131 + } else { + 32768 + } +} + +struct Run { + path: Vec, + x: f64, + y: f64, + open: bool, + stack: Vec, + hints: usize, + width: Option, + ops: usize, + done: bool, +} + +impl Run { + fn move_to(&mut self, dx: f64, dy: f64) { + if self.open { + self.path.push(Seg::Close); + } + self.x += dx; + self.y += dy; + self.path.push(Seg::Move(self.x, self.y)); + self.open = true; + } + + fn line(&mut self, dx: f64, dy: f64) { + self.x += dx; + self.y += dy; + self.path.push(Seg::Line(self.x, self.y)); + } + + fn curve(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) { + let (x1, y1) = (self.x + a, self.y + b); + let (x2, y2) = (x1 + c, y1 + d); + let (x3, y3) = (x2 + e, y2 + f); + self.path.push(Seg::Curve(x1, y1, x2, y2, x3, y3)); + self.x = x3; + self.y = y3; + } + + /// The first stack-clearing operator may carry the width before its arguments: there is + /// one when the count's parity differs from the operator's own (`expected_odd`). + fn take_width(&mut self, expected_odd: bool) { + if self.width.is_none() { + let present = !self.stack.is_empty() && (self.stack.len() % 2 == 1) != expected_odd; + self.width = Some(if present { self.stack.remove(0) } else { f64::NAN }); + } + } +} + +impl FontSet { + fn bytes(&self, r: (usize, usize)) -> &[u8] { + self.data.get(r.0..r.1).unwrap_or(&[]) + } + + fn exec(&self, code: &[u8], local: &[(usize, usize)], run: &mut Run, depth: usize) -> Option<()> { + if depth > MAX_DEPTH { + return None; + } + let mut i = 0; + while i < code.len() && !run.done { + run.ops += 1; + if run.ops > MAX_OPS || run.stack.len() > 96 { + return None; + } + let b = *code.get(i)?; + i += 1; + match b { + 32..=246 => run.stack.push(f64::from(b) - 139.0), + 247..=250 => { + let w = *code.get(i)?; + i += 1; + run.stack.push((f64::from(b) - 247.0) * 256.0 + f64::from(w) + 108.0); + } + 251..=254 => { + let w = *code.get(i)?; + i += 1; + run.stack.push(-(f64::from(b) - 251.0) * 256.0 - f64::from(w) - 108.0); + } + 28 => { + let v = i16::from_be_bytes([*code.get(i)?, *code.get(i + 1)?]); + i += 2; + run.stack.push(f64::from(v)); + } + 255 => { + let v = i32::from_be_bytes([*code.get(i)?, *code.get(i + 1)?, *code.get(i + 2)?, *code.get(i + 3)?]); + i += 4; + run.stack.push(f64::from(v) / 65536.0); + } + // hstem, vstem, hstemhm, vstemhm: count the hints (an odd count carries the width). + 1 | 3 | 18 | 23 => { + run.take_width(false); + run.hints += run.stack.len() / 2; + run.stack.clear(); + } + 19 | 20 => { + // hintmask, cntrmask: implicit vstems, then the mask bytes. + run.take_width(false); + run.hints += run.stack.len() / 2; + run.stack.clear(); + i += run.hints.div_ceil(8); + } + 21 => { + run.take_width(false); + let s = std::mem::take(&mut run.stack); + run.move_to(s.first().copied().unwrap_or(0.0), s.get(1).copied().unwrap_or(0.0)); + } + 22 | 4 => { + run.take_width(true); + let s = std::mem::take(&mut run.stack); + let v = s.first().copied().unwrap_or(0.0); + if b == 22 { run.move_to(v, 0.0) } else { run.move_to(0.0, v) } + } + 5 => { + let s = std::mem::take(&mut run.stack); + for &[x, y] in s.as_chunks::<2>().0 { + run.line(x, y); + } + } + 6 | 7 => { + let s = std::mem::take(&mut run.stack); + let mut horizontal = b == 6; + for v in s { + if horizontal { + run.line(v, 0.0) + } else { + run.line(0.0, v) + } + horizontal = !horizontal; + } + } + 8 => { + let s = std::mem::take(&mut run.stack); + for &[a, b2, c, d, e, f] in s.as_chunks::<6>().0 { + run.curve(a, b2, c, d, e, f); + } + } + 24 => { + // rcurveline + let s = std::mem::take(&mut run.stack); + let n = s.len().saturating_sub(2) / 6; + for &[a, b2, c, d, e, f] in s.as_chunks::<6>().0.iter().take(n) { + run.curve(a, b2, c, d, e, f); + } + if let (Some(a), Some(b2)) = (s.get(n * 6), s.get(n * 6 + 1)) { + run.line(*a, *b2); + } + } + 25 => { + // rlinecurve + let s = std::mem::take(&mut run.stack); + let lines = s.len().saturating_sub(6) / 2; + for &[x, y] in s.as_chunks::<2>().0.iter().take(lines) { + run.line(x, y); + } + if let Some(&[a, b2, c, d, e, f]) = s.get(lines * 2..lines * 2 + 6).and_then(|w| <&[f64; 6]>::try_from(w).ok()) { + run.curve(a, b2, c, d, e, f); + } + } + 26 | 27 => { + // vvcurveto, hhcurveto + let mut s = std::mem::take(&mut run.stack); + let mut first = if s.len() % 4 == 1 { Some(s.remove(0)) } else { None }; + for &[p, q, r, t] in s.as_chunks::<4>().0 { + let d1 = first.take().unwrap_or(0.0); + if b == 26 { run.curve(d1, p, q, r, 0.0, t) } else { run.curve(p, d1, q, r, t, 0.0) } + } + } + 30 | 31 => { + // vhcurveto, hvcurveto: alternating curves; the last may end off-axis. + let s = std::mem::take(&mut run.stack); + let mut horizontal = b == 31; + let mut k = 0; + while let Some(&[a, bb, c, d]) = s.get(k..k + 4).and_then(|w| <&[f64; 4]>::try_from(w).ok()) { + let extra = if s.len() - k == 5 { s.get(k + 4).copied().unwrap_or(0.0) } else { 0.0 }; + if horizontal { + run.curve(a, 0.0, bb, c, extra, d) + } else { + run.curve(0.0, a, bb, c, d, extra) + } + horizontal = !horizontal; + k += 4; + } + } + 10 | 29 => { + let n = run.stack.pop()? as i64; + let (list, bias) = if b == 10 { (local, bias(local.len())) } else { (&self.gsubrs[..], bias(self.gsubrs.len())) }; + let sub = *list.get(usize::try_from(n + bias).ok()?)?; + let sub = self.bytes(sub).to_vec(); + self.exec(&sub, local, run, depth + 1)?; + } + 11 => return Some(()), + 14 => { + run.take_width(false); + if run.open { + run.path.push(Seg::Close); + run.open = false; + } + run.done = true; + } + 12 => { + let e = *code.get(i)?; + i += 1; + let s = std::mem::take(&mut run.stack); + let a = |k: usize| s.get(k).copied().unwrap_or(0.0); + match e { + 35 => { + run.curve(a(0), a(1), a(2), a(3), a(4), a(5)); + run.curve(a(6), a(7), a(8), a(9), a(10), a(11)); + } + 34 => { + // hflex: dx1 dx2 dy2 dx3 dx4 dx5 dx6, back to the start height. + run.curve(a(0), 0.0, a(1), a(2), a(3), 0.0); + run.curve(a(4), 0.0, a(5), -a(2), a(6), 0.0); + } + 36 => { + // hflex1: dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6. + run.curve(a(0), a(1), a(2), a(3), a(4), 0.0); + run.curve(a(5), 0.0, a(6), a(7), a(8), -(a(1) + a(3) + a(7))); + } + 37 => { + // flex1: the last coordinate runs along the longer direction. + let dx = a(0) + a(2) + a(4) + a(6) + a(8); + let dy = a(1) + a(3) + a(5) + a(7) + a(9); + let (ex, ey) = if dx.abs() > dy.abs() { (a(10), -dy) } else { (-dx, a(10)) }; + run.curve(a(0), a(1), a(2), a(3), a(4), a(5)); + run.curve(a(6), a(7), a(8), a(9), ex, ey); + } + _ => {} + } + } + _ => {} + } + } + Some(()) + } + + /// Glyph `gid` of font `k` in glyph space (multiplied out by its FontMatrix later). + pub fn glyph(&self, k: usize, gid: u32) -> Option { + let font = self.fonts.get(k)?; + let cs = *font.charstrings.get(gid as usize)?; + let fd = usize::from(font.fd_select.get(gid as usize).copied().unwrap_or(0)); + let private = font.privates.get(fd).or_else(|| font.privates.first()).cloned().unwrap_or_default(); + let mut run = Run { path: Vec::new(), x: 0.0, y: 0.0, open: false, stack: Vec::new(), hints: 0, width: None, ops: 0, done: false }; + let code = self.bytes(cs).to_vec(); + self.exec(&code, &private.subrs, &mut run, 0)?; + if run.open { + run.path.push(Seg::Close); + } + let w = match run.width { + Some(w) if w.is_finite() => private.nominal_width + w, + _ => private.default_width, + }; + Some(Glyph { cost: run.ops + run.path.len(), path: run.path, width: (w, 0.0) }) + } + + /// The glyph index of a CID in font `k`. + pub fn gid_of_cid(&self, k: usize, cid: u32) -> Option { + let font = self.fonts.get(k)?; + let cids = font.cids.as_ref()?; + let map = font.by_cid.get_or_init(|| cids.iter().enumerate().filter_map(|(g, c)| Some((*c, u32::try_from(g).ok()?))).collect()); + map.get(&cid).copied() + } +} diff --git a/crates/ps/src/read/cff_strings.rs b/crates/ps/src/read/cff_strings.rs new file mode 100644 index 0000000000..38061243ba --- /dev/null +++ b/crates/ps/src/read/cff_strings.rs @@ -0,0 +1,252 @@ +//! CFF standard strings (Technical Note 5176, Appendix A): SIDs below 391 name these. + +/// SIDs 0–228: the Standard and ISO Latin glyph names. +const NAMES: [&str; 229] = [ + ".notdef", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "questiondown", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "AE", + "ordfeminine", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "ae", + "dotlessi", + "lslash", + "oslash", + "oe", + "germandbls", + "onesuperior", + "logicalnot", + "mu", + "trademark", + "Eth", + "onehalf", + "plusminus", + "Thorn", + "onequarter", + "divide", + "brokenbar", + "degree", + "thorn", + "threequarters", + "twosuperior", + "registered", + "minus", + "eth", + "multiply", + "threesuperior", + "copyright", + "Aacute", + "Acircumflex", + "Adieresis", + "Agrave", + "Aring", + "Atilde", + "Ccedilla", + "Eacute", + "Ecircumflex", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Ntilde", + "Oacute", + "Ocircumflex", + "Odieresis", + "Ograve", + "Otilde", + "Scaron", + "Uacute", + "Ucircumflex", + "Udieresis", + "Ugrave", + "Yacute", + "Ydieresis", + "Zcaron", + "aacute", + "acircumflex", + "adieresis", + "agrave", + "aring", + "atilde", + "ccedilla", + "eacute", + "ecircumflex", + "edieresis", + "egrave", + "iacute", + "icircumflex", + "idieresis", + "igrave", + "ntilde", + "oacute", + "ocircumflex", + "odieresis", + "ograve", + "otilde", + "scaron", + "uacute", + "ucircumflex", + "udieresis", + "ugrave", + "yacute", + "ydieresis", + "zcaron", +]; + +/// SIDs 379–390. +const TAIL: [&str; 12] = ["001.000", "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold"]; + +/// The number of standard strings. +pub const COUNT: usize = 391; + +/// The glyph name a standard SID stands for. The expert-set names (229–378) are given as +/// `sid`, which only has to be consistent within one font (they are its own glyph names). +pub fn standard(sid: usize) -> Option { + if let Some(n) = NAMES.get(sid) { + return Some((*n).to_string()); + } + if let Some(n) = sid.checked_sub(379).and_then(|i| TAIL.get(i)) { + return Some((*n).to_string()); + } + (sid < COUNT).then(|| format!("sid{sid}")) +} diff --git a/crates/ps/src/read/composite.rs b/crates/ps/src/read/composite.rs new file mode 100644 index 0000000000..dad0785d9c --- /dev/null +++ b/crates/ps/src/read/composite.rs @@ -0,0 +1,549 @@ +//! CFF font sets (`StartData`), CIDFonts, CMaps (`CIDInit`) and composite (Type 0) fonts. + +use std::rc::Rc; + +use crate::read::gstate::M; +use crate::read::interp::{Interp, R, err, matrix_obj}; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; +use crate::read::type1::Glyph; + +/// A CMap: code space ranges, code → CID ranges (single codes are ranges of one), a parent. +#[derive(Debug, Default)] +pub struct CMap { + codespace: Vec<(Vec, Vec)>, + ranges: Vec<(Vec, Vec, u32)>, + parent: Option, + identity: bool, + /// Vertical writing (WMode 1). + pub vertical: bool, +} + +const MAX_CMAPS: usize = 10_000; +const MAX_RANGES: usize = 500_000; + +fn code_value(b: &[u8]) -> u64 { + b.iter().fold(0u64, |a, x| a << 8 | u64::from(*x)) +} + +fn in_range(code: &[u8], lo: &[u8], hi: &[u8]) -> bool { + code.len() == lo.len() && code.len() == hi.len() && code.iter().zip(lo).zip(hi).all(|((c, l), h)| c >= l && c <= h) +} + +impl Interp { + fn cmap_of(&self, d: &PDict) -> Option { + match d.get_name(b"CraftPsCMap") { + Some(Obj::Int(i)) => usize::try_from(i).ok(), + _ => None, + } + } + + /// The CMap the current dictionary is building (made on first use). + fn building(&mut self) -> R { + let d = self.current_dict()?; + if let Some(i) = self.cmap_of(&d) { + return Ok(i); + } + if self.cmaps.len() >= MAX_CMAPS { + return err("limitcheck"); + } + self.cmaps.push(CMap::default()); + let i = self.cmaps.len() - 1; + d.put_name(b"CraftPsCMap", Obj::Int(i as i64)); + Ok(i) + } + + /// CID for a code through CMap `i` (and its parents); None when unmapped. + fn cid(&self, i: usize, code: &[u8], depth: usize) -> Option { + let m = self.cmaps.get(i)?; + if m.identity { + return u32::try_from(code_value(code)).ok(); + } + for (lo, hi, start) in &m.ranges { + if in_range(code, lo, hi) { + return u32::try_from(u64::from(*start) + code_value(code).saturating_sub(code_value(lo))).ok(); + } + } + if depth < 8 { m.parent.and_then(|p| self.cid(p, code, depth + 1)) } else { None } + } + + /// How many ranges a lookup through CMap `i` may compare. + fn cmap_cost(&self, i: usize) -> u64 { + let mut n = 0u64; + let mut cur = Some(i); + for _ in 0..8 { + let Some(m) = cur.and_then(|c| self.cmaps.get(c)) else { break }; + n = n.saturating_add((m.ranges.len() + m.codespace.len()) as u64); + cur = m.parent; + } + n + } + + fn code_len(&self, i: usize, s: &[u8], depth: usize) -> Option { + let m = self.cmaps.get(i)?; + for n in 1..=4 { + let Some(code) = s.get(..n) else { break }; + if m.codespace.iter().any(|(lo, hi)| in_range(code, lo, hi)) { + return Some(n); + } + } + if depth < 8 { m.parent.and_then(|p| self.code_len(p, s, depth + 1)) } else { None } + } +} + +// ----- CIDInit procedures ----- + +pub fn begincmap(_ip: &mut Interp) -> R { + Ok(()) +} + +pub fn endcmap(ip: &mut Interp) -> R { + let i = ip.building()?; + let vertical = ip.current_dict()?.get_name(b"WMode").and_then(|o| o.num()) == Some(1.0); + if let Some(m) = ip.cmaps.get_mut(i) { + m.vertical = vertical; + } + Ok(()) +} + +pub fn usecmap(ip: &mut Interp) -> R { + let n = ip.pop()?; + let parent = find_cmap(ip, &n)?; + let i = ip.building()?; + if let Some(m) = ip.cmaps.get_mut(i) { + m.parent = Some(parent); + } + Ok(()) +} + +/// `n begin…` pushes a mark for its entries. +pub fn begin_block(ip: &mut Interp) -> R { + ip.pop_int()?; + ip.push(Obj::Mark) +} + +fn block(ip: &mut Interp) -> R> { + let i = crate::read::ops::basic::mark_pos(ip)?; + let items = ip.o.split_off(i + 1); + ip.o.pop(); + Ok(items) +} + +fn bytes_of(o: &Obj) -> R> { + match o { + Obj::Str(s, _) => Ok(s.bytes()), + _ => err("typecheck"), + } +} + +pub fn endcodespacerange(ip: &mut Interp) -> R { + let items = block(ip)?; + let i = ip.building()?; + for p in items.chunks(2) { + if let [lo, hi] = p { + let (lo, hi) = (bytes_of(lo)?, bytes_of(hi)?); + if let Some(m) = ip.cmaps.get_mut(i) { + m.codespace.push((lo, hi)); + } + } + } + Ok(()) +} + +fn add_ranges(ip: &mut Interp, triples: bool) -> R { + let items = block(ip)?; + let i = ip.building()?; + let step = if triples { 3 } else { 2 }; + for e in items.chunks(step) { + let (lo, hi, cid) = match (triples, e) { + (true, [lo, hi, cid]) => (bytes_of(lo)?, bytes_of(hi)?, cid), + (false, [code, cid]) => (bytes_of(code)?, bytes_of(code)?, cid), + _ => continue, + }; + let Some(cid) = cid.num() else { continue }; + if let Some(m) = ip.cmaps.get_mut(i) + && m.ranges.len() < MAX_RANGES + { + m.ranges.push((lo, hi, cid.max(0.0) as u32)); + } + } + Ok(()) +} + +pub fn endcidrange(ip: &mut Interp) -> R { + add_ranges(ip, true) +} + +pub fn endcidchar(ip: &mut Interp) -> R { + add_ranges(ip, false) +} + +/// bf (Unicode) and notdef blocks: read and dropped. +pub fn end_ignored(ip: &mut Interp) -> R { + block(ip).map(|_| ()) +} + +fn identity(ip: &mut Interp, n: &[u8]) -> PDict { + let d = PDict::new(4); + d.put_name(b"CMapName", Obj::lit(n)); + let vertical = n.ends_with(b"-V"); + ip.cmaps.push(CMap { codespace: vec![(vec![0, 0], vec![0xff, 0xff])], identity: true, vertical, ..Default::default() }); + d.put_name(b"CraftPsCMap", Obj::Int(ip.cmaps.len() as i64 - 1)); + d.put_name(b"WMode", Obj::Int(i64::from(n.ends_with(b"-V")))); + d +} + +/// A CMap by name or dictionary: as an index into `ip.cmaps`. +fn find_cmap(ip: &mut Interp, o: &Obj) -> R { + let d = match o { + Obj::Dict(d) => d.clone(), + n => { + let cats = category(ip, b"CMap"); + match cats.get(&n.key()) { + Some(Obj::Dict(d)) => d, + _ => { + // Unknown CMaps read two-byte codes as CIDs, as Identity does. + let d = identity(ip, &crate::read::ops::basic::text_of(n)); + cats.put(n.clone(), Obj::Dict(d.clone())); + d + } + } + } + }; + match ip.cmap_of(&d) { + Some(i) => Ok(i), + None => { + let i = ip.cmaps.len(); + ip.cmaps.push(CMap { identity: true, codespace: vec![(vec![0, 0], vec![0xff, 0xff])], ..Default::default() }); + d.put_name(b"CraftPsCMap", Obj::Int(i as i64)); + Ok(i) + } + } +} + +fn category(ip: &mut Interp, cat: &[u8]) -> PDict { + match ip.resources.get_name(cat) { + Some(Obj::Dict(d)) => d, + _ => { + let d = PDict::new(20); + ip.resources.put_name(cat, Obj::Dict(d.clone())); + d + } + } +} + +fn add_fid(ip: &mut Interp, d: &PDict) { + if !d.known(&Key::Name(name(b"FID"))) { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } +} + +// ----- StartData ----- + +fn nums(v: &[f64]) -> Obj { + Obj::Array(PArr::new(v.iter().map(|x| Obj::Real(*x)).collect()), false) +} + +/// `/name length StartData`: the CFF font set in the next `length` bytes of the current file; +/// its fonts become Font (name-keyed) or CIDFont (CID-keyed) resources. +pub fn startdata(ip: &mut Interp) -> R { + let len = ip.pop_usize()?; + let _set_name = ip.pop()?; + if len > 256 << 20 { + return err("limitcheck"); + } + let file = + ip.e.iter() + .rev() + .find_map(|f| match f { + crate::read::interp::Frame::File { id } => Some(*id), + _ => None, + }) + .unwrap_or(ip.main); + ip.alloc(len)?; + let mut data = Vec::with_capacity(len); + while data.len() < len { + match ip.srcs.read(file) { + Some(c) => data.push(c), + None => break, + } + } + // StartData ends the FontSetInit dictionary its program began. + let fsi = match category(ip, b"ProcSet").get_name(b"FontSetInit") { + Some(Obj::Dict(d)) => Some(d), + _ => None, + }; + if let (Some(top), Some(fsi)) = (ip.d.last(), fsi) + && top.same(&fsi) + && ip.d.len() > 3 + { + ip.d.pop(); + } + // Parsing walks the data, and a font set's glyph tables are as large again. + ip.charge_bytes(data.len())?; + ip.alloc(data.len())?; + let Some(set) = crate::read::cff::parse(data) else { + ip.warnings.push("unreadable CFF font set".into()); + return Ok(()); + }; + let set = Rc::new(set); + let si = ip.cff.len(); + ip.cff.push(set.clone()); + for (k, f) in set.fonts.iter().enumerate() { + let d = PDict::new(16); + let reference = Obj::Array(PArr::new(vec![Obj::Int(si as i64), Obj::Int(k as i64)]), false); + d.put_name(b"CraftPsCff", reference); + d.put_name(b"FontMatrix", nums(&f.matrix)); + d.put_name(b"FontBBox", nums(&f.bbox)); + d.put_name(b"PaintType", Obj::Int(0)); + if let Some((reg, ord, sup)) = &f.ros { + d.put_name(b"CIDFontName", Obj::lit(&f.name)); + d.put_name(b"CIDFontType", Obj::Int(0)); + d.put_name(b"FontType", Obj::Int(9)); + let info = PDict::new(3); + info.put_name(b"Registry", Obj::str(reg)); + info.put_name(b"Ordering", Obj::str(ord)); + info.put_name(b"Supplement", Obj::Int(*sup)); + d.put_name(b"CIDSystemInfo", Obj::Dict(info)); + add_fid(ip, &d); + category(ip, b"CIDFont").put(Obj::lit(&f.name), Obj::Dict(d)); + } else { + d.put_name(b"FontName", Obj::lit(&f.name)); + d.put_name(b"FontType", Obj::Int(2)); + let mut enc = vec![Obj::lit(b".notdef"); 256]; + for (code, gid) in &f.encoding { + if let (Some(slot), Some(n)) = (enc.get_mut(usize::from(*code)), f.names.get(*gid as usize)) { + *slot = Obj::lit(n); + } + } + d.put_name(b"Encoding", Obj::Array(PArr::new(enc), false)); + let cs = PDict::new(f.names.len()); + for (g, n) in f.names.iter().enumerate() { + cs.put_name(n, Obj::Int(g as i64)); + } + d.put_name(b"CharStrings", Obj::Dict(cs)); + d.put_name(b"Private", Obj::Dict(PDict::new(1))); + add_fid(ip, &d); + ip.fontdir.put(Obj::lit(&f.name), Obj::Dict(d.clone())); + category(ip, b"Font").put(Obj::lit(&f.name), Obj::Dict(d)); + } + } + Ok(()) +} + +/// The CFF font set and font index behind a font dictionary. +pub fn cff_of(ip: &Interp, d: &PDict) -> Option<(Rc, usize)> { + let Some(Obj::Array(a, _)) = d.get_name(b"CraftPsCff") else { return None }; + let si = a.get(0)?.num()? as usize; + let k = a.get(1)?.num()? as usize; + Some((ip.cff.get(si)?.clone(), k)) +} + +// ----- composite fonts ----- + +/// `name cmap [cidfonts] composefont`: a Type 0 font. +pub fn composefont(ip: &mut Interp) -> R { + let fonts = ip.pop_arr()?; + let cmap = ip.pop()?; + let n = ip.pop()?; + let font = compose(ip, &n, &cmap, fonts.items())?; + ip.push(Obj::Dict(font)) +} + +fn compose(ip: &mut Interp, n: &Obj, cmap: &Obj, descendants: Vec) -> R { + let i = find_cmap(ip, cmap)?; + let mut desc = Vec::new(); + for f in descendants { + desc.push(match f { + Obj::Dict(d) => Obj::Dict(d), + k => match category(ip, b"CIDFont").get(&k.key()) { + Some(d @ Obj::Dict(_)) => d, + _ => Obj::Dict(crate::read::font::find_font(ip, &k)?), + }, + }); + } + let d = PDict::new(10); + d.put_name(b"FontName", n.clone()); + d.put_name(b"FontType", Obj::Int(0)); + d.put_name(b"FMapType", Obj::Int(9)); + d.put_name(b"FontMatrix", matrix_obj(&M::ID)); + d.put_name(b"Encoding", Obj::Array(PArr::new(vec![Obj::Int(0)]), false)); + d.put_name(b"FDepVector", Obj::Array(PArr::new(desc), false)); + let cm = PDict::new(2); + cm.put_name(b"CraftPsCMap", Obj::Int(i as i64)); + d.put_name(b"CMap", Obj::Dict(cm)); + let vertical = ip.cmaps.get(i).is_some_and(|m| m.vertical); + d.put_name(b"WMode", Obj::Int(i64::from(vertical))); + add_fid(ip, &d); + ip.fontdir.put(n.clone(), Obj::Dict(d.clone())); + Ok(d) +} + +/// `findfont` of `CIDFont-CMap` (as Adobe interpreters do): the two composed. +pub fn compose_by_name(ip: &mut Interp, n: &[u8]) -> Option { + let cats = category(ip, b"CIDFont"); + for (k, v) in cats.entries() { + let kn = crate::read::ops::basic::text_of(&k); + if n.len() > kn.len() + 1 && n.starts_with(&kn) && n.get(kn.len()) == Some(&b'-') { + let cmap = n.get(kn.len() + 1..)?; + return compose(ip, &Obj::lit(n), &Obj::lit(cmap), vec![v]).ok(); + } + } + None +} + +/// Whether a font writes vertically (its WMode, or its CMap's). +pub fn vertical(ip: &Interp, font: &PDict) -> bool { + match font.get_name(b"WMode").and_then(|o| o.num()) { + Some(w) => w == 1.0, + None => match font.get_name(b"CMap") { + Some(Obj::Dict(d)) => ip.cmap_of(&d).and_then(|i| ip.cmaps.get(i)).is_some_and(|m| m.vertical), + _ => false, + }, + } +} + +/// A CIDFont's vertical metrics for a CID in glyph space: the advance (w1) and the position +/// vector (v) from the horizontal origin to the vertical one. `Metrics2` gives them per CID; +/// otherwise the defaults: one em down, and v = (half the width, 0.88 em). +pub fn vertical_metrics(cidfont: &PDict, cid: u32, w0: f64, em: f64) -> ((f64, f64), (f64, f64)) { + if let Some(Obj::Dict(m)) = cidfont.get_name(b"Metrics2") + && let Some(Obj::Array(a, _)) = m.get(&Key::Int(i64::from(cid))) + { + let v: Vec = a.items().iter().filter_map(Obj::num).collect(); + if let [w1x, w1y, vx, vy] = v[..] { + return ((w1x, w1y), (vx, vy)); + } + } + ((0.0, -em), (w0 / 2.0, 0.88 * em)) +} + +/// What one glyph of a shown string draws with. +pub enum Key2 { + Code(u8), + Cid(u32), +} + +/// The glyphs of a string in a Type 0 font: (code, leaf font, glyph → text-space matrix, key). +pub fn decode(ip: &mut Interp, font: &PDict, s: &[u8]) -> R> { + let fm = font_matrix(font); + let desc: Vec = match font.get_name(b"FDepVector") { + Some(Obj::Array(a, _)) => a.items().into_iter().filter_map(|o| if let Obj::Dict(d) = o { Some(d) } else { None }).collect(), + _ => Vec::new(), + }; + let Some(first) = desc.first().cloned() else { return err("invalidfont") }; + let fmap = font.get_name(b"FMapType").and_then(|o| o.num()).unwrap_or(9.0) as i64; + let mut out = Vec::new(); + if fmap == 2 { + // 8/8 mapping: a font number, then a code in it. + for p in s.chunks(2) { + if let [f, c] = p { + let leaf = desc.get(usize::from(*f)).cloned().unwrap_or_else(|| first.clone()); + let m = font_matrix(&leaf).then(&fm); + out.push((u32::from(*c), leaf, m, Key2::Code(*c))); + } + } + return Ok(out); + } + let cmap = match font.get_name(b"CMap") { + Some(Obj::Dict(d)) => ip.cmap_of(&d), + _ => None, + }; + let m = font_matrix(&first).then(&fm); + let mut i = 0; + // Each code is looked up through the CMap's ranges (and its parents'). + let per_code = cmap.map_or(1, |c| ip.cmap_cost(c)) / 16 + 1; + while i < s.len() { + ip.charge(per_code)?; + let rest = s.get(i..).unwrap_or(&[]); + let n = cmap.and_then(|c| ip.code_len(c, rest, 0)).unwrap_or(2).min(rest.len()).max(1); + let code = rest.get(..n).unwrap_or(&[]); + let cid = cmap.and_then(|c| ip.cid(c, code, 0)).unwrap_or(0); + out.push((u32::try_from(code_value(code)).unwrap_or(0), first.clone(), m, Key2::Cid(cid))); + i += n; + } + Ok(out) +} + +fn font_matrix(d: &PDict) -> M { + match d.get_name(b"FontMatrix") { + Some(Obj::Array(a, _)) => crate::read::interp::matrix_of(&a).unwrap_or(M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0])), + _ => M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]), + } +} + +/// A CID's glyph in a CIDFont: CFF (CIDFontType 0) or TrueType (CIDFontType 2, through CIDMap). +pub fn cid_glyph(ip: &mut Interp, cidfont: &PDict, cid: u32) -> Option { + if let Some((set, k)) = cff_of(ip, cidfont) { + let gid = set.gid_of_cid(k, cid).unwrap_or(0); + return set.glyph(k, gid); + } + if cidfont.get_name(b"CIDFontType").and_then(|o| o.num()) == Some(2.0) { + let gid = match cidfont.get_name(b"CIDMap") { + Some(Obj::Int(off)) => u32::try_from(i64::from(cid) + off).ok()?, + Some(Obj::Dict(m)) => m.get(&Key::Int(i64::from(cid))).and_then(|o| o.num()).map_or(0, |v| v as u32), + Some(Obj::Str(s, _)) => gid_from(&[&s], cidfont, cid), + Some(Obj::Array(a, _)) => { + let strs: Vec = a.items().into_iter().filter_map(|o| if let Obj::Str(s, _) = o { Some(s) } else { None }).collect(); + gid_from(&strs.iter().collect::>(), cidfont, cid) + } + _ => cid, + }; + let data = crate::read::type42::sfnts(cidfont)?; + return crate::read::type42::glyph(&data, gid); + } + None +} + +/// A glyph index read from CIDMap strings (GDBytes bytes per CID, across the strings). +fn gid_from(strs: &[&PStr], cidfont: &PDict, cid: u32) -> u32 { + let gd = cidfont.get_name(b"GDBytes").and_then(|o| o.num()).unwrap_or(2.0).clamp(1.0, 4.0) as usize; + let mut at = (cid as usize).saturating_mul(gd); + for s in strs { + if at < s.len { + return (0..gd).fold(0u32, |a, k| a << 8 | u32::from(s.get(at + k).unwrap_or(0))); + } + at -= s.len; + } + 0 +} + +/// The ProcSets EPS files ask for, and the identity CMaps. +pub fn install(ip: &mut Interp) { + let procsets = category(ip, b"ProcSet"); + let fsi = PDict::new(2); + if let Some(op) = crate::read::ops::op_id(b"StartData") { + fsi.put_name(b"StartData", Obj::Op(op)); + } + procsets.put_name(b"FontSetInit", Obj::Dict(fsi)); + let cid = PDict::new(24); + for n in [ + "begincmap", + "endcmap", + "usecmap", + "begincodespacerange", + "endcodespacerange", + "begincidrange", + "endcidrange", + "begincidchar", + "endcidchar", + "beginbfchar", + "endbfchar", + "beginbfrange", + "endbfrange", + "beginnotdefrange", + "endnotdefrange", + "beginnotdefchar", + "endnotdefchar", + ] { + if let Some(op) = crate::read::ops::op_id(n.as_bytes()) { + cid.put_name(n.as_bytes(), Obj::Op(op)); + } + } + procsets.put_name(b"CIDInit", Obj::Dict(cid)); + let cmaps = category(ip, b"CMap"); + for n in [&b"Identity-H"[..], b"Identity-V"] { + let d = identity(ip, n); + cmaps.put_name(n, Obj::Dict(d)); + } +} diff --git a/crates/ps/src/read/encodings.rs b/crates/ps/src/read/encodings.rs new file mode 100644 index 0000000000..7ed3ff2530 --- /dev/null +++ b/crates/ps/src/read/encodings.rs @@ -0,0 +1,318 @@ +//! The two encodings every interpreter provides (PostScript Language Reference, Appendix E). + +/// Glyph names for codes 32–126, shared by both encodings except where noted. +const ASCII: [&str; 95] = [ + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", +]; + +const STANDARD_HIGH: &[(u8, &str)] = &[ + (161, "exclamdown"), + (162, "cent"), + (163, "sterling"), + (164, "fraction"), + (165, "yen"), + (166, "florin"), + (167, "section"), + (168, "currency"), + (169, "quotesingle"), + (170, "quotedblleft"), + (171, "guillemotleft"), + (172, "guilsinglleft"), + (173, "guilsinglright"), + (174, "fi"), + (175, "fl"), + (177, "endash"), + (178, "dagger"), + (179, "daggerdbl"), + (180, "periodcentered"), + (182, "paragraph"), + (183, "bullet"), + (184, "quotesinglbase"), + (185, "quotedblbase"), + (186, "quotedblright"), + (187, "guillemotright"), + (188, "ellipsis"), + (189, "perthousand"), + (191, "questiondown"), + (193, "grave"), + (194, "acute"), + (195, "circumflex"), + (196, "tilde"), + (197, "macron"), + (198, "breve"), + (199, "dotaccent"), + (200, "dieresis"), + (202, "ring"), + (203, "cedilla"), + (205, "hungarumlaut"), + (206, "ogonek"), + (207, "caron"), + (208, "emdash"), + (225, "AE"), + (227, "ordfeminine"), + (232, "Lslash"), + (233, "Oslash"), + (234, "OE"), + (235, "ordmasculine"), + (241, "ae"), + (245, "dotlessi"), + (248, "lslash"), + (249, "oslash"), + (250, "oe"), + (251, "germandbls"), +]; + +/// ISOLatin1Encoding: accents at 144–159, then ISO 8859-1 from 160. +const LATIN1_HIGH: [&str; 112] = [ + "dotlessi", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + ".notdef", + "ring", + "cedilla", + ".notdef", + "hungarumlaut", + "ogonek", + "caron", + "space", + "exclamdown", + "cent", + "sterling", + "currency", + "yen", + "brokenbar", + "section", + "dieresis", + "copyright", + "ordfeminine", + "guillemotleft", + "logicalnot", + "hyphen", + "registered", + "macron", + "degree", + "plusminus", + "twosuperior", + "threesuperior", + "acute", + "mu", + "paragraph", + "periodcentered", + "cedilla", + "onesuperior", + "ordmasculine", + "guillemotright", + "onequarter", + "onehalf", + "threequarters", + "questiondown", + "Agrave", + "Aacute", + "Acircumflex", + "Atilde", + "Adieresis", + "Aring", + "AE", + "Ccedilla", + "Egrave", + "Eacute", + "Ecircumflex", + "Edieresis", + "Igrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Eth", + "Ntilde", + "Ograve", + "Oacute", + "Ocircumflex", + "Otilde", + "Odieresis", + "multiply", + "Oslash", + "Ugrave", + "Uacute", + "Ucircumflex", + "Udieresis", + "Yacute", + "Thorn", + "germandbls", + "agrave", + "aacute", + "acircumflex", + "atilde", + "adieresis", + "aring", + "ae", + "ccedilla", + "egrave", + "eacute", + "ecircumflex", + "edieresis", + "igrave", + "iacute", + "icircumflex", + "idieresis", + "eth", + "ntilde", + "ograve", + "oacute", + "ocircumflex", + "otilde", + "odieresis", + "divide", + "oslash", + "ugrave", + "uacute", + "ucircumflex", + "udieresis", + "yacute", + "thorn", + "ydieresis", +]; + +pub fn standard() -> Vec<&'static str> { + let mut v = vec![".notdef"; 256]; + for (i, n) in ASCII.iter().enumerate() { + if let Some(slot) = v.get_mut(32 + i) { + *slot = n; + } + } + for (c, n) in STANDARD_HIGH { + if let Some(slot) = v.get_mut(usize::from(*c)) { + *slot = n; + } + } + v +} + +pub fn iso_latin1() -> Vec<&'static str> { + let mut v = vec![".notdef"; 256]; + for (i, n) in ASCII.iter().enumerate() { + if let Some(slot) = v.get_mut(32 + i) { + *slot = n; + } + } + // Latin-1 differs from Standard at the minus sign. + if let Some(slot) = v.get_mut(45) { + *slot = "minus"; + } + for (i, n) in LATIN1_HIGH.iter().enumerate() { + if let Some(slot) = v.get_mut(144 + i) { + *slot = n; + } + } + v +} + +#[cfg(test)] +mod tests { + #[test] + fn encodings_place_their_glyphs() { + let s = super::standard(); + assert_eq!((s[65], s[39], s[251], s[200]), ("A", "quoteright", "germandbls", "dieresis")); + let l = super::iso_latin1(); + assert_eq!((l[228], l[45], l[173], l[223], l[255]), ("adieresis", "minus", "hyphen", "germandbls", "ydieresis")); + } +} diff --git a/crates/ps/src/read/font.rs b/crates/ps/src/read/font.rs new file mode 100644 index 0000000000..9a1af3fb63 --- /dev/null +++ b/crates/ps/src/read/font.rs @@ -0,0 +1,751 @@ +//! Fonts: dictionaries, scaling, and showing text. Type 3 fonts draw through their BuildGlyph +//! or BuildChar procedures; other font types advance by their widths (or an estimate) without +//! drawing until their glyph programs are read. + +use crate::read::gstate::M; +use crate::read::interp::{Interp, PsErr, R, err, matrix_obj}; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; + +fn font_matrix(d: &PDict) -> M { + match d.get_name(b"FontMatrix") { + Some(Obj::Array(a, _)) => crate::read::interp::matrix_of(&a).unwrap_or(M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0])), + _ => M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]), + } +} + +/// A stand-in for a font the file doesn't carry: a Type 1 shell with StandardEncoding. +fn substitute(ip: &mut Interp, font_name: &[u8]) -> R { + if let Some(bytes) = ip.limits.fallback_font.and_then(|provider| provider(font_name)) + && let Some(d) = substitute_type42(ip, font_name, bytes)? + { + add_fid(ip, &d); + return Ok(d); + } + let d = PDict::new(12); + d.put_name(b"FontName", Obj::lit(font_name)); + d.put_name(b"FontType", Obj::Int(1)); + d.put_name(b"FontMatrix", matrix_obj(&M([0.001, 0.0, 0.0, 0.001, 0.0, 0.0]))); + d.put_name(b"FontBBox", Obj::Array(PArr::new(vec![Obj::Int(0), Obj::Int(-200), Obj::Int(1000), Obj::Int(900)]), false)); + d.put_name(b"PaintType", Obj::Int(0)); + if let Some(enc) = ip.systemdict.get_name(b"StandardEncoding") { + d.put_name(b"Encoding", enc); + } + d.put_name(b"CharStrings", Obj::Dict(PDict::new(1))); + d.put_name(b"Private", Obj::Dict(PDict::new(1))); + d.put_name(b"CraftPsSubstitute", Obj::Bool(true)); + add_fid(ip, &d); + Ok(d) +} + +fn substitute_type42(ip: &mut Interp, font_name: &[u8], bytes: &[u8]) -> R> { + use skrifa::MetadataProvider; + + let Ok(font) = skrifa::FontRef::new(bytes) else { return Ok(None) }; + let cmap = font.charmap(); + let charstrings = PDict::new(256); + for glyph_name in crate::read::encodings::standard() { + let Some(ch) = standard_glyph_char(glyph_name.as_bytes()) else { continue }; + let Some(gid) = cmap.map(ch) else { continue }; + charstrings.put(Obj::lit(glyph_name.as_bytes()), Obj::Int(i64::from(gid.to_u32()))); + } + ip.alloc(bytes.len().saturating_add(bytes.len() % 2))?; + let mut sfnt = bytes.to_vec(); + if sfnt.len() % 2 == 1 { + sfnt.push(0); + } + let d = PDict::new(12); + d.put_name(b"FontName", Obj::lit(font_name)); + d.put_name(b"FontType", Obj::Int(42)); + // Type 42 outlines are emitted in normalized em units by `type42::glyph`, unlike the + // 1000-unit CharStrings convention used by Type 1 fonts. + d.put_name(b"FontMatrix", matrix_obj(&M([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]))); + d.put_name(b"FontBBox", Obj::Array(PArr::new(vec![Obj::Int(0), Obj::Int(-200), Obj::Int(1000), Obj::Int(900)]), false)); + d.put_name(b"PaintType", Obj::Int(0)); + if let Some(enc) = ip.systemdict.get_name(b"StandardEncoding") { + d.put_name(b"Encoding", enc); + } + d.put_name(b"CharStrings", Obj::Dict(charstrings)); + d.put_name(b"sfnts", Obj::Array(PArr::new(vec![Obj::Str(PStr::new(sfnt), false)]), false)); + Ok(Some(d)) +} + +fn standard_glyph_char(name: &[u8]) -> Option { + if name.len() == 1 && name[0].is_ascii() { + return Some(char::from(name[0])); + } + Some(match name { + b"space" => ' ', + b"exclam" => '!', + b"quotedbl" => '"', + b"numbersign" => '#', + b"dollar" => '$', + b"percent" => '%', + b"ampersand" => '&', + b"quoteright" => '’', + b"parenleft" => '(', + b"parenright" => ')', + b"asterisk" => '*', + b"plus" => '+', + b"comma" => ',', + b"hyphen" => '-', + b"period" => '.', + b"slash" => '/', + b"colon" => ':', + b"semicolon" => ';', + b"less" => '<', + b"equal" => '=', + b"greater" => '>', + b"question" => '?', + b"at" => '@', + b"bracketleft" => '[', + b"backslash" => '\\', + b"bracketright" => ']', + b"asciicircum" => '^', + b"underscore" => '_', + b"quoteleft" => '‘', + b"braceleft" => '{', + b"bar" => '|', + b"braceright" => '}', + b"asciitilde" => '~', + b"zero" => '0', + b"one" => '1', + b"two" => '2', + b"three" => '3', + b"four" => '4', + b"five" => '5', + b"six" => '6', + b"seven" => '7', + b"eight" => '8', + b"nine" => '9', + b"exclamdown" => '¡', + b"cent" => '¢', + b"sterling" => '£', + b"fraction" => '⁄', + b"yen" => '¥', + b"florin" => 'ƒ', + b"section" => '§', + b"currency" => '¤', + b"quotesingle" => '\'', + b"quotedblleft" => '“', + b"guillemotleft" => '«', + b"guilsinglleft" => '‹', + b"guilsinglright" => '›', + b"fi" => '\u{fb01}', + b"fl" => '\u{fb02}', + b"endash" => '–', + b"dagger" => '†', + b"daggerdbl" => '‡', + b"periodcentered" => '·', + b"paragraph" => '¶', + b"bullet" => '•', + b"quotesinglbase" => '‚', + b"quotedblbase" => '„', + b"quotedblright" => '”', + b"guillemotright" => '»', + b"ellipsis" => '…', + b"perthousand" => '‰', + b"questiondown" => '¿', + b"grave" => '`', + b"acute" => '´', + b"circumflex" => 'ˆ', + b"tilde" => '˜', + b"macron" => '¯', + b"breve" => '˘', + b"dotaccent" => '˙', + b"dieresis" => '¨', + b"ring" => '˚', + b"cedilla" => '¸', + b"hungarumlaut" => '˝', + b"ogonek" => '˛', + b"caron" => 'ˇ', + b"emdash" => '—', + b"AE" => 'Æ', + b"ordfeminine" => 'ª', + b"Lslash" => 'Ł', + b"Oslash" => 'Ø', + b"OE" => 'Œ', + b"ordmasculine" => 'º', + b"ae" => 'æ', + b"dotlessi" => 'ı', + b"lslash" => 'ł', + b"oslash" => 'ø', + b"oe" => 'œ', + b"germandbls" => 'ß', + _ => return None, + }) +} + +pub(crate) fn add_fid(ip: &mut Interp, d: &PDict) { + if !d.known(&Key::Name(name(b"FID"))) { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } +} + +pub fn find_font(ip: &mut Interp, key: &Obj) -> R { + if let Some(Obj::Dict(d)) = ip.fontdir.get(&key.key()) { + return Ok(d); + } + if let Some(Obj::Dict(fonts)) = ip.resources.get_name(b"Font") + && let Some(Obj::Dict(d)) = fonts.get(&key.key()) + { + return Ok(d); + } + // An embedded Type 1 program can leave its FontName dictionary active after eexec without + // issuing definefont. Resolve that in-scope font before substituting a stand-in. + let active = + ip.d.iter() + .rev() + .find(|font| font.get_name(b"FontName").is_some_and(|n| n.key() == key.key()) && font.get_name(b"CharStrings").is_some()) + .cloned(); + if let Some(d) = active { + add_fid(ip, &d); + return Ok(d); + } + let n = crate::read::ops::basic::text_of(key); + if let Some(d) = crate::read::composite::compose_by_name(ip, &n) { + return Ok(d); + } + let d = substitute(ip, &n)?; + ip.fontdir.put(key.clone(), Obj::Dict(d.clone())); + Ok(d) +} + +pub fn findfont(ip: &mut Interp) -> R { + let k = ip.pop()?; + let d = find_font(ip, &k)?; + ip.push(Obj::Dict(d)) +} + +pub fn definefont(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + let k = ip.pop()?; + add_fid(ip, &d); + ip.fontdir.put(k, Obj::Dict(d.clone())); + ip.push(Obj::Dict(d)) +} + +pub fn undefinefont(ip: &mut Interp) -> R { + let k = ip.pop()?; + ip.fontdir.remove(&k.key()); + Ok(()) +} + +/// A copy of a font dictionary with its FontMatrix replaced (and a new FID). +fn transformed(ip: &mut Interp, d: &PDict, m: &M) -> PDict { + let copy = PDict::new(d.len() + 2); + for (k, v) in d.entries() { + copy.put(k, v); + } + copy.put_name(b"FontMatrix", matrix_obj(&font_matrix(d).then(m))); + copy.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + copy +} + +pub fn scalefont(ip: &mut Interp) -> R { + let s = ip.pop_num()?; + let d = ip.pop_dict()?; + let f = transformed(ip, &d, &M([s, 0.0, 0.0, s, 0.0, 0.0])); + ip.push(Obj::Dict(f)) +} + +pub fn makefont(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + let d = ip.pop_dict()?; + let f = transformed(ip, &d, &m); + ip.push(Obj::Dict(f)) +} + +pub fn setfont(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + ip.gs.font = Some(d); + Ok(()) +} + +pub fn currentfont(ip: &mut Interp) -> R { + let f = match ip.gs.font.clone() { + Some(f) => f, + None => find_font(ip, &Obj::lit(b"Courier"))?, + }; + ip.push(Obj::Dict(f)) +} + +pub fn selectfont(ip: &mut Interp) -> R { + let m = match ip.pop()? { + Obj::Array(a, _) => crate::read::interp::matrix_of(&a)?, + o => { + let s = o.num().ok_or(PsErr::Ps("typecheck"))?; + M([s, 0.0, 0.0, s, 0.0, 0.0]) + } + }; + let k = ip.pop()?; + let d = match k { + Obj::Dict(d) => d, + k => find_font(ip, &k)?, + }; + let f = transformed(ip, &d, &m); + ip.gs.font = Some(f); + Ok(()) +} + +/// The glyph name for a character code through the font's Encoding. +fn glyph_name(font: &PDict, code: u8) -> Vec { + match font.get_name(b"Encoding") { + Some(Obj::Array(a, _)) => match a.get(usize::from(code)) { + Some(Obj::Name(n, _)) => n.to_vec(), + _ => b".notdef".to_vec(), + }, + _ => b".notdef".to_vec(), + } +} + +/// Unicode text represented by the simple font's selected glyph names. Unknown names have no +/// honest replacement text, so callers must omit ActualText rather than infer from input bytes. +fn actual_text(font: &PDict, bytes: &[u8]) -> Option { + bytes.iter().map(|code| standard_glyph_char(&glyph_name(font, *code)).map(|c| c.to_string())).collect() +} + +/// A glyph's advance from the font's Metrics or CharStrings-free estimate, in glyph space. +fn estimated_width(font: &PDict, code: u8) -> (f64, f64) { + let g = glyph_name(font, code); + if let Some(Obj::Dict(m)) = font.get_name(b"Metrics") + && let Some(v) = m.get(&Key::Name(name(&g))) + { + match v { + Obj::Array(a, _) if a.len >= 2 => { + let n: Vec = a.items().iter().filter_map(Obj::num).collect(); + // The last two numbers are the width (an entry without two numbers gives none). + let w = n.len().checked_sub(2).and_then(|i| n.get(i)).copied().unwrap_or(0.0); + return (w, n.last().copied().unwrap_or(0.0)); + } + o => return (o.num().unwrap_or(0.0), 0.0), + } + } + // An average glyph: half the em, as glyph space usually has 1000 units to it. + let em = 1.0 / font_matrix(font).0[0].abs().max(1e-6); + (if code == b' ' { 0.25 } else { 0.5 } * em, 0.0) +} + +/// A Type 1 glyph of `font` (cached), None for fonts without charstrings. +fn outline(ip: &mut Interp, font: &PDict, code: u8) -> Option> { + if font.get_name(b"CraftPsSubstitute").is_some() { + return None; + } + let fid = match font.get_name(b"FID") { + Some(Obj::FontId(f)) => f, + _ => 0, + }; + let g = glyph_name(font, code); + if let Some(hit) = ip.glyphs.get(&(fid, g.clone())) { + return Some(hit.clone()); + } + let glyph = if let Some((set, k)) = crate::read::composite::cff_of(ip, font) { + let gid = match font.get_name(b"CharStrings") { + Some(Obj::Dict(cs)) => cs.get(&Key::Name(name(&g))).and_then(|o| o.num()).map_or(0, |v| v as u32), + _ => 0, + }; + std::rc::Rc::new(set.glyph(k, gid)?) + } else if font.get_name(b"FontType").and_then(|o| o.num()) == Some(42.0) { + let data = match ip.sfnts.get(&fid) { + Some(d) => d.clone(), + None => { + let d = std::rc::Rc::new(crate::read::type42::sfnts(font)?); + if ip.sfnts.len() < 256 { + ip.sfnts.insert(fid, d.clone()); + } + d + } + }; + std::rc::Rc::new(crate::read::type42::glyph(&data, crate::read::type42::glyph_index(font, &g))?) + } else { + let std = crate::read::encodings::standard(); + std::rc::Rc::new(crate::read::type1::glyph(font, &g, &std)?) + }; + // Running the glyph's program was work; failing to charge it ends the run at the next step. + let _ = ip.charge(glyph.cost as u64 / 4 + 1); + let _ = ip.alloc(glyph.path.len().saturating_mul(crate::read::interp::SEG_BYTES)); + if ip.glyphs.len() < 100_000 { + ip.glyphs.insert((fid, g), glyph.clone()); + } + Some(glyph) +} + +/// A CID's glyph in a CIDFont (cached by font and CID). +fn cid_outline(ip: &mut Interp, font: &PDict, cid: u32) -> Option> { + let fid = match font.get_name(b"FID") { + Some(Obj::FontId(f)) => f, + _ => 0, + }; + let key = (fid, format!("\0cid{cid}").into_bytes()); + if let Some(hit) = ip.glyphs.get(&key) { + return Some(hit.clone()); + } + let g = std::rc::Rc::new(crate::read::composite::cid_glyph(ip, font, cid)?); + let _ = ip.charge(g.cost as u64 / 4 + 1); + let _ = ip.alloc(g.path.len().saturating_mul(crate::read::interp::SEG_BYTES)); + if ip.glyphs.len() < 100_000 { + ip.glyphs.insert(key, g.clone()); + } + Some(g) +} + +/// Where a glyph at the current point lands: glyph space (through `fm`) → device space. `v` +/// moves the glyph's origin (vertical writing hangs a glyph from its vertical origin). +fn glyph_to_device(ip: &Interp, fm: &M, v: (f64, f64)) -> R { + let (x, y) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (ux, uy) = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?.apply(x, y); + Ok(M([1.0, 0.0, 0.0, 1.0, -v.0, -v.1]).then(fm).then(&M([1.0, 0.0, 0.0, 1.0, ux, uy])).then(&ip.gs.ctm)) +} + +/// Run one Type 3 glyph at the current point: its advance in glyph space. +fn type3_glyph(ip: &mut Interp, font: &PDict, code: u8) -> R<(f64, f64)> { + let (x, y) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let fm = font_matrix(font); + ip.gsave()?; + let r = (|| -> R<(f64, f64)> { + let (ux, uy) = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?.apply(x, y); + ip.gs.ctm = fm.then(&M([1.0, 0.0, 0.0, 1.0, ux, uy]).then(&ip.gs.ctm)); + ip.gs.path.clear(); + ip.gs.cur = None; + ip.gs.char_width = None; + if let Some(bg) = font.get_name(b"BuildGlyph") { + ip.push(Obj::Dict(font.clone()))?; + ip.push(Obj::lit(&glyph_name(font, code)))?; + ip.call(bg)?; + } else if let Some(bc) = font.get_name(b"BuildChar") { + ip.push(Obj::Dict(font.clone()))?; + ip.push(Obj::Int(i64::from(code)))?; + ip.call(bc)?; + } + Ok(ip.gs.char_width.unwrap_or((0.0, 0.0))) + })(); + ip.grestore(); + r +} + +/// What a glyph adds to (or, for `xshow`, replaces) its advance: given the code and its index. +type PerGlyph<'a> = dyn FnMut(&mut Interp, u32, usize) -> R<(f64, f64)> + 'a; + +/// Show (or, with `draw` false, measure) a string: the total advance in user space. +/// `per_char` gives each glyph's extra displacement (or, with `replace`, its whole advance). +fn show_glyphs(ip: &mut Interp, s: &[u8], draw: bool, replace: bool, per_char: &mut PerGlyph<'_>) -> R<(f64, f64)> { + let font = match ip.gs.font.clone() { + Some(f) => f, + None => return err("invalidfont"), + }; + let vertical = crate::read::composite::vertical(ip, &font); + // The list of glyphs is made first: at most one per byte. + ip.alloc(s.len().saturating_mul(GLYPH_JOB_BYTES))?; + let jobs: Vec<(u32, PDict, M, crate::read::composite::Key2)> = if font.get_name(b"FontType").and_then(|o| o.num()) == Some(0.0) { + crate::read::composite::decode(ip, &font, s)? + } else { + let fm = font_matrix(&font); + s.iter().map(|c| (u32::from(*c), font.clone(), fm, crate::read::composite::Key2::Code(*c))).collect() + }; + let mut total = (0.0, 0.0); + let mut text_paths: Vec<(Vec, crate::read::gstate::DevColor)> = Vec::new(); + let mut text_segments = 0usize; + let result = (|| -> R<(f64, f64)> { + for (i, (code, leaf, fm, key)) in jobs.into_iter().enumerate() { + let type3 = leaf.get_name(b"FontType").and_then(|o| o.num()) == Some(3.0); + let w = match key { + crate::read::composite::Key2::Code(c) if type3 => { + // Type 3 glyph procedures paint immediately. Commit any earlier staged + // outlines first so their paint order remains the same as the input string. + let pending = std::mem::take(&mut text_paths); + if !ip.gs.nulldev { + for (path, color) in pending { + ip.out.fill(&ip.gs.clip, &path, false, color).map_err(PsErr::Fatal)?; + } + } + ip.charge(GLYPH_STEPS)?; + if draw && ip.gs.cur.is_some() { + type3_glyph(ip, &leaf, c)? + } else { + let saved = ip.gs.nulldev; + ip.gs.nulldev = true; + if ip.gs.cur.is_none() { + ip.gs.cur = Some((0.0, 0.0)); + } + let w = type3_glyph(ip, &leaf, c); + ip.gs.nulldev = saved; + w? + } + } + key => { + let cid = match key { + crate::read::composite::Key2::Cid(cid) => Some(cid), + crate::read::composite::Key2::Code(_) => None, + }; + let g = match key { + crate::read::composite::Key2::Code(c) => outline(ip, &leaf, c), + crate::read::composite::Key2::Cid(cid) => cid_outline(ip, &leaf, cid), + }; + // Empty outlines (usually spaces) still advance but need little work; their + // outline cache/decoder has already charged what it actually did. + ip.charge(if g.as_ref().is_some_and(|g| g.path.is_empty()) { 1 } else { GLYPH_STEPS })?; + // Vertical writing: the glyph hangs from its vertical origin and advances down. + let em = 1.0 / font_matrix(&leaf).0[3].abs().max(1e-9); + let vmetrics = match (vertical, &g) { + (true, Some(g)) => Some(crate::read::composite::vertical_metrics(&leaf, cid.unwrap_or(0), g.width.0, em)), + (true, None) => Some(crate::read::composite::vertical_metrics(&leaf, cid.unwrap_or(0), em, em)), + _ => None, + }; + let origin = vmetrics.map_or((0.0, 0.0), |(_, v)| v); + match g { + Some(g) => { + if draw && !g.path.is_empty() && ip.gs.cur.is_some() { + ip.charge_path(g.path.len())?; + let m = glyph_to_device(ip, &fm, origin)?; + let path: Vec = g.path.iter().map(|s| s.map(&m)).collect(); + if ip.charpath { + if ip.gs.path.len().saturating_add(path.len()) > crate::read::gstate::MAX_PATH { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + ip.gs.path.extend(path); + } else { + if text_segments.saturating_add(path.len()) > crate::read::gstate::MAX_PATH { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + text_segments += path.len(); + if matches!(ip.gs.space, crate::read::gstate::Space::Pattern) { + // Pattern fills execute a cell program. Keep them on the normal + // path until their deferred representation is prepared. + crate::read::ops::gfx::fill_path(ip, &path, false)?; + } else { + let color = crate::read::ops::gfx::current_color(ip)?; + // Charge the fill work before staging it so completed glyphs + // can still be committed if a later glyph hits the budget. + ip.charge(path.len() as u64 / 4 + 1)?; + text_paths.push((path, color)); + } + } + } + match (vmetrics, leaf.get_name(b"Metrics"), key_code(code)) { + (Some((w1, _)), _, _) => w1, + (None, Some(_), Some(c)) => estimated_width(&leaf, c), + _ => g.width, + } + } + None => match vmetrics { + Some((w1, _)) => w1, + None => estimated_width(&leaf, key_code(code).unwrap_or(0)), + }, + } + } + }; + let (wx, wy) = fm.delta(w.0, w.1); + let (ex, ey) = per_char(ip, code, i)?; + let (dx, dy) = if replace { (ex, ey) } else { (wx + ex, wy + ey) }; + total = (total.0 + dx, total.1 + dy); + if draw && let Some((cx, cy)) = ip.gs.cur { + let (ddx, ddy) = ip.gs.ctm.delta(dx, dy); + ip.gs.cur = Some((cx + ddx, cy + ddy)); + } + } + Ok(total) + })(); + let path_limit = matches!(&result, Err(PsErr::Fatal(message)) if message == "PostScript (path limit)"); + if (result.is_ok() || !path_limit) && !ip.gs.nulldev { + for (path, color) in text_paths { + ip.out.fill(&ip.gs.clip, &path, false, color).map_err(PsErr::Fatal)?; + } + } + result +} + +/// What showing one glyph costs, in steps (it takes about ten times a plain operator), and the +/// memory its place in the list of glyphs takes. +const GLYPH_STEPS: u64 = 10; +const GLYPH_JOB_BYTES: usize = 96; + +fn key_code(code: u32) -> Option { + u8::try_from(code).ok() +} + +fn show_string(ip: &mut Interp, s: &[u8], draw: bool, per_char: &mut PerGlyph<'_>) -> R<(f64, f64)> { + // Whitespace-only shows advance the text position but emit no painted glyphs; avoid bloating + // the content stream with an empty semantic marked-content wrapper for them. + let text = ip.gs.font.as_ref().and_then(|font| actual_text(font, s)); + if draw + && !ip.charpath + && let Some(text) = text.filter(|text| text.chars().any(|c| !c.is_whitespace())) + { + ip.out.begin_actual_text(&text); + let result = show_glyphs(ip, s, draw, false, per_char); + ip.out.end_actual_text(); + result + } else { + show_glyphs(ip, s, draw, false, per_char) + } +} + +pub fn show(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + show_string(ip, &s, true, &mut |_, _, _| Ok((0.0, 0.0))).map(|_| ()) +} + +pub fn ashow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let ay = ip.pop_num()?; + let ax = ip.pop_num()?; + show_string(ip, &s, true, &mut |_, _, _| Ok((ax, ay))).map(|_| ()) +} + +pub fn widthshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let ch = ip.pop_int()?; + let cy = ip.pop_num()?; + let cx = ip.pop_num()?; + show_string(ip, &s, true, &mut |_, c, _| Ok(if i64::from(c) == ch { (cx, cy) } else { (0.0, 0.0) })).map(|_| ()) +} + +pub fn awidthshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let ay = ip.pop_num()?; + let ax = ip.pop_num()?; + let ch = ip.pop_int()?; + let cy = ip.pop_num()?; + let cx = ip.pop_num()?; + show_string(ip, &s, true, &mut |_, c, _| Ok(if i64::from(c) == ch { (cx + ax, cy + ay) } else { (ax, ay) })).map(|_| ()) +} + +/// `xshow`, `yshow`, `xyshow`: explicit displacements replace the widths. +fn explicit_show(ip: &mut Interp, xs: bool, ys: bool) -> R { + let disp: Vec = match ip.pop()? { + Obj::Array(a, _) => a.items().iter().filter_map(Obj::num).collect(), + // An encoded number string is rare in EPS: the glyphs' own widths then. + Obj::Str(_, _) => Vec::new(), + _ => return err("typecheck"), + }; + let s = ip.pop_str()?.bytes(); + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + let step = if xs && ys { 2 } else { 1 }; + show_glyphs(ip, &s, true, true, &mut |_, _, i| { + let d = |k: usize| disp.get(i * step + k).copied().unwrap_or(0.0); + Ok(match (xs, ys) { + (true, true) => (d(0), d(1)), + (true, false) => (d(0), 0.0), + _ => (0.0, d(0)), + }) + }) + .map(|_| ()) +} + +pub fn xshow(ip: &mut Interp) -> R { + explicit_show(ip, true, false) +} + +pub fn yshow(ip: &mut Interp) -> R { + explicit_show(ip, false, true) +} + +pub fn xyshow(ip: &mut Interp) -> R { + explicit_show(ip, true, true) +} + +pub fn kshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let proc = ip.pop()?; + for (i, c) in s.iter().enumerate() { + show_string(ip, &[*c], true, &mut |_, _, _| Ok((0.0, 0.0)))?; + if let Some(next) = s.get(i + 1) { + ip.push(Obj::Int(i64::from(*c)))?; + ip.push(Obj::Int(i64::from(*next)))?; + ip.call(proc.clone())?; + } + } + Ok(()) +} + +pub fn cshow(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let proc = ip.pop()?; + for c in s { + let (wx, wy) = show_string(ip, &[c], false, &mut |_, _, _| Ok((0.0, 0.0)))?; + ip.push(Obj::Int(i64::from(c)))?; + ip.push(Obj::Real(wx))?; + ip.push(Obj::Real(wy))?; + ip.call(proc.clone())?; + } + Ok(()) +} + +pub fn glyphshow(ip: &mut Interp) -> R { + let _ = ip.pop()?; + // Advance by an average glyph. + let font = ip.gs.font.clone().ok_or(PsErr::Ps("invalidfont"))?; + let (wx, wy) = font_matrix(&font).delta(500.0, 0.0); + if let Some((cx, cy)) = ip.gs.cur { + let (dx, dy) = ip.gs.ctm.delta(wx, wy); + ip.gs.cur = Some((cx + dx, cy + dy)); + } + Ok(()) +} + +pub fn stringwidth(ip: &mut Interp) -> R { + let s = ip.pop_str()?.bytes(); + let (wx, wy) = show_string(ip, &s, false, &mut |_, _, _| Ok((0.0, 0.0)))?; + ip.push(Obj::Real(wx))?; + ip.push(Obj::Real(wy)) +} + +pub fn charpath(ip: &mut Interp) -> R { + let _stroke = ip.pop_bool()?; + let s = ip.pop_str()?.bytes(); + let saved = ip.charpath; + ip.charpath = true; + let cur = ip.gs.cur; + let r = show_string(ip, &s, true, &mut |_, _, _| Ok((0.0, 0.0))); + ip.charpath = saved; + // The path ends at the advanced point. + if let (Some(p), Ok(_)) = (ip.gs.cur, &r) { + ip.gs.path.push(crate::read::gstate::Seg::Move(p.0, p.1)); + ip.gs.start = Some(p); + } + let _ = cur; + r.map(|_| ()) +} + +pub fn setcharwidth(ip: &mut Interp) -> R { + let wy = ip.pop_num()?; + let wx = ip.pop_num()?; + ip.gs.char_width = Some((wx, wy)); + Ok(()) +} + +pub fn setcachedevice(ip: &mut Interp) -> R { + for _ in 0..4 { + ip.pop_num()?; + } + setcharwidth(ip) +} + +/// `w0x w0y llx lly urx ury w1x w1y vx vy setcachedevice2`: the mode-0 width counts. +pub fn setcachedevice2(ip: &mut Interp) -> R { + for _ in 0..8 { + ip.pop_num()?; + } + setcharwidth(ip) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn standard_encoding_glyph_names_have_unicode_text() { + assert_eq!(standard_glyph_char(b"emdash"), Some('—')); + assert_eq!(standard_glyph_char(b"fi"), Some('\u{fb01}')); + assert_eq!(standard_glyph_char(b"sterling"), Some('£')); + assert_eq!(standard_glyph_char(b"quoteleft"), Some('‘')); + assert_eq!(standard_glyph_char(b"quoteright"), Some('’')); + assert_eq!(standard_glyph_char(b"unmapped.custom"), None); + } +} diff --git a/crates/ps/src/read/gstate.rs b/crates/ps/src/read/gstate.rs new file mode 100644 index 0000000000..2b62f91800 --- /dev/null +++ b/crates/ps/src/read/gstate.rs @@ -0,0 +1,399 @@ +//! The graphics state: transformation, current path (kept in device space, as PostScript +//! defines it), colour, line parameters and clipping. + +use std::rc::Rc; + +use crate::read::obj::{Obj, PDict}; + +/// An affine matrix `[a b c d e f]`: (x, y) → (a·x + c·y + e, b·x + d·y + f). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct M(pub [f64; 6]); + +impl M { + pub const ID: M = M([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + + /// `self` first, then `o` (PostScript's `concat` is `m · CTM`). + pub fn then(&self, o: &M) -> M { + let [a, b, c, d, e, f] = self.0; + let [p, q, r, s, t, u] = o.0; + M([a * p + b * r, a * q + b * s, c * p + d * r, c * q + d * s, e * p + f * r + t, e * q + f * s + u]) + } + + pub fn apply(&self, x: f64, y: f64) -> (f64, f64) { + let [a, b, c, d, e, f] = self.0; + (a * x + c * y + e, b * x + d * y + f) + } + + pub fn delta(&self, x: f64, y: f64) -> (f64, f64) { + let [a, b, c, d, ..] = self.0; + (a * x + c * y, b * x + d * y) + } + + pub fn inv(&self) -> Option { + let [a, b, c, d, e, f] = self.0; + let det = a * d - b * c; + if det == 0.0 || !det.is_finite() { + return None; + } + let m = M([d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det]); + m.0.iter().all(|v| v.is_finite()).then_some(m) + } + + pub fn finite(&self) -> bool { + self.0.iter().all(|v| v.is_finite()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Seg { + Move(f64, f64), + Line(f64, f64), + Curve(f64, f64, f64, f64, f64, f64), + Close, +} + +impl Seg { + pub fn map(&self, m: &M) -> Seg { + match *self { + Seg::Move(x, y) => { + let (x, y) = m.apply(x, y); + Seg::Move(x, y) + } + Seg::Line(x, y) => { + let (x, y) = m.apply(x, y); + Seg::Line(x, y) + } + Seg::Curve(a, b, c, d, e, f) => { + let (a, b) = m.apply(a, b); + let (c, d) = m.apply(c, d); + let (e, f) = m.apply(e, f); + Seg::Curve(a, b, c, d, e, f) + } + Seg::Close => Seg::Close, + } + } +} + +/// The most segments one path may hold. +pub const MAX_PATH: usize = 1 << 20; + +/// Maximum number of complete turns an `arc`/`arcn` adds to the path before preserving parity. +pub const MAX_ARC_TURNS: f64 = 1024.0; + +/// The sweep PostScript's `arc` or `arcn` operator selects without iterating over whole turns. +/// +/// The modulo form matters for hostile angles: repeatedly adding or subtracting 360 can take +/// effectively forever for a finite `f64` with a huge magnitude. +pub fn bounded_arc_sweep(a0: f64, a1: f64, negative: bool) -> (f64, bool) { + let sweep = if !negative && a1 < a0 { + (a1 % 360.0 - a0 % 360.0).rem_euclid(360.0) + } else if negative && a1 > a0 { + -(a0 % 360.0 - a1 % 360.0).rem_euclid(360.0) + } else { + a1 - a0 + }; + let max = MAX_ARC_TURNS * 360.0; + if !sweep.is_finite() { + return (0.0, true); + } + if sweep.abs() <= max { + return (sweep, false); + } + let sign = sweep.signum(); + let remainder = (sign * (a1 % 720.0 - a0 % 720.0)).rem_euclid(720.0); + (sign * (max - 720.0 + remainder), true) +} + +/// How many Bézier segments an arc needs, or `None` if it exceeds `max_segments`. +pub fn arc_curve_count(r: f64, a0: f64, a1: f64, max_segments: usize) -> Option { + let sweep = a1.to_radians() - a0.to_radians(); + if !sweep.is_finite() || sweep == 0.0 { + return Some(0); + } + // The established EPS reader uses a 0.1-unit curve tolerance. A quarter-circle cubic has + // about 0.00027253*r maximum radial error; subdivision error falls with the sixth power of + // the segment angle. Estimate before allocation so huge radii stop at the path bound. + let subdivisions = (r.abs() * 0.00027253 / 0.1).max(1.0).powf(1.0 / 6.0).ceil(); + let required = (sweep.abs() / std::f64::consts::FRAC_PI_2 * subdivisions).ceil().max(1.0); + (required.is_finite() && required <= max_segments as f64).then_some(required as usize) +} + +/// Bézier segments for an arc of the circle at (cx, cy) with radius r, from angle a0 to a1 +/// (degrees), in user space: the first point and the curves. +pub fn arc_curves(cx: f64, cy: f64, r: f64, a0: f64, a1: f64, max_segments: usize) -> ((f64, f64), Vec<[f64; 6]>, bool) { + let count = arc_curve_count(r, a0, a1, max_segments); + let (a0, a1) = (a0.to_radians(), a1.to_radians()); + let start = (cx + r * a0.cos(), cy + r * a0.sin()); + let Some(n) = count else { + return (start, Vec::new(), true); + }; + let sweep = a1 - a0; + if n == 0 || !sweep.is_finite() { + return (start, Vec::new(), false); + } + let step = sweep / n as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let mut out = Vec::with_capacity(n); + let mut a = a0; + for _ in 0..n { + let b = a + step; + let (ca, sa, cb, sb) = (a.cos(), a.sin(), b.cos(), b.sin()); + out.push([cx + r * (ca - k * sa), cy + r * (sa + k * ca), cx + r * (cb + k * sb), cy + r * (sb - k * cb), cx + r * cb, cy + r * sb]); + a = b; + } + (start, out, false) +} + +#[derive(Clone, Debug)] +pub enum Space { + Gray, + Rgb, + Cmyk, + /// Separation or DeviceN: the colourant names, the alternate space and its tint transform. + Tint { + names: Vec>, + alt: Box, + tint: Obj, + }, + Indexed { + base: Box, + hival: usize, + lookup: Vec, + }, + Lab, + Pattern, +} + +impl Space { + pub fn comps(&self) -> usize { + match self { + Space::Gray | Space::Indexed { .. } | Space::Pattern => 1, + Space::Rgb | Space::Lab => 3, + Space::Cmyk => 4, + Space::Tint { names, .. } => names.len().max(1), + } + } + + pub fn initial(&self) -> Vec { + match self { + Space::Cmyk => vec![0.0, 0.0, 0.0, 1.0], + Space::Tint { names, .. } => vec![1.0; names.len().max(1)], + Space::Lab => vec![0.0, 0.0, 0.0], + _ => vec![0.0; self.comps()], + } + } +} + +/// A device colour as written to the PDF. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DevColor { + Gray(f64), + Rgb(f64, f64, f64), + Cmyk(f64, f64, f64, f64), +} + +/// A clipping path, intersected with the ones before it. +#[derive(Debug)] +pub struct Clip { + pub path: Vec, + pub eo: bool, + pub parent: Option>, + pub depth: usize, +} + +pub fn clip_chain(c: &Option>) -> Vec> { + let mut out = Vec::new(); + let mut cur = c.clone(); + while let Some(n) = cur { + cur = n.parent.clone(); + out.push(n); + } + out.reverse(); + out +} + +#[derive(Clone, Debug)] +pub struct GState { + pub ctm: M, + pub path: Vec, + /// The current point, in device space. + pub cur: Option<(f64, f64)>, + /// Where the current subpath started (closepath returns there). + pub start: Option<(f64, f64)>, + pub space: Space, + pub color: Vec, + /// The pattern dictionary when the space is Pattern. + pub pattern: Option, + pub line_width: f64, + pub cap: i64, + pub join: i64, + pub miter: f64, + pub dash: (Vec, f64), + pub flat: f64, + pub font: Option, + pub clip: Option>, + pub overprint: bool, + pub stroke_adjust: bool, + /// Clips saved by `clipsave`. + pub clip_saves: Vec>>, + /// The colour space under an uncoloured pattern (`[/Pattern /DeviceRGB]`). + pub pattern_base: Option>, + /// Inside an uncoloured pattern's PaintProc: colour operators are ignored. + pub color_locked: bool, + /// Painting goes nowhere (`nulldevice`, measuring glyphs). + pub nulldev: bool, + /// Glyph widths reported by `setcharwidth`/`setcachedevice` while a glyph runs. + pub char_width: Option<(f64, f64)>, +} + +impl Default for GState { + fn default() -> Self { + GState { + ctm: M::ID, + path: Vec::new(), + cur: None, + start: None, + space: Space::Gray, + color: vec![0.0], + pattern: None, + line_width: 1.0, + cap: 0, + join: 0, + miter: 10.0, + dash: (Vec::new(), 0.0), + flat: 1.0, + font: None, + clip: None, + overprint: false, + stroke_adjust: false, + clip_saves: Vec::new(), + color_locked: false, + pattern_base: None, + nulldev: false, + char_width: None, + } + } +} + +/// The bounding box of a path's points (control points included), or None for an empty path. +pub fn bbox(path: &[Seg]) -> Option<[f64; 4]> { + let mut b: Option<[f64; 4]> = None; + let mut add = |x: f64, y: f64| { + let r = b.get_or_insert([x, y, x, y]); + r[0] = r[0].min(x); + r[1] = r[1].min(y); + r[2] = r[2].max(x); + r[3] = r[3].max(y); + }; + for s in path { + match *s { + Seg::Move(x, y) | Seg::Line(x, y) => add(x, y), + Seg::Curve(a, b2, c, d, e, f) => { + add(a, b2); + add(c, d); + add(e, f); + } + Seg::Close => {} + } + } + b +} + +/// The most dashes a stroke may break into; beyond, it is drawn solid (a tiny pattern on a +/// long path would otherwise make billions of pieces). +pub const MAX_DASHES: f64 = 100_000.0; + +/// Whether dash pattern `dash` on `path` (in the space the pattern is measured in) stays within +/// [`MAX_DASHES`]; its lengths must be finite and not all zero. +pub fn dashes_ok(path: &[Seg], dash: &[f64]) -> bool { + let period: f64 = dash.iter().sum(); + if dash.is_empty() || !period.is_finite() || period <= 0.0 || dash.iter().any(|d| !d.is_finite() || *d < 0.0) { + return false; + } + let mut len = 0.0; + let mut cur = (0.0, 0.0); + for s in path { + match *s { + Seg::Move(x, y) => cur = (x, y), + Seg::Line(x, y) => { + len += (x - cur.0).hypot(y - cur.1); + cur = (x, y); + } + Seg::Curve(a, b, c, d, e, f) => { + len += (a - cur.0).hypot(b - cur.1) + (c - a).hypot(d - b) + (e - c).hypot(f - d); + cur = (e, f); + } + Seg::Close => {} + } + } + len.is_finite() && len / period * dash.len() as f64 <= MAX_DASHES +} + +/// A path with its curves replaced by line segments (`flattenpath`). +pub fn flatten(path: &[Seg], tol: f64) -> Vec { + let mut out = Vec::with_capacity(path.len()); + let mut cur = (0.0, 0.0); + for s in path { + match *s { + Seg::Curve(x1, y1, x2, y2, x3, y3) => { + let d = ((x1 - cur.0).hypot(y1 - cur.1) + (x2 - x1).hypot(y2 - y1) + (x3 - x2).hypot(y3 - y2)).max(0.0); + let n = ((d / tol.max(0.05)).sqrt().ceil() as usize).clamp(1, 256); + for i in 1..=n { + let t = i as f64 / n as f64; + let mt = 1.0 - t; + let x = mt * mt * mt * cur.0 + 3.0 * mt * mt * t * x1 + 3.0 * mt * t * t * x2 + t * t * t * x3; + let y = mt * mt * mt * cur.1 + 3.0 * mt * mt * t * y1 + 3.0 * mt * t * t * y2 + t * t * t * y3; + out.push(Seg::Line(x, y)); + } + cur = (x3, y3); + } + Seg::Move(x, y) | Seg::Line(x, y) => { + cur = (x, y); + out.push(*s); + } + Seg::Close => out.push(*s), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matrices_compose_like_postscript() { + let t = M([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]); + let s = M([2.0, 0.0, 0.0, 3.0, 0.0, 0.0]); + // `10 20 translate 2 3 scale`: scale applies first, then translate. + let ctm = s.then(&t); + assert_eq!(ctm.apply(1.0, 1.0), (12.0, 23.0)); + let inv = ctm.inv().unwrap(); + let (x, y) = inv.apply(12.0, 23.0); + assert!((x - 1.0).abs() < 1e-12 && (y - 1.0).abs() < 1e-12); + assert!(M([0.0; 6]).inv().is_none()); + } + + #[test] + fn a_full_circle_is_four_quarter_curves() { + let (start, curves, truncated) = arc_curves(0.0, 0.0, 10.0, 0.0, 360.0, MAX_PATH); + assert!(!truncated); + assert!((start.0 - 10.0).abs() < 1e-9); + assert_eq!(curves.len(), 4); + let last = curves.last().unwrap(); + assert!((last[4] - 10.0).abs() < 1e-9 && last[5].abs() < 1e-9); + assert!(arc_curves(0.0, 0.0, 1.0, 0.0, f64::INFINITY, MAX_PATH).1.is_empty()); + assert_eq!(arc_curves(0.0, 0.0, 1.0, 0.0, MAX_ARC_TURNS * 360.0, MAX_PATH).1.len(), 4096); + assert!(arc_curves(0.0, 0.0, 2e17, 0.0, 360.0, 100).2); + } + + #[test] + fn huge_arc_angles_are_reduced_without_unbounded_turn_loops() { + assert_eq!(bounded_arc_sweep(1e18, 0.0, false), (80.0, false)); + assert_eq!(bounded_arc_sweep(0.0, 1e18, true), (-80.0, false)); + let (sweep, skipped) = bounded_arc_sweep(0.0, 5e18, false); + assert!(skipped); + assert!(sweep.abs() <= MAX_ARC_TURNS * 360.0); + assert_eq!(bounded_arc_sweep(0.0, f64::INFINITY, false), (0.0, true)); + } +} diff --git a/crates/ps/src/read/interp.rs b/crates/ps/src/read/interp.rs new file mode 100644 index 0000000000..1f4e7e1408 --- /dev/null +++ b/crates/ps/src/read/interp.rs @@ -0,0 +1,747 @@ +//! The interpreter: stacks, the execution loop and error handling. +//! +//! Execution never recurses on the Rust stack for PostScript control flow: procedures, loops +//! and `stopped` are frames on an explicit execution stack. Operators that must run a procedure +//! and use its result (tint transforms, BuildChar, `pathforall`) call [`Interp::call`], a +//! nested run of the loop with a bounded depth. + +use crate::read::gstate::GState; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; +use crate::read::ops::{self, OpId}; +use crate::read::pdf::Out; +use crate::read::scan; +use crate::read::source::{Source, Sources}; + +/// A PostScript error (`typecheck`, …), `stop`, `quit`, or a fatal problem that ends the run. +#[derive(Debug, Clone, PartialEq)] +pub enum PsErr { + Ps(&'static str), + Stop, + Quit, + Fatal(String), +} + +pub type R = Result; + +pub fn err(name: &'static str) -> R { + Err(PsErr::Ps(name)) +} + +#[derive(Debug, Clone)] +pub enum Frame { + Proc { + arr: PArr, + i: usize, + }, + File { + id: usize, + }, + For { + cur: f64, + inc: f64, + limit: f64, + int: bool, + proc: Obj, + }, + Repeat { + n: i64, + proc: Obj, + }, + Loop { + proc: Obj, + }, + ForallArr { + arr: PArr, + i: usize, + proc: Obj, + }, + ForallStr { + s: PStr, + i: usize, + proc: Obj, + }, + ForallDict { + items: Vec<(Obj, Obj)>, + i: usize, + proc: Obj, + }, + Stopped, + /// The bottom of a nested run ([`Interp::call`]). + Barrier, +} + +impl Frame { + pub fn is_loop(&self) -> bool { + matches!( + self, + Frame::For { .. } + | Frame::Repeat { .. } + | Frame::Loop { .. } + | Frame::ForallArr { .. } + | Frame::ForallStr { .. } + | Frame::ForallDict { .. } + ) + } +} + +/// How much work and memory one EPS may use. +pub type FallbackFont = fn(&[u8]) -> Option<&'static [u8]>; + +#[derive(Debug, Clone, Copy)] +pub struct Limits { + pub steps: u64, + pub memory: usize, + /// Let hosts that historically ignored excess operands preserve that behavior. + pub stack_overflow_noop: bool, + /// Consume image data but leave drawing to hosts that historically skipped EPS images. + pub skip_images: bool, + /// Return an empty page plus a warning when execution fails before painting anything. + pub keep_unpainted: bool, + /// Match hosts that historically coerce zero divisors to a zero integer result. + pub zero_division_zero: bool, + /// Optional host font provider for stand-in fonts absent from an EPS file. + pub fallback_font: Option, +} + +impl Default for Limits { + /// Generous for real EPS files: an Illustrator file with its procsets takes about 0.6 million + /// steps and 2 MB, one carrying a 15 MB CJK font 2 million steps and 30 MB. A program that + /// runs into the step limit ends within a few seconds. Smaller on the web. + fn default() -> Self { + if cfg!(target_arch = "wasm32") { + Limits { + steps: 20_000_000, + memory: 256 << 20, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + } + } else { + Limits { + steps: 50_000_000, + memory: 1 << 30, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + } + } + } +} + +/// Memory a path segment and a graphics state take. +pub const SEG_BYTES: usize = std::mem::size_of::(); +pub const GSTATE_BYTES: usize = 512; + +/// Content-stream bytes one written path segment takes, about. +pub const OUT_SEG_BYTES: usize = 24; + +/// Memory a file takes (charged when one is made). +pub const SOURCE_BYTES: usize = 128; + +/// Bytes read, copied or scanned per step of work charged. +pub const BYTES_PER_STEP: u64 = 16; + +// Keep the operand limit in line with the EPS reader's established 100,000-value ceiling. +const MAX_OSTACK: usize = 100_000; +const MAX_ESTACK: usize = 100_000; +const MAX_DSTACK: usize = 1_000; +const MAX_GSTACK: usize = 10_000; +const MAX_NAME_DEPTH: usize = 48; +const MAX_CALL_DEPTH: usize = 48; + +pub struct Interp { + pub o: Vec, + pub d: Vec, + pub e: Vec, + pub srcs: Sources, + pub gs: GState, + pub gstack: Vec, + /// Graphics-state depths that `save` objects restore to. + pub saves: Vec, + pub gstates: Vec, + pub systemdict: PDict, + pub globaldict: PDict, + pub userdict: PDict, + pub errordict: PDict, + pub dollar_error: PDict, + pub statusdict: PDict, + pub fontdir: PDict, + /// Resource categories: name → dictionary of instances. + pub resources: PDict, + pub out: Out, + pub limits: Limits, + pub steps: u64, + pub memory: usize, + /// How many of `srcs.read` have been charged as steps, and of the segments written. + pub read_charged: u64, + pub written_charged: u64, + pub depth: usize, + /// Executable names can resolve to each other without entering a procedure frame. + pub name_depth: usize, + pub next_fid: usize, + pub main: usize, + pub warnings: Vec, + /// Tiling pattern cells already written, by pattern and colour. + pub cells: std::collections::HashMap<(crate::read::obj::Key, Vec), usize>, + /// CMaps by index (CMap dictionaries refer to them). + pub cmaps: Vec, + /// CFF font sets read by StartData. + pub cff: Vec>, + /// Type 42 fonts' TrueType data by FID. + pub sfnts: std::collections::HashMap>>, + /// `charpath` is running: glyphs add to the path instead of painting. + pub charpath: bool, + /// Glyph outlines by font (FID) and glyph name. + pub glyphs: std::collections::HashMap<(usize, Vec), std::rc::Rc>, + /// The last names executed (for error reports). + pub recent: std::collections::VecDeque, +} + +impl Interp { + pub fn new(program: Vec, origin: (f64, f64), limits: Limits) -> Self { + let mut srcs = Sources { max_read: limits.steps.saturating_mul(BYTES_PER_STEP), ..Sources::default() }; + let main = srcs.add(Source::bytes(program)); + let systemdict = PDict::new(1000); + let globaldict = PDict::new(100); + let userdict = PDict::new(200); + let mut ip = Interp { + o: Vec::new(), + d: vec![systemdict.clone(), globaldict.clone(), userdict.clone()], + e: Vec::new(), + srcs, + gs: GState::default(), + gstack: Vec::new(), + saves: Vec::new(), + gstates: Vec::new(), + systemdict, + globaldict, + userdict, + errordict: PDict::new(40), + dollar_error: PDict::new(10), + statusdict: PDict::new(40), + fontdir: PDict::new(100), + resources: PDict::new(20), + out: Out::new(origin), + limits, + steps: 0, + memory: SOURCE_BYTES, + read_charged: 0, + written_charged: 0, + depth: 0, + name_depth: 0, + next_fid: 1, + main, + warnings: Vec::new(), + recent: std::collections::VecDeque::new(), + glyphs: std::collections::HashMap::new(), + charpath: false, + sfnts: std::collections::HashMap::new(), + cmaps: Vec::new(), + cells: std::collections::HashMap::new(), + cff: Vec::new(), + }; + ops::install(&mut ip); + ip + } + + // ----- operand stack ----- + + pub fn push(&mut self, o: Obj) -> R { + if self.o.len() >= MAX_OSTACK { + if self.limits.stack_overflow_noop { + return Ok(()); + } + return err("stackoverflow"); + } + self.o.push(o); + Ok(()) + } + + pub fn pop(&mut self) -> R { + self.o.pop().ok_or(PsErr::Ps("stackunderflow")) + } + + pub fn top(&self, n: usize) -> R<&Obj> { + let i = self.o.len().checked_sub(n + 1).ok_or(PsErr::Ps("stackunderflow"))?; + self.o.get(i).ok_or(PsErr::Ps("stackunderflow")) + } + + pub fn need(&self, n: usize) -> R { + if self.o.len() < n { err("stackunderflow") } else { Ok(()) } + } + + /// Whether an operator can append `n` values without exceeding the operand stack limit. + pub fn has_operand_room(&self, n: usize) -> bool { + self.o.len().checked_add(n).is_some_and(|len| len <= MAX_OSTACK) + } + + pub fn pop_num(&mut self) -> R { + match self.pop()? { + o @ (Obj::Int(_) | Obj::Real(_)) => o.num().ok_or(PsErr::Ps("typecheck")), + _ => err("typecheck"), + } + } + + pub fn pop_int(&mut self) -> R { + match self.pop()? { + Obj::Int(i) => Ok(i), + Obj::Real(r) if r.is_finite() => Ok(r as i64), + _ => err("typecheck"), + } + } + + pub fn pop_usize(&mut self) -> R { + usize::try_from(self.pop_int()?).map_err(|_| PsErr::Ps("rangecheck")) + } + + pub fn pop_bool(&mut self) -> R { + match self.pop()? { + Obj::Bool(b) => Ok(b), + _ => err("typecheck"), + } + } + + pub fn pop_dict(&mut self) -> R { + match self.pop()? { + Obj::Dict(d) => Ok(d), + _ => err("typecheck"), + } + } + + pub fn pop_arr(&mut self) -> R { + match self.pop()? { + Obj::Array(a, _) => Ok(a), + _ => err("typecheck"), + } + } + + pub fn pop_str(&mut self) -> R { + match self.pop()? { + Obj::Str(s, _) => Ok(s), + _ => err("typecheck"), + } + } + + /// A name, or a string read as one. + pub fn pop_name(&mut self) -> R> { + match self.pop()? { + Obj::Name(n, _) => Ok(n.to_vec()), + Obj::Str(s, _) => Ok(s.bytes()), + _ => err("typecheck"), + } + } + + pub fn pop_matrix(&mut self) -> R { + let a = self.pop_arr()?; + matrix_of(&a) + } + + /// Charge `units` steps of work (elements visited, or [`BYTES_PER_STEP`] bytes each): what an + /// operator does in proportion to its operands counts against the step limit, checked as it + /// goes rather than after. + pub fn charge(&mut self, units: u64) -> R { + self.steps = self.steps.saturating_add(units); + if self.steps > self.limits.steps { Err(PsErr::Fatal("the program runs too long".into())) } else { Ok(()) } + } + + /// Charge work for `n` bytes handled. + pub fn charge_bytes(&mut self, n: usize) -> R { + self.charge((n as u64) / BYTES_PER_STEP + 1) + } + + /// Charge memory for `n` bytes made (new objects and copies alike; the cap bounds what one + /// conversion makes in all, not only what it keeps). + pub fn alloc(&mut self, n: usize) -> R { + self.memory = self.memory.saturating_add(n); + if self.memory > self.limits.memory { Err(PsErr::Fatal("out of memory".into())) } else { Ok(()) } + } + + /// Register a retained file source against the memory bound. + pub fn add_source(&mut self, source: Source) -> R { + self.alloc(SOURCE_BYTES)?; + Ok(self.srcs.add(source)) + } + + /// Whether a file ID is still held by an operand or execution frame. + pub fn file_is_live(&self, id: usize) -> bool { + self.o.iter().any(|o| matches!(o, Obj::File(file) if *file == id)) + || self.e.iter().any(|frame| matches!(frame, Frame::File { id: file } if *file == id)) + } + + /// Consume a SubFileDecode stream whose file object is explicitly discarded with `pop`. + pub fn discard_subfile(&mut self, id: usize) -> R { + if !self.srcs.is_subfile_filter(id) { + return Ok(()); + } + let mut chunk = 0u64; + while self.srcs.read(id).is_some() { + chunk += 1; + if chunk == BYTES_PER_STEP { + self.read_charged = self.read_charged.saturating_add(chunk); + self.charge(1)?; + chunk = 0; + } + } + if self.srcs.exhausted { Err(PsErr::Fatal("the program reads too much data".into())) } else { Ok(()) } + } + + // ----- dictionaries ----- + + pub fn lookup(&self, k: &Key) -> Option { + self.d.iter().rev().find_map(|d| d.get(k)) + } + + pub fn begin(&mut self, d: PDict) -> R { + if self.d.len() >= MAX_DSTACK { + return err("dictstackoverflow"); + } + self.d.push(d); + Ok(()) + } + + pub fn current_dict(&self) -> R { + self.d.last().cloned().ok_or(PsErr::Ps("dictstackunderflow")) + } + + // ----- execution ----- + + pub fn push_frame(&mut self, f: Frame) -> R { + if self.e.len() >= MAX_ESTACK { + return err("execstackoverflow"); + } + self.e.push(f); + Ok(()) + } + + /// Execute an object as `exec` does: procedures run, names are looked up, strings and files + /// are scanned as programs, anything else is pushed. + pub fn exec_value(&mut self, o: Obj) -> R { + match o { + Obj::Array(a, true) => { + if a.len > 0 { + self.push_frame(Frame::Proc { arr: a, i: 0 })?; + } + Ok(()) + } + Obj::Name(n, true) => { + if self.name_depth >= MAX_NAME_DEPTH { + return Err(PsErr::Fatal("executable name resolution limit".into())); + } + self.name_depth += 1; + if self.recent.len() >= 24 { + self.recent.pop_front(); + } + self.recent.push_back(n.clone()); + let result = match self.lookup(&Key::Name(n.clone())) { + Some(v) => self.exec_found(v), + None => { + self.dollar_error.put_name(b"offending", Obj::Name(n, false)); + Err(PsErr::Ps("undefined")) + } + }; + self.name_depth -= 1; + result + } + Obj::Op(op) => self.call_op(op), + Obj::Str(s, true) => { + // A string runs as a file reading it in place. + let id = self.add_source(Source::string(&s))?; + self.push_frame(Frame::File { id }) + } + Obj::File(id) => self.push_frame(Frame::File { id }), + other => self.push(other), + } + } + + /// The value of an executable name: executed (procedures run). + fn exec_found(&mut self, v: Obj) -> R { + match v { + Obj::Array(a, true) => { + if a.len > 0 { + self.push_frame(Frame::Proc { arr: a, i: 0 })?; + } + Ok(()) + } + Obj::Op(op) => self.call_op(op), + // A name bound to another executable name: `exec_value` bounds this resolution chain. + // Files are literal unless `exec` runs them (`cvx exec`). + o @ (Obj::Name(_, true) | Obj::Str(_, true)) => self.exec_value(o), + other => self.push(other), + } + } + + pub fn call_op(&mut self, op: OpId) -> R { + let (opname, f) = ops::OPS.get(op as usize).copied().ok_or(PsErr::Ps("undefined"))?; + match f(self) { + Err(PsErr::Ps(e)) => { + self.dollar_error.put_name(b"command", Obj::lit(opname)); + Err(PsErr::Ps(e)) + } + r => r, + } + } + + /// Execute one object met in a procedure body or a program: executable names and operators + /// run, everything else (procedures included) is pushed. + fn exec_direct(&mut self, o: Obj) -> R { + match o { + Obj::Name(_, true) | Obj::Op(_) => self.exec_value(o), + other => self.push(other), + } + } + + fn step(&mut self) -> R { + // Bytes read since the last step are work too (decoding included). + let read = self.srcs.read; + let fresh = read.saturating_sub(self.read_charged); + self.read_charged = read; + self.charge(1 + fresh / BYTES_PER_STEP)?; + // So is what was written: re-emitted clips included. + let written = self.out.segments() as u64; + let fresh = written.saturating_sub(self.written_charged); + if fresh > 0 { + self.written_charged = written; + self.charge(fresh / 4)?; + self.alloc(usize::try_from(fresh).unwrap_or(usize::MAX).saturating_mul(OUT_SEG_BYTES))?; + } + if self.srcs.exhausted { + return Err(PsErr::Fatal("the program reads too much data".into())); + } + let Some(frame) = self.e.last_mut() else { return Ok(()) }; + match frame { + Frame::Proc { arr, i } => { + let Some(o) = arr.get(*i) else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + if *i >= arr.len { + // The last element: drop the frame first, so tail recursion doesn't grow it. + self.e.pop(); + } + self.exec_direct(o) + } + Frame::File { id } => { + let id = *id; + let d = &self.d; + let mut resolve = |n: &[u8]| d.iter().rev().find_map(|dict| dict.get(&Key::Name(name(n)))); + let before = self.srcs.read; + let token = scan::next(&mut self.srcs, id, &mut resolve); + // What the scanner read became objects: memory. + let scanned = usize::try_from(self.srcs.read.saturating_sub(before)).unwrap_or(usize::MAX); + self.alloc(scanned)?; + match token { + Ok(Some(o)) => self.exec_direct(o), + Ok(None) => { + self.e.pop(); + Ok(()) + } + Err(msg) => { + self.e.pop(); + self.warnings.push(msg); + err("syntaxerror") + } + } + } + Frame::For { cur, inc, limit, int, proc } => { + let done = if *inc > 0.0 { *cur > *limit } else { *cur < *limit }; + if done || !cur.is_finite() { + self.e.pop(); + return Ok(()); + } + let v = if *int { Obj::Int(*cur as i64) } else { Obj::Real(*cur) }; + *cur += *inc; + let p = proc.clone(); + self.push(v)?; + self.exec_value(p) + } + Frame::Repeat { n, proc } => { + if *n <= 0 { + self.e.pop(); + return Ok(()); + } + *n -= 1; + let p = proc.clone(); + self.exec_value(p) + } + Frame::Loop { proc } => { + let p = proc.clone(); + self.exec_value(p) + } + Frame::ForallArr { arr, i, proc } => { + let Some(v) = arr.get(*i) else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + let p = proc.clone(); + self.push(v)?; + self.exec_value(p) + } + Frame::ForallStr { s, i, proc } => { + let Some(v) = s.get(*i) else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + let p = proc.clone(); + self.push(Obj::Int(i64::from(v)))?; + self.exec_value(p) + } + Frame::ForallDict { items, i, proc } => { + let Some((k, v)) = items.get(*i).cloned() else { + self.e.pop(); + return Ok(()); + }; + *i += 1; + let p = proc.clone(); + self.push(k)?; + self.push(v)?; + self.exec_value(p) + } + Frame::Stopped => { + self.e.pop(); + self.push(Obj::Bool(false)) + } + Frame::Barrier => Ok(()), + } + } + + /// Run until the execution stack is back to `floor` frames. + pub fn run_to(&mut self, floor: usize) -> R { + while self.e.len() > floor { + if matches!(self.e.last(), Some(Frame::Barrier)) && self.e.len() == floor + 1 { + break; + } + match self.step() { + Ok(()) => {} + Err(PsErr::Fatal(m)) => return Err(PsErr::Fatal(m)), + Err(PsErr::Quit) => return Err(PsErr::Quit), + Err(e) => { + if let PsErr::Ps(name) = &e { + self.dollar_error.put_name(b"errorname", Obj::lit(name.as_bytes())); + self.dollar_error.put_name(b"newerror", Obj::Bool(true)); + } + // Unwind to the nearest `stopped` above the floor; none: the error is ours to return. + match self.e.iter().rposition(|f| matches!(f, Frame::Stopped | Frame::Barrier)) { + Some(i) if i >= floor && matches!(self.e.get(i), Some(Frame::Stopped)) => { + self.e.truncate(i); + self.push(Obj::Bool(true))?; + } + _ => { + self.e.truncate(floor); + return Err(e); + } + } + } + } + } + Ok(()) + } + + /// Run `proc` to completion (a nested run), for operators that need its results. + pub fn call(&mut self, proc: Obj) -> R { + if self.depth >= MAX_CALL_DEPTH { + return err("limitcheck"); + } + self.depth += 1; + let floor = self.e.len(); + let r = self.push_frame(Frame::Barrier).and_then(|()| self.exec_value(proc)).and_then(|()| self.run_to(floor + 1)); + // Drop the barrier (and anything an error left above the floor). + self.e.truncate(floor); + self.depth -= 1; + r + } + + /// Run the program. + pub fn run(&mut self) -> Result<(), String> { + self.e.push(Frame::File { id: self.main }); + match self.run_to(0) { + Ok(()) | Err(PsErr::Quit) => Ok(()), + Err(PsErr::Stop) => Ok(()), + Err(PsErr::Ps(e)) => { + let cmd = self.dollar_error.get_name(b"command").map(|c| match c { + Obj::Name(n, _) => String::from_utf8_lossy(&n).into_owned(), + _ => String::new(), + }); + let offending = match self.dollar_error.get_name(b"offending") { + Some(Obj::Name(n, _)) => format!(" ({})", String::from_utf8_lossy(&n)), + _ => String::new(), + }; + let recent: Vec = self.recent.iter().map(|n| String::from_utf8_lossy(n).into_owned()).collect(); + let stack: Vec = self + .o + .iter() + .rev() + .take(6) + .map(|o| { + String::from_utf8_lossy(&crate::read::ops::basic::text_of(o)).chars().take(24).collect::() + + ":" + + &String::from_utf8_lossy(o.type_name()) + }) + .collect(); + Err(format!( + "PostScript error {e} in {}{offending}; after {}; stack {}", + cmd.unwrap_or_default(), + recent.join(" "), + stack.join(" | ") + )) + } + Err(PsErr::Fatal(m)) => Err(m), + } + } + + // ----- graphics-state stack ----- + + pub fn gsave(&mut self) -> R { + if self.gstack.len() >= MAX_GSTACK { + return err("limitcheck"); + } + self.charge_gstate()?; + self.gstack.push(self.gs.clone()); + Ok(()) + } + + /// Copying the graphics state copies its path: work and memory in proportion. + pub fn charge_gstate(&mut self) -> R { + let n = self.gs.path.len() + self.gs.dash.0.len() + self.gs.clip_saves.len() + self.gs.color.len(); + self.charge(n as u64 / 4 + 1)?; + self.alloc(n.saturating_mul(SEG_BYTES).saturating_add(GSTATE_BYTES)) + } + + /// Charge work and memory for copying or walking `n` path segments. + pub fn charge_path(&mut self, n: usize) -> R { + self.charge(n as u64 / 4 + 1)?; + self.alloc(n.saturating_mul(SEG_BYTES)) + } + + pub fn grestore(&mut self) { + // Not below the innermost save. + let floor = self.saves.last().copied().unwrap_or(0); + if self.gstack.len() > floor + && let Some(g) = self.gstack.pop() + { + self.gs = g; + } + } +} + +/// A six-number array as a matrix. +pub fn matrix_of(a: &PArr) -> R { + if a.len != 6 { + return err("rangecheck"); + } + let mut m = [0.0; 6]; + for (i, slot) in m.iter_mut().enumerate() { + *slot = a.get(i).and_then(|o| o.num()).ok_or(PsErr::Ps("typecheck"))?; + } + Ok(crate::read::gstate::M(m)) +} + +pub fn matrix_obj(m: &crate::read::gstate::M) -> Obj { + Obj::Array(PArr::new(m.0.iter().map(|v| Obj::Real(*v)).collect()), false) +} diff --git a/crates/ps/src/read/mod.rs b/crates/ps/src/read/mod.rs new file mode 100644 index 0000000000..0fcc3b3634 --- /dev/null +++ b/crates/ps/src/read/mod.rs @@ -0,0 +1,118 @@ +//! Reading EPS: a PostScript interpreter that runs the program and writes what it paints as a +//! one-page PDF the size of its bounding box, in vector form with its colours kept (CMYK stays +//! CMYK), so an app can show and print it as a placed PDF. +//! +//! Written from the PostScript Language Reference (third edition), the EPS specification, the +//! Type 1 Font Format and Adobe Technical Notes 5012 (Type 42), 5176 (CFF) and 5177 (Type 2 +//! charstrings). +//! Covered: the language (Level 3 operators EPS files use), paths, painting, clipping, device and +//! Separation/DeviceN/Indexed colour, sampled images with the standard filters, smooth shadings +//! (axial, radial, function-based, triangle and patch meshes), shading and tiling patterns, and +//! text in Type 1, Type 3, Type 42 and CFF fonts (`StartData`), CIDFonts and composite fonts +//! through CMaps, written horizontally or vertically. + +mod cff; +mod cff_strings; +mod composite; +mod encodings; +mod font; +mod gstate; +mod interp; +mod obj; +mod ops; +mod pdf; +mod scan; +mod source; +mod type1; +mod type42; + +use craft_eps::{Comments, Kind, MAX_EXTENDED_HEADER, postscript_section as shared_postscript_section}; + +pub use interp::{FallbackFont, Limits}; + +/// A converted EPS. +#[derive(Debug)] +pub struct Converted { + /// A one-page PDF of the bounding box. + pub pdf: Vec, + /// The bounding box in points (x0, y0, x1, y1). + pub bbox: [f64; 4], + /// Things the program did that weren't drawn (unsupported features). + pub warnings: Vec, + /// The work and memory the conversion used, as [`Limits`] counts them. + pub steps: u64, + pub memory: usize, +} + +/// The PostScript part of an EPS (inside a DOS EPS binary header, when there is one). +pub fn postscript_section(bytes: &[u8]) -> &[u8] { + shared_postscript_section(bytes).unwrap_or(&[]) +} + +/// The bounding box from the DSC comments: the high-resolution one when it is valid. +pub fn bounding_box(ps: &[u8]) -> Option<[f64; 4]> { + Comments::read_with_header_limit(ps, MAX_EXTENDED_HEADER).page_box() +} + +/// An EPS file (plain, or DOS EPS with a binary header)? +pub fn is_eps(bytes: &[u8]) -> bool { + craft_eps::sniff(bytes).is_some_and(|file| file.kind == Kind::Eps) +} + +/// How many converted EPS files are kept. +const CACHE_ENTRIES: usize = 64; + +type Cache = std::collections::HashMap<(u64, usize), Option>>>; + +fn cache() -> &'static std::sync::Mutex { + static CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); + CACHE.get_or_init(|| std::sync::Mutex::new(Cache::new())) +} + +/// [`eps_to_pdf`] with the default limits, remembered by content: the screen, thumbnails and +/// every export convert an EPS once. None when it can't be converted (callers show its preview). +pub fn cached_pdf(eps: &[u8]) -> Option>> { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + eps.hash(&mut h); + let key = (h.finish(), eps.len()); + if let Some(hit) = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) { + return hit.clone(); + } + // Convert outside the lock: other EPS files keep drawing meanwhile. + let pdf = eps_to_pdf(eps, Limits::default()).ok().map(|c| std::sync::Arc::new(c.pdf)); + let mut c = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if c.len() >= CACHE_ENTRIES { + c.clear(); + } + c.insert(key, pdf.clone()); + pdf +} + +/// Run an EPS and write what it paints as PDF. `Err` when it isn't an EPS with a bounding box, +/// or when it fails before painting and `limits.keep_unpainted` is false. +pub fn eps_to_pdf(bytes: &[u8], limits: Limits) -> Result { + let ps = postscript_section(bytes); + if !ps.starts_with(b"%!") { + return Err("not PostScript".into()); + } + let bbox = bounding_box(ps).ok_or("the EPS has no bounding box")?; + let mut ip = interp::Interp::new(ps.to_vec(), (bbox[0], bbox[1]), limits); + let result = ip.run(); + let mut warnings = std::mem::take(&mut ip.warnings); + warnings.dedup(); + if let Err(e) = result { + // What was painted before an error is kept (the rest of the page is lost, as on a + // printer); with nothing painted, the caller falls back to the preview. + if !ip.out.painted && !limits.keep_unpainted { + return Err(e); + } + warnings.push(e); + } + let size = (bbox[2] - bbox[0], bbox[3] - bbox[1]); + let (steps, memory) = (ip.steps, ip.memory); + Ok(Converted { pdf: ip.out.finish(size), bbox, warnings, steps, memory }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ps/src/read/obj.rs b/crates/ps/src/read/obj.rs new file mode 100644 index 0000000000..411450123a --- /dev/null +++ b/crates/ps/src/read/obj.rs @@ -0,0 +1,301 @@ +//! PostScript objects. Composite objects (strings, arrays, dictionaries) share their storage the +//! way the language requires: `dup` copies the reference, `getinterval` a window onto the same +//! values. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use crate::read::ops::OpId; + +/// A name: its bytes, shared. +pub type Name = Rc<[u8]>; + +pub fn name(s: &[u8]) -> Name { + Rc::from(s) +} + +#[derive(Clone, Debug)] +pub struct PStr { + pub buf: Rc>>, + pub off: usize, + pub len: usize, +} + +impl PStr { + pub fn new(bytes: Vec) -> Self { + let len = bytes.len(); + PStr { buf: Rc::new(RefCell::new(bytes)), off: 0, len } + } + + /// The bytes in view (empty when the window no longer fits its storage). + pub fn bytes(&self) -> Vec { + let b = self.buf.borrow(); + self.off.checked_add(self.len).and_then(|end| b.get(self.off..end)).map(<[u8]>::to_vec).unwrap_or_default() + } + + pub fn get(&self, i: usize) -> Option { + if i >= self.len { + return None; + } + self.buf.borrow().get(self.off.checked_add(i)?).copied() + } + + pub fn set(&self, i: usize, v: u8) -> bool { + if i >= self.len { + return false; + } + let Some(at) = self.off.checked_add(i) else { return false }; + match self.buf.borrow_mut().get_mut(at) { + Some(slot) => { + *slot = v; + true + } + None => false, + } + } + + pub fn interval(&self, start: usize, count: usize) -> Option { + (start.checked_add(count)? <= self.len).then(|| PStr { buf: self.buf.clone(), off: self.off + start, len: count }) + } + + /// Copy `src` into the start of this string: the written window, or None when it doesn't fit. + pub fn put_bytes(&self, at: usize, src: &[u8]) -> Option { + if at.checked_add(src.len())? > self.len { + return None; + } + let mut b = self.buf.borrow_mut(); + let start = self.off.checked_add(at)?; + b.get_mut(start..start.checked_add(src.len())?)?.copy_from_slice(src); + Some(PStr { buf: self.buf.clone(), off: start, len: src.len() }) + } +} + +#[derive(Clone, Debug)] +pub struct PArr { + pub buf: Rc>>, + pub off: usize, + pub len: usize, +} + +impl PArr { + pub fn new(v: Vec) -> Self { + let len = v.len(); + PArr { buf: Rc::new(RefCell::new(v)), off: 0, len } + } + + pub fn get(&self, i: usize) -> Option { + if i >= self.len { + return None; + } + self.buf.borrow().get(self.off.checked_add(i)?).cloned() + } + + pub fn set(&self, i: usize, v: Obj) -> bool { + if i >= self.len { + return false; + } + let Some(at) = self.off.checked_add(i) else { return false }; + match self.buf.borrow_mut().get_mut(at) { + Some(slot) => { + *slot = v; + true + } + None => false, + } + } + + pub fn items(&self) -> Vec { + let b = self.buf.borrow(); + self.off.checked_add(self.len).and_then(|end| b.get(self.off..end)).map(<[Obj]>::to_vec).unwrap_or_default() + } + + pub fn interval(&self, start: usize, count: usize) -> Option { + (start.checked_add(count)? <= self.len).then(|| PArr { buf: self.buf.clone(), off: self.off + start, len: count }) + } + + pub fn same(&self, o: &PArr) -> bool { + Rc::ptr_eq(&self.buf, &o.buf) && self.off == o.off && self.len == o.len + } +} + +/// A dictionary key: names (strings become names), integers (integral reals too), booleans, and +/// anything else by identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Key { + Name(Name), + Int(i64), + Real(u64), + Bool(bool), + Null, + Ident(usize), +} + +#[derive(Debug, Default)] +pub struct DictInner { + pub map: HashMap, + pub cap: usize, +} + +#[derive(Clone, Debug)] +pub struct PDict(pub Rc>); + +impl PDict { + pub fn new(cap: usize) -> Self { + PDict(Rc::new(RefCell::new(DictInner { map: HashMap::new(), cap }))) + } + + pub fn get(&self, k: &Key) -> Option { + self.0.borrow().map.get(k).map(|(_, v)| v.clone()) + } + + pub fn get_name(&self, n: &[u8]) -> Option { + self.get(&Key::Name(name(n))) + } + + pub fn put(&self, key: Obj, v: Obj) { + let k = key.key(); + self.0.borrow_mut().map.insert(k, (key, v)); + } + + pub fn put_name(&self, n: &[u8], v: Obj) { + self.put(Obj::Name(name(n), false), v); + } + + pub fn remove(&self, k: &Key) { + self.0.borrow_mut().map.remove(k); + } + + pub fn len(&self) -> usize { + self.0.borrow().map.len() + } + + pub fn known(&self, k: &Key) -> bool { + self.0.borrow().map.contains_key(k) + } + + pub fn entries(&self) -> Vec<(Obj, Obj)> { + self.0.borrow().map.values().cloned().collect() + } + + pub fn same(&self, o: &PDict) -> bool { + Rc::ptr_eq(&self.0, &o.0) + } + + fn ident(&self) -> usize { + Rc::as_ptr(&self.0) as *const u8 as usize + } +} + +/// An open file: an index into the interpreter's sources. +pub type FileId = usize; + +#[derive(Clone, Debug)] +pub enum Obj { + Null, + Bool(bool), + Int(i64), + Real(f64), + /// A name; `true` when executable. + Name(Name, bool), + Str(PStr, bool), + Array(PArr, bool), + Dict(PDict), + Mark, + Op(OpId), + File(FileId), + /// A `save` snapshot: the graphics-state depth it restores to. + Save(usize), + /// A font identifier (`FID`). + FontId(usize), + /// A saved graphics state (`gstate`). + GState(usize), +} + +impl Obj { + pub fn key(&self) -> Key { + match self { + Obj::Name(n, _) => Key::Name(n.clone()), + Obj::Str(s, _) => Key::Name(name(&s.bytes())), + Obj::Int(i) => Key::Int(*i), + Obj::Real(r) if r.fract() == 0.0 && r.abs() < 9.0e15 => Key::Int(*r as i64), + Obj::Real(r) => Key::Real(r.to_bits()), + Obj::Bool(b) => Key::Bool(*b), + Obj::Null => Key::Null, + Obj::Array(a, _) => Key::Ident(Rc::as_ptr(&a.buf) as *const u8 as usize ^ a.off), + Obj::Dict(d) => Key::Ident(d.ident()), + Obj::Op(o) => Key::Ident(0x4000_0000 + *o as usize), + Obj::File(f) => Key::Ident(0x5000_0000 + f), + Obj::FontId(f) => Key::Ident(0x6000_0000 + f), + Obj::Mark => Key::Ident(1), + Obj::Save(s) => Key::Ident(0x7000_0000 + s), + Obj::GState(g) => Key::Ident(0x7800_0000 + g), + } + } + + pub fn type_name(&self) -> &'static [u8] { + match self { + Obj::Null => b"nulltype", + Obj::Bool(_) => b"booleantype", + Obj::Int(_) => b"integertype", + Obj::Real(_) => b"realtype", + Obj::Name(..) => b"nametype", + Obj::Str(..) => b"stringtype", + Obj::Array(..) => b"arraytype", + Obj::Dict(_) => b"dicttype", + Obj::Mark => b"marktype", + Obj::Op(_) => b"operatortype", + Obj::File(_) => b"filetype", + Obj::Save(_) => b"savetype", + Obj::FontId(_) => b"fonttype", + Obj::GState(_) => b"gstatetype", + } + } + + pub fn is_exec(&self) -> bool { + match self { + Obj::Name(_, x) | Obj::Str(_, x) | Obj::Array(_, x) => *x, + Obj::Op(_) => true, + _ => false, + } + } + + pub fn num(&self) -> Option { + match self { + Obj::Int(i) => Some(*i as f64), + Obj::Real(r) => Some(*r), + _ => None, + } + } + + pub fn str(s: &[u8]) -> Obj { + Obj::Str(PStr::new(s.to_vec()), false) + } + + pub fn lit(n: &[u8]) -> Obj { + Obj::Name(name(n), false) + } + + pub fn proc(v: Vec) -> Obj { + Obj::Array(PArr::new(v), true) + } + + /// Equality as `eq` sees it: numbers by value, strings by contents, names and strings + /// interchangeably, composites by identity. + pub fn ps_eq(&self, o: &Obj) -> bool { + match (self, o) { + (a, b) if a.num().is_some() && b.num().is_some() => a.num() == b.num(), + (Obj::Str(a, _), Obj::Str(b, _)) => a.bytes() == b.bytes(), + (Obj::Name(a, _), Obj::Name(b, _)) => a == b, + (Obj::Name(a, _), Obj::Str(b, _)) | (Obj::Str(b, _), Obj::Name(a, _)) => **a == *b.bytes(), + (Obj::Bool(a), Obj::Bool(b)) => a == b, + (Obj::Null, Obj::Null) | (Obj::Mark, Obj::Mark) => true, + (Obj::Array(a, _), Obj::Array(b, _)) => a.same(b), + (Obj::Dict(a), Obj::Dict(b)) => a.same(b), + (Obj::Op(a), Obj::Op(b)) => a == b, + (Obj::File(a), Obj::File(b)) | (Obj::FontId(a), Obj::FontId(b)) | (Obj::Save(a), Obj::Save(b)) => a == b, + (Obj::GState(a), Obj::GState(b)) => a == b, + _ => false, + } + } +} diff --git a/crates/ps/src/read/ops/basic.rs b/crates/ps/src/read/ops/basic.rs new file mode 100644 index 0000000000..7177bd7f1b --- /dev/null +++ b/crates/ps/src/read/ops/basic.rs @@ -0,0 +1,1101 @@ +//! The language: stack, arithmetic, relations, control, types, dictionaries, strings, arrays. + +use crate::read::interp::{Frame, Interp, PsErr, R, err}; +use crate::read::obj::{Key, Obj, PArr, PDict, PStr, name}; + +// ----- stack ----- + +pub fn pop(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::File(id) if !ip.file_is_live(id) => ip.discard_subfile(id), + _ => Ok(()), + } +} + +pub fn exch(ip: &mut Interp) -> R { + ip.need(2)?; + let n = ip.o.len(); + ip.o.swap(n - 1, n - 2); + Ok(()) +} + +pub fn dup(ip: &mut Interp) -> R { + let o = ip.top(0)?.clone(); + ip.push(o) +} + +pub fn copy(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Int(n) => { + let n = usize::try_from(n).map_err(|_| PsErr::Ps("rangecheck"))?; + ip.need(n)?; + // Check before cloning or charging so a hostile count cannot partially mutate the + // stack or allocate a large temporary; strict hosts still report stackoverflow. + if !ip.has_operand_room(n) { + return if ip.limits.stack_overflow_noop { Ok(()) } else { err("stackoverflow") }; + } + let start = ip.o.len() - n; + ip.charge((n / 8) as u64)?; + ip.alloc(n.saturating_mul(OBJ_BYTES))?; + let items: Vec = ip.o.get(start..).map(<[Obj]>::to_vec).unwrap_or_default(); + for o in items { + ip.push(o)?; + } + Ok(()) + } + Obj::Array(dst, x) => { + let src = ip.pop_arr()?; + if src.len > dst.len { + return err("rangecheck"); + } + ip.charge(src.len as u64)?; + ip.alloc(src.len.saturating_mul(OBJ_BYTES))?; + for (i, o) in src.items().into_iter().enumerate() { + dst.set(i, o); + } + let sub = dst.interval(0, src.len).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Array(sub, x)) + } + Obj::Str(dst, x) => { + let src = ip.pop_str()?; + ip.charge_bytes(src.len)?; + ip.alloc(src.len)?; + let w = dst.put_bytes(0, &src.bytes()).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(w, x)) + } + Obj::Dict(dst) => { + let src = ip.pop_dict()?; + ip.charge(src.len() as u64)?; + ip.alloc(src.len().saturating_mul(2 * OBJ_BYTES))?; + for (k, v) in src.entries() { + dst.put(k, v); + } + ip.push(Obj::Dict(dst)) + } + _ => err("typecheck"), + } +} + +pub fn index(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + let o = ip.top(n).map_err(|_| PsErr::Ps("rangecheck"))?.clone(); + ip.push(o) +} + +pub fn roll(ip: &mut Interp) -> R { + let j = ip.pop_int()?; + let n = ip.pop_usize()?; + ip.need(n)?; + if n == 0 { + return Ok(()); + } + let start = ip.o.len() - n; + let k = usize::try_from(j.rem_euclid(n as i64)).unwrap_or(0); + if let Some(s) = ip.o.get_mut(start..) { + s.rotate_right(k); + } + Ok(()) +} + +pub fn clear(ip: &mut Interp) -> R { + ip.o.clear(); + Ok(()) +} + +pub fn count(ip: &mut Interp) -> R { + let n = ip.o.len() as i64; + ip.push(Obj::Int(n)) +} + +pub fn mark(ip: &mut Interp) -> R { + ip.push(Obj::Mark) +} + +/// Where the topmost mark is; the search is work (a deep stack takes long). +pub fn mark_pos(ip: &mut Interp) -> R { + let i = ip.o.iter().rposition(|o| matches!(o, Obj::Mark)); + ip.charge((ip.o.len() - i.map_or(0, |i| i + 1)) as u64)?; + i.ok_or(PsErr::Ps("unmatchedmark")) +} + +/// Memory one object takes, for charging copies of arrays and stacks. +pub const OBJ_BYTES: usize = 32; + +/// A string used as a dictionary key is copied into a name: work and memory. +pub fn key_cost(ip: &mut Interp, k: &Obj) -> R { + if let Obj::Str(s, _) = k { + ip.charge_bytes(s.len)?; + ip.alloc(s.len)?; + } + Ok(()) +} + +pub fn cleartomark(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + ip.o.truncate(i); + Ok(()) +} + +pub fn counttomark(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + let n = (ip.o.len() - i - 1) as i64; + ip.push(Obj::Int(n)) +} + +pub fn array_close(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + let items = ip.o.split_off(i + 1); + ip.o.pop(); + ip.alloc(items.len().saturating_mul(OBJ_BYTES))?; + ip.push(Obj::Array(PArr::new(items), false)) +} + +pub fn dict_close(ip: &mut Interp) -> R { + let i = mark_pos(ip)?; + let items = ip.o.split_off(i + 1); + ip.o.pop(); + if !items.len().is_multiple_of(2) { + return err("rangecheck"); + } + ip.alloc(items.len().saturating_mul(OBJ_BYTES))?; + for k in items.iter().step_by(2) { + key_cost(ip, k)?; + } + let d = PDict::new(items.len() / 2); + let mut it = items.into_iter(); + while let (Some(k), Some(v)) = (it.next(), it.next()) { + d.put(k, v); + } + ip.push(Obj::Dict(d)) +} + +// ----- arithmetic ----- + +fn arith(ip: &mut Interp, fi: fn(i64, i64) -> Option, fr: fn(f64, f64) -> f64) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + match (&a, &b) { + (Obj::Int(x), Obj::Int(y)) => match fi(*x, *y).filter(|v| i32::try_from(*v).is_ok()) { + Some(v) => ip.push(Obj::Int(v)), + None => ip.push(Obj::Real(fr(*x as f64, *y as f64))), + }, + _ => { + let (Some(x), Some(y)) = (a.num(), b.num()) else { return err("typecheck") }; + let v = fr(x, y); + if !v.is_finite() { + return err("undefinedresult"); + } + ip.push(Obj::Real(v)) + } + } +} + +pub fn add(ip: &mut Interp) -> R { + arith(ip, i64::checked_add, |a, b| a + b) +} + +pub fn sub(ip: &mut Interp) -> R { + arith(ip, i64::checked_sub, |a, b| a - b) +} + +pub fn mul(ip: &mut Interp) -> R { + arith(ip, i64::checked_mul, |a, b| a * b) +} + +pub fn div(ip: &mut Interp) -> R { + let b = ip.pop_num()?; + let a = ip.pop_num()?; + if b == 0.0 { + return err("undefinedresult"); + } + ip.push(Obj::Real(a / b)) +} + +pub fn idiv(ip: &mut Interp) -> R { + let b = ip.pop_int()?; + let a = ip.pop_int()?; + if b == 0 { + if ip.limits.zero_division_zero { + return ip.push(Obj::Int(0)); + } + return err("undefinedresult"); + } + // The signed minimum divided by -1 overflows the host integer type. PostScript integer + // arithmetic wraps this one exceptional result to zero rather than raising an error. + let v = a.checked_div(b).unwrap_or(0); + ip.push(Obj::Int(v)) +} + +pub fn mod_(ip: &mut Interp) -> R { + let b = ip.pop_int()?; + let a = ip.pop_int()?; + if b == 0 { + if ip.limits.zero_division_zero { + return ip.push(Obj::Int(0)); + } + return err("undefinedresult"); + } + let v = a.checked_rem(b).unwrap_or(0); + ip.push(Obj::Int(v)) +} + +fn unary(ip: &mut Interp, fi: fn(i64) -> Option, fr: fn(f64) -> f64) -> R { + match ip.pop()? { + Obj::Int(i) => match fi(i) { + Some(v) => ip.push(Obj::Int(v)), + None => ip.push(Obj::Real(fr(i as f64))), + }, + Obj::Real(r) => ip.push(Obj::Real(fr(r))), + _ => err("typecheck"), + } +} + +pub fn neg(ip: &mut Interp) -> R { + unary(ip, i64::checked_neg, |r| -r) +} + +pub fn abs(ip: &mut Interp) -> R { + unary(ip, i64::checked_abs, f64::abs) +} + +pub fn ceiling(ip: &mut Interp) -> R { + unary(ip, Some, f64::ceil) +} + +pub fn floor(ip: &mut Interp) -> R { + unary(ip, Some, f64::floor) +} + +pub fn round(ip: &mut Interp) -> R { + // PostScript rounds halves up (toward +∞). + unary(ip, Some, |r| (r + 0.5).floor()) +} + +pub fn truncate(ip: &mut Interp) -> R { + unary(ip, Some, f64::trunc) +} + +fn real_fn(ip: &mut Interp, f: fn(f64) -> f64) -> R { + let a = ip.pop_num()?; + let v = f(a); + if !v.is_finite() { + return err("undefinedresult"); + } + ip.push(Obj::Real(v)) +} + +pub fn sqrt(ip: &mut Interp) -> R { + let a = ip.pop_num()?; + if a < 0.0 { + return err("rangecheck"); + } + ip.push(Obj::Real(a.sqrt())) +} + +pub fn sin(ip: &mut Interp) -> R { + real_fn(ip, |d| d.to_radians().sin()) +} + +pub fn cos(ip: &mut Interp) -> R { + real_fn(ip, |d| d.to_radians().cos()) +} + +pub fn atan(ip: &mut Interp) -> R { + let den = ip.pop_num()?; + let num = ip.pop_num()?; + if num == 0.0 && den == 0.0 { + return err("undefinedresult"); + } + let mut a = num.atan2(den).to_degrees(); + if a < 0.0 { + a += 360.0; + } + ip.push(Obj::Real(a)) +} + +pub fn exp(ip: &mut Interp) -> R { + let e = ip.pop_num()?; + let b = ip.pop_num()?; + let v = b.powf(e); + if !v.is_finite() { + return err("undefinedresult"); + } + ip.push(Obj::Real(v)) +} + +pub fn ln(ip: &mut Interp) -> R { + let a = ip.pop_num()?; + if a <= 0.0 { + return err("rangecheck"); + } + ip.push(Obj::Real(a.ln())) +} + +pub fn log(ip: &mut Interp) -> R { + let a = ip.pop_num()?; + if a <= 0.0 { + return err("rangecheck"); + } + ip.push(Obj::Real(a.log10())) +} + +pub fn rand(ip: &mut Interp) -> R { + // A fixed, repeatable sequence (no entropy in conversions). + ip.steps = ip.steps.wrapping_add(1); + let v = (ip.steps.wrapping_mul(1_103_515_245).wrapping_add(12345) >> 1) & 0x7FFF_FFFF; + ip.push(Obj::Int(v as i64)) +} + +pub fn srand(ip: &mut Interp) -> R { + ip.pop_int().map(|_| ()) +} + +pub fn rrand(ip: &mut Interp) -> R { + ip.push(Obj::Int(0)) +} + +// ----- relations, booleans, bits ----- + +/// Comparing strings compares (and copies) their bytes. +fn compare_cost(ip: &mut Interp, a: &Obj, b: &Obj) -> R { + let len = |o: &Obj| match o { + Obj::Str(s, _) => s.len, + Obj::Name(n, _) => n.len(), + _ => 0, + }; + if matches!(a, Obj::Str(..)) || matches!(b, Obj::Str(..)) { + let n = len(a).saturating_add(len(b)); + ip.charge_bytes(n)?; + ip.alloc(n)?; + } + Ok(()) +} + +pub fn eq(ip: &mut Interp) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + compare_cost(ip, &a, &b)?; + ip.push(Obj::Bool(a.ps_eq(&b))) +} + +pub fn ne(ip: &mut Interp) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + compare_cost(ip, &a, &b)?; + ip.push(Obj::Bool(!a.ps_eq(&b))) +} + +fn compare(ip: &mut Interp, f: fn(std::cmp::Ordering) -> bool) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + compare_cost(ip, &a, &b)?; + let ord = match (&a, &b) { + (Obj::Str(x, _), Obj::Str(y, _)) => x.bytes().cmp(&y.bytes()), + _ => { + let (Some(x), Some(y)) = (a.num(), b.num()) else { return err("typecheck") }; + x.partial_cmp(&y).ok_or(PsErr::Ps("undefinedresult"))? + } + }; + ip.push(Obj::Bool(f(ord))) +} + +pub fn gt(ip: &mut Interp) -> R { + compare(ip, |o| o.is_gt()) +} + +pub fn ge(ip: &mut Interp) -> R { + compare(ip, |o| o.is_ge()) +} + +pub fn lt(ip: &mut Interp) -> R { + compare(ip, |o| o.is_lt()) +} + +pub fn le(ip: &mut Interp) -> R { + compare(ip, |o| o.is_le()) +} + +fn logic(ip: &mut Interp, fb: fn(bool, bool) -> bool, fi: fn(i64, i64) -> i64) -> R { + let b = ip.pop()?; + let a = ip.pop()?; + match (a, b) { + (Obj::Bool(x), Obj::Bool(y)) => ip.push(Obj::Bool(fb(x, y))), + (Obj::Int(x), Obj::Int(y)) => ip.push(Obj::Int(fi(x, y))), + _ => err("typecheck"), + } +} + +pub fn and(ip: &mut Interp) -> R { + logic(ip, |a, b| a & b, |a, b| a & b) +} + +pub fn or(ip: &mut Interp) -> R { + logic(ip, |a, b| a | b, |a, b| a | b) +} + +pub fn xor(ip: &mut Interp) -> R { + logic(ip, |a, b| a ^ b, |a, b| a ^ b) +} + +pub fn not(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Bool(b) => ip.push(Obj::Bool(!b)), + Obj::Int(i) => ip.push(Obj::Int(!i)), + _ => err("typecheck"), + } +} + +pub fn bitshift(ip: &mut Interp) -> R { + let s = ip.pop_int()?; + let v = ip.pop_int()? as i32 as u32; + let r = if s >= 0 { v.checked_shl(s.min(32) as u32).unwrap_or(0) } else { v.checked_shr((-s).min(32) as u32).unwrap_or(0) }; + ip.push(Obj::Int(i64::from(r as i32))) +} + +pub fn true_(ip: &mut Interp) -> R { + ip.push(Obj::Bool(true)) +} + +pub fn false_(ip: &mut Interp) -> R { + ip.push(Obj::Bool(false)) +} + +pub fn null(ip: &mut Interp) -> R { + ip.push(Obj::Null) +} + +// ----- control ----- + +pub fn exec(ip: &mut Interp) -> R { + let o = ip.pop()?; + ip.exec_value(o) +} + +pub fn if_(ip: &mut Interp) -> R { + let p = ip.pop()?; + if ip.pop_bool()? { ip.exec_value(p) } else { Ok(()) } +} + +pub fn ifelse(ip: &mut Interp) -> R { + let pf = ip.pop()?; + let pt = ip.pop()?; + if ip.pop_bool()? { ip.exec_value(pt) } else { ip.exec_value(pf) } +} + +pub fn for_(ip: &mut Interp) -> R { + let proc = ip.pop()?; + let limit = ip.pop()?; + let inc = ip.pop()?; + let init = ip.pop()?; + let int = matches!((&init, &inc), (Obj::Int(_), Obj::Int(_))); + let (Some(cur), Some(inc), Some(limit)) = (init.num(), inc.num(), limit.num()) else { return err("typecheck") }; + if inc == 0.0 { + // Runs forever in PostScript; the step limit would end it. Treat as empty. + return Ok(()); + } + ip.push_frame(Frame::For { cur, inc, limit, int, proc }) +} + +pub fn repeat(ip: &mut Interp) -> R { + let proc = ip.pop()?; + let n = ip.pop_int()?; + if n < 0 { + return err("rangecheck"); + } + ip.push_frame(Frame::Repeat { n, proc }) +} + +pub fn loop_(ip: &mut Interp) -> R { + let proc = ip.pop()?; + ip.push_frame(Frame::Loop { proc }) +} + +pub fn exit(ip: &mut Interp) -> R { + let depth = ip.e.len() as u64; + ip.charge(depth / 16)?; + let i = ip.e.iter().rposition(|f| f.is_loop() || matches!(f, Frame::Stopped | Frame::Barrier)).ok_or(PsErr::Ps("invalidexit"))?; + if !ip.e.get(i).is_some_and(Frame::is_loop) { + return err("invalidexit"); + } + ip.e.truncate(i); + Ok(()) +} + +pub fn stop(_ip: &mut Interp) -> R { + Err(PsErr::Stop) +} + +pub fn stopped(ip: &mut Interp) -> R { + let p = ip.pop()?; + ip.push_frame(Frame::Stopped)?; + ip.exec_value(p) +} + +pub fn quit(_ip: &mut Interp) -> R { + Err(PsErr::Quit) +} + +pub fn forall(ip: &mut Interp) -> R { + let proc = ip.pop()?; + match ip.pop()? { + Obj::Array(arr, _) => ip.push_frame(Frame::ForallArr { arr, i: 0, proc }), + Obj::Str(s, _) => ip.push_frame(Frame::ForallStr { s, i: 0, proc }), + Obj::Dict(d) => { + // The entries are copied first (the procedure may change the dictionary). + ip.charge(d.len() as u64)?; + ip.alloc(d.len().saturating_mul(2 * OBJ_BYTES))?; + ip.push_frame(Frame::ForallDict { items: d.entries(), i: 0, proc }) + } + _ => err("typecheck"), + } +} + +pub fn countexecstack(ip: &mut Interp) -> R { + let n = ip.e.len() as i64; + ip.push(Obj::Int(n)) +} + +pub fn execstack(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + let n = ip.e.len().min(a.len); + let sub = a.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.charge(n as u64)?; + for i in 0..n { + sub.set(i, Obj::Null); + } + ip.push(Obj::Array(sub, false)) +} + +// ----- types and conversion ----- + +pub fn type_(ip: &mut Interp) -> R { + let o = ip.pop()?; + ip.push(Obj::Name(name(o.type_name()), true)) +} + +pub fn cvlit(ip: &mut Interp) -> R { + let o = match ip.pop()? { + Obj::Name(n, _) => Obj::Name(n, false), + Obj::Array(a, _) => Obj::Array(a, false), + Obj::Str(s, _) => Obj::Str(s, false), + o => o, + }; + ip.push(o) +} + +pub fn cvx(ip: &mut Interp) -> R { + let o = match ip.pop()? { + Obj::Name(n, _) => Obj::Name(n, true), + Obj::Array(a, _) => Obj::Array(a, true), + Obj::Str(s, _) => Obj::Str(s, true), + o => o, + }; + ip.push(o) +} + +pub fn xcheck(ip: &mut Interp) -> R { + let o = ip.pop()?; + ip.push(Obj::Bool(o.is_exec())) +} + +/// Access attributes aren't enforced: everything stays readable and writable. +pub fn noop_keep(ip: &mut Interp) -> R { + ip.top(0).map(|_| ()) +} + +pub fn check_true(ip: &mut Interp) -> R { + ip.pop()?; + ip.push(Obj::Bool(true)) +} + +pub fn cvi(ip: &mut Interp) -> R { + let v = match ip.pop()? { + Obj::Int(i) => i, + Obj::Real(r) if r.is_finite() && r.abs() < 2.2e9 => r.trunc() as i64, + Obj::Str(s, _) if s.len > 4096 => return err("limitcheck"), + Obj::Str(s, _) => match crate::read::scan::number(&s.bytes()) { + Some(o) => o.num().filter(|v| v.abs() < 2.2e9).ok_or(PsErr::Ps("rangecheck"))?.trunc() as i64, + None => return err("syntaxerror"), + }, + Obj::Real(_) => return err("rangecheck"), + _ => return err("typecheck"), + }; + ip.push(Obj::Int(v)) +} + +pub fn cvr(ip: &mut Interp) -> R { + let v = match ip.pop()? { + o @ (Obj::Int(_) | Obj::Real(_)) => o.num().unwrap_or(0.0), + Obj::Str(s, _) if s.len > 4096 => return err("limitcheck"), + Obj::Str(s, _) => crate::read::scan::number(&s.bytes()).and_then(|o| o.num()).ok_or(PsErr::Ps("syntaxerror"))?, + _ => return err("typecheck"), + }; + ip.push(Obj::Real(v)) +} + +pub fn cvn(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Str(s, x) => { + ip.charge_bytes(s.len)?; + ip.alloc(s.len)?; + ip.push(Obj::Name(name(&s.bytes()), x)) + } + n @ Obj::Name(..) => ip.push(n), + _ => err("typecheck"), + } +} + +/// The text `cvs`/`=` print for an object. +pub fn text_of(o: &Obj) -> Vec { + match o { + Obj::Int(i) => i.to_string().into_bytes(), + Obj::Real(r) => { + if r.fract() == 0.0 && r.abs() < 1e15 { + format!("{r:.1}").into_bytes() + } else { + format!("{r}").into_bytes() + } + } + Obj::Bool(b) => { + if *b { + b"true".to_vec() + } else { + b"false".to_vec() + } + } + Obj::Name(n, _) => n.to_vec(), + Obj::Str(s, _) => s.bytes(), + Obj::Op(op) => crate::read::ops::OPS.get(*op as usize).map(|(n, _)| n.to_vec()).unwrap_or_default(), + _ => b"--nostringval--".to_vec(), + } +} + +pub fn cvs(ip: &mut Interp) -> R { + let dst = ip.pop_str()?; + let o = ip.pop()?; + ip.charge_bytes(dst.len)?; + let t = text_of(&o); + let w = dst.put_bytes(0, &t).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(w, false)) +} + +pub fn cvrs(ip: &mut Interp) -> R { + let dst = ip.pop_str()?; + let radix = ip.pop_int()?; + let n = ip.pop_num()?; + if !(2..=36).contains(&radix) { + return err("rangecheck"); + } + let t = if radix == 10 { + text_of(&Obj::Real(n)) + } else { + let mut v = (n as i64 as i32) as u32; + let mut digits = Vec::new(); + loop { + let d = (v % radix as u32) as u8; + digits.push(if d < 10 { b'0' + d } else { b'A' + d - 10 }); + v /= radix as u32; + if v == 0 { + break; + } + } + digits.reverse(); + digits + }; + let w = dst.put_bytes(0, &t).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(w, false)) +} + +// ----- dictionaries ----- + +pub fn dict(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.alloc(64)?; + ip.push(Obj::Dict(PDict::new(n.min(100_000)))) +} + +pub fn maxlength(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + let n = d.0.borrow().cap.max(d.len()) as i64; + ip.push(Obj::Int(n)) +} + +pub fn begin(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + ip.begin(d) +} + +pub fn end(ip: &mut Interp) -> R { + // systemdict, globaldict and userdict stay. + if ip.d.len() <= 3 { + return err("dictstackunderflow"); + } + ip.d.pop(); + Ok(()) +} + +pub fn def(ip: &mut Interp) -> R { + let v = ip.pop()?; + let k = ip.pop()?; + key_cost(ip, &k)?; + ip.alloc(2 * OBJ_BYTES)?; + ip.current_dict()?.put(k, v); + Ok(()) +} + +pub fn load(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + let Some(v) = ip.lookup(&k.key()) else { + ip.dollar_error.put_name(b"offending", k); + return err("undefined"); + }; + ip.push(v) +} + +pub fn store(ip: &mut Interp) -> R { + let v = ip.pop()?; + let k = ip.pop()?; + key_cost(ip, &k)?; + let key = k.key(); + let d = ip.d.iter().rev().find(|d| d.known(&key)).cloned().map_or_else(|| ip.current_dict(), Ok)?; + d.put(k, v); + Ok(()) +} + +pub fn get(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + match ip.pop()? { + Obj::Dict(d) => { + let Some(v) = d.get(&k.key()) else { + ip.dollar_error.put_name(b"offending", k); + return err("undefined"); + }; + ip.push(v) + } + Obj::Array(a, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + let v = a.get(i).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(v) + } + Obj::Str(s, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + let v = s.get(i).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Int(i64::from(v))) + } + _ => err("typecheck"), + } +} + +fn int_of(o: &Obj) -> R { + match o { + Obj::Int(i) => Ok(*i), + _ => err("typecheck"), + } +} + +pub fn put(ip: &mut Interp) -> R { + let v = ip.pop()?; + let k = ip.pop()?; + match ip.pop()? { + Obj::Dict(d) => { + key_cost(ip, &k)?; + ip.alloc(2 * OBJ_BYTES)?; + d.put(k, v); + Ok(()) + } + Obj::Array(a, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + if a.set(i, v) { Ok(()) } else { err("rangecheck") } + } + Obj::Str(s, _) => { + let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; + let b = u8::try_from(int_of(&v)? & 0xFF).unwrap_or(0); + if s.set(i, b) { Ok(()) } else { err("rangecheck") } + } + _ => err("typecheck"), + } +} + +pub fn known(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + let d = ip.pop_dict()?; + ip.push(Obj::Bool(d.known(&k.key()))) +} + +pub fn undef(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + let d = ip.pop_dict()?; + d.remove(&k.key()); + Ok(()) +} + +pub fn where_(ip: &mut Interp) -> R { + let k = ip.pop()?; + key_cost(ip, &k)?; + ip.charge(ip.d.len() as u64 / 16)?; + let k = k.key(); + match ip.d.iter().rev().find(|d| d.known(&k)).cloned() { + Some(d) => { + ip.push(Obj::Dict(d))?; + ip.push(Obj::Bool(true)) + } + None => ip.push(Obj::Bool(false)), + } +} + +pub fn currentdict(ip: &mut Interp) -> R { + let d = ip.current_dict()?; + ip.push(Obj::Dict(d)) +} + +pub fn countdictstack(ip: &mut Interp) -> R { + let n = ip.d.len() as i64; + ip.push(Obj::Int(n)) +} + +pub fn dictstack(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + let n = ip.d.len().min(a.len); + for (i, d) in ip.d.iter().take(n).enumerate() { + a.set(i, Obj::Dict(d.clone())); + } + let sub = a.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Array(sub, false)) +} + +pub fn cleardictstack(ip: &mut Interp) -> R { + ip.d.truncate(3); + Ok(()) +} + +// ----- strings and arrays ----- + +pub fn array(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.charge(n as u64)?; + ip.alloc(n.saturating_mul(OBJ_BYTES))?; + ip.push(Obj::Array(PArr::new(vec![Obj::Null; n]), false)) +} + +pub fn string(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.charge_bytes(n)?; + ip.alloc(n)?; + ip.push(Obj::Str(PStr::new(vec![0; n]), false)) +} + +pub fn length(ip: &mut Interp) -> R { + let n = match ip.pop()? { + Obj::Array(a, _) => a.len, + Obj::Str(s, _) => s.len, + Obj::Dict(d) => d.len(), + Obj::Name(n, _) => n.len(), + _ => return err("typecheck"), + }; + ip.push(Obj::Int(n as i64)) +} + +pub fn getinterval(ip: &mut Interp) -> R { + let count = ip.pop_usize()?; + let start = ip.pop_usize()?; + match ip.pop()? { + Obj::Array(a, x) => { + let s = a.interval(start, count).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Array(s, x)) + } + Obj::Str(s, x) => { + let s = s.interval(start, count).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(s, x)) + } + _ => err("typecheck"), + } +} + +pub fn putinterval(ip: &mut Interp) -> R { + let src = ip.pop()?; + let start = ip.pop_usize()?; + match (ip.pop()?, src) { + (Obj::Array(dst, _), Obj::Array(src, _)) => { + if start.checked_add(src.len).is_none_or(|e| e > dst.len) { + return err("rangecheck"); + } + ip.charge(src.len as u64)?; + ip.alloc(src.len.saturating_mul(OBJ_BYTES))?; + for (i, o) in src.items().into_iter().enumerate() { + dst.set(start + i, o); + } + Ok(()) + } + (Obj::Str(dst, _), Obj::Str(src, _)) => { + ip.charge_bytes(src.len)?; + ip.alloc(src.len)?; + dst.put_bytes(start, &src.bytes()).map(|_| ()).ok_or(PsErr::Ps("rangecheck")) + } + _ => err("typecheck"), + } +} + +pub fn aload(ip: &mut Interp) -> R { + let o = ip.pop()?; + let Obj::Array(a, _) = &o else { return err("typecheck") }; + ip.charge(a.len as u64)?; + ip.alloc(a.len.saturating_mul(OBJ_BYTES))?; + for v in a.items() { + ip.push(v)?; + } + ip.push(o) +} + +pub fn astore(ip: &mut Interp) -> R { + let o = ip.pop()?; + let Obj::Array(a, _) = &o else { return err("typecheck") }; + ip.need(a.len)?; + ip.charge(a.len as u64)?; + let start = ip.o.len() - a.len; + let items = ip.o.split_off(start); + for (i, v) in items.into_iter().enumerate() { + a.set(i, v); + } + ip.push(o) +} + +pub fn packedarray(ip: &mut Interp) -> R { + let n = ip.pop_usize()?; + ip.need(n)?; + ip.charge(n as u64)?; + ip.alloc(n.saturating_mul(OBJ_BYTES))?; + let start = ip.o.len() - n; + let items = ip.o.split_off(start); + ip.push(Obj::Array(PArr::new(items), false)) +} + +pub fn search(ip: &mut Interp) -> R { + let seek = ip.pop_str()?.bytes(); + let s = ip.pop_str()?; + ip.charge_bytes(s.len.saturating_add(seek.len()))?; + ip.alloc(s.len.saturating_add(seek.len()))?; + let hay = s.bytes(); + let found = find(ip, &hay, &seek)?; + match found { + Some(i) => { + let post = s.interval(i + seek.len(), hay.len() - i - seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + let m = s.interval(i, seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + let pre = s.interval(0, i).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(post, false))?; + ip.push(Obj::Str(m, false))?; + ip.push(Obj::Str(pre, false))?; + ip.push(Obj::Bool(true)) + } + None => { + ip.push(Obj::Str(s, false))?; + ip.push(Obj::Bool(false)) + } + } +} + +/// Where `seek` first occurs in `hay`, charging the bytes compared as it goes (a naive search +/// costs |hay| × |seek| on inputs made to defeat it). +fn find(ip: &mut Interp, hay: &[u8], seek: &[u8]) -> R> { + if seek.is_empty() { + return Ok(Some(0)); + } + let mut compared = 0usize; + for (i, w) in hay.windows(seek.len()).enumerate() { + let same = w.iter().zip(seek).take_while(|(a, b)| a == b).count(); + compared += same + 1; + if same == seek.len() { + ip.charge_bytes(compared)?; + return Ok(Some(i)); + } + if compared >= 1 << 16 { + ip.charge_bytes(compared)?; + compared = 0; + } + } + ip.charge_bytes(compared)?; + Ok(None) +} + +pub fn anchorsearch(ip: &mut Interp) -> R { + let seek = ip.pop_str()?.bytes(); + let s = ip.pop_str()?; + ip.charge_bytes(s.len.saturating_add(seek.len()))?; + ip.alloc(s.len.saturating_add(seek.len()))?; + if s.bytes().starts_with(&seek) { + let post = s.interval(seek.len(), s.len - seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + let m = s.interval(0, seek.len()).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(post, false))?; + ip.push(Obj::Str(m, false))?; + ip.push(Obj::Bool(true)) + } else { + ip.push(Obj::Str(s, false))?; + ip.push(Obj::Bool(false)) + } +} + +/// `token` on a string: the first object and the rest. +pub fn token(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::Str(s, _) => { + let id = ip.add_source(crate::read::source::Source::string(&s))?; + let d = &ip.d; + let mut resolve = |n: &[u8]| d.iter().rev().find_map(|dict| dict.get(&Key::Name(name(n)))); + match crate::read::scan::next(&mut ip.srcs, id, &mut resolve) { + Ok(Some(o)) => { + let used = ip.srcs.position(id).unwrap_or(s.len).min(s.len); + let rest = s.interval(used, s.len - used).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(rest, false))?; + ip.push(o)?; + ip.push(Obj::Bool(true)) + } + Ok(None) => ip.push(Obj::Bool(false)), + Err(_) => err("syntaxerror"), + } + } + Obj::File(id) => { + let d = &ip.d; + let mut resolve = |n: &[u8]| d.iter().rev().find_map(|dict| dict.get(&Key::Name(name(n)))); + match crate::read::scan::next(&mut ip.srcs, id, &mut resolve) { + Ok(Some(o)) => { + ip.push(o)?; + ip.push(Obj::Bool(true)) + } + Ok(None) => ip.push(Obj::Bool(false)), + Err(_) => err("syntaxerror"), + } + } + _ => err("typecheck"), + } +} + +/// `bind`: executable names that name operators become the operators, through nested +/// procedures (each procedure once). +pub fn bind(ip: &mut Interp) -> R { + let o = ip.top(0)?.clone(); + let Obj::Array(root, _) = o else { return Ok(()) }; + let mut todo = vec![root]; + let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + while let Some(a) = todo.pop() { + let id = std::rc::Rc::as_ptr(&a.buf) as *const u8 as usize; + if seen.len() > 100_000 || !seen.insert(id) { + continue; + } + ip.charge(a.len as u64)?; + for i in 0..a.len { + match a.get(i) { + Some(Obj::Name(n, true)) => { + if let Some(Obj::Op(op)) = ip.lookup(&Key::Name(n)) { + a.set(i, Obj::Op(op)); + } + } + Some(Obj::Array(sub, true)) => todo.push(sub), + _ => {} + } + } + } + Ok(()) +} diff --git a/crates/ps/src/read/ops/gfx.rs b/crates/ps/src/read/ops/gfx.rs new file mode 100644 index 0000000000..489c9fe860 --- /dev/null +++ b/crates/ps/src/read/ops/gfx.rs @@ -0,0 +1,1257 @@ +//! Graphics: the graphics state, matrices, paths, painting, clipping and colour. + +use std::rc::Rc; + +use crate::read::gstate::{Clip, DevColor, GState, M, MAX_PATH, Seg, Space, arc_curve_count, arc_curves, bbox, bounded_arc_sweep, flatten}; +use crate::read::interp::{Interp, PsErr, R, SEG_BYTES, err, matrix_obj}; +use crate::read::obj::{Obj, PArr, PDict}; +use crate::read::pdf::StrokeParams; + +// ----- graphics-state stack ----- + +pub fn gsave(ip: &mut Interp) -> R { + ip.gsave() +} + +pub fn grestore(ip: &mut Interp) -> R { + ip.grestore(); + Ok(()) +} + +pub fn grestoreall(ip: &mut Interp) -> R { + let floor = ip.saves.last().copied().unwrap_or(0); + while ip.gstack.len() > floor { + ip.grestore(); + } + Ok(()) +} + +pub fn initgraphics(ip: &mut Interp) -> R { + let font = ip.gs.font.clone(); + ip.gs = GState { font, ..GState::default() }; + Ok(()) +} + +pub fn save(ip: &mut Interp) -> R { + ip.gsave()?; + ip.saves.push(ip.gstack.len()); + let n = ip.saves.len(); + ip.push(Obj::Save(n)) +} + +pub fn restore(ip: &mut Interp) -> R { + let Obj::Save(n) = ip.pop()? else { return err("typecheck") }; + if n == 0 || n > ip.saves.len() { + return err("invalidrestore"); + } + let depth = ip.saves.get(n - 1).copied().unwrap_or(0); + ip.saves.truncate(n - 1); + // Back to the state saved with it (save did a gsave, leaving `depth` states stacked). + while ip.gstack.len() >= depth.max(1) { + let Some(g) = ip.gstack.pop() else { break }; + ip.gs = g; + } + Ok(()) +} + +pub fn gstate(ip: &mut Interp) -> R { + ip.charge_gstate()?; + if ip.gstates.len() > 100_000 { + return err("limitcheck"); + } + ip.gstates.push(ip.gs.clone()); + let n = ip.gstates.len() - 1; + ip.push(Obj::GState(n)) +} + +pub fn currentgstate(ip: &mut Interp) -> R { + ip.charge_gstate()?; + let Obj::GState(n) = ip.pop()? else { return err("typecheck") }; + if let Some(slot) = ip.gstates.get_mut(n) { + *slot = ip.gs.clone(); + } + ip.push(Obj::GState(n)) +} + +pub fn setgstate(ip: &mut Interp) -> R { + ip.charge_gstate()?; + let Obj::GState(n) = ip.pop()? else { return err("typecheck") }; + if let Some(g) = ip.gstates.get(n) { + ip.gs = g.clone(); + } + Ok(()) +} + +// ----- line parameters ----- + +pub fn setlinewidth(ip: &mut Interp) -> R { + ip.gs.line_width = ip.pop_num()?.abs(); + Ok(()) +} + +pub fn currentlinewidth(ip: &mut Interp) -> R { + let w = ip.gs.line_width; + ip.push(Obj::Real(w)) +} + +pub fn setlinecap(ip: &mut Interp) -> R { + ip.gs.cap = ip.pop_int()?.clamp(0, 2); + Ok(()) +} + +pub fn currentlinecap(ip: &mut Interp) -> R { + let v = ip.gs.cap; + ip.push(Obj::Int(v)) +} + +pub fn setlinejoin(ip: &mut Interp) -> R { + ip.gs.join = ip.pop_int()?.clamp(0, 2); + Ok(()) +} + +pub fn currentlinejoin(ip: &mut Interp) -> R { + let v = ip.gs.join; + ip.push(Obj::Int(v)) +} + +pub fn setmiterlimit(ip: &mut Interp) -> R { + ip.gs.miter = ip.pop_num()?.max(1.0); + Ok(()) +} + +pub fn currentmiterlimit(ip: &mut Interp) -> R { + let v = ip.gs.miter; + ip.push(Obj::Real(v)) +} + +pub fn setdash(ip: &mut Interp) -> R { + let phase = ip.pop_num()?; + let a = ip.pop_arr()?; + let mut v = Vec::with_capacity(a.len.min(64)); + for o in a.items().iter().take(64) { + v.push(o.num().ok_or(PsErr::Ps("typecheck"))?); + } + ip.gs.dash = (v, phase); + Ok(()) +} + +pub fn currentdash(ip: &mut Interp) -> R { + let (v, phase) = ip.gs.dash.clone(); + ip.push(Obj::Array(PArr::new(v.into_iter().map(Obj::Real).collect()), false))?; + ip.push(Obj::Real(phase)) +} + +pub fn setflat(ip: &mut Interp) -> R { + ip.gs.flat = ip.pop_num()?.clamp(0.2, 100.0); + Ok(()) +} + +pub fn currentflat(ip: &mut Interp) -> R { + let v = ip.gs.flat; + ip.push(Obj::Real(v)) +} + +pub fn setstrokeadjust(ip: &mut Interp) -> R { + ip.gs.stroke_adjust = ip.pop_bool()?; + Ok(()) +} + +pub fn currentstrokeadjust(ip: &mut Interp) -> R { + let v = ip.gs.stroke_adjust; + ip.push(Obj::Bool(v)) +} + +pub fn setoverprint(ip: &mut Interp) -> R { + ip.gs.overprint = ip.pop_bool()?; + Ok(()) +} + +pub fn currentoverprint(ip: &mut Interp) -> R { + let v = ip.gs.overprint; + ip.push(Obj::Bool(v)) +} + +// ----- matrices ----- + +fn fill_matrix(a: &PArr, m: &M) -> R { + if a.len != 6 { + return err("rangecheck"); + } + for (i, v) in m.0.iter().enumerate() { + a.set(i, Obj::Real(*v)); + } + Ok(()) +} + +pub fn matrix(ip: &mut Interp) -> R { + ip.push(matrix_obj(&M::ID)) +} + +pub fn identmatrix(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + fill_matrix(&a, &M::ID)?; + ip.push(Obj::Array(a, false)) +} + +pub fn defaultmatrix(ip: &mut Interp) -> R { + identmatrix(ip) +} + +pub fn initmatrix(ip: &mut Interp) -> R { + ip.gs.ctm = M::ID; + Ok(()) +} + +pub fn currentmatrix(ip: &mut Interp) -> R { + let a = ip.pop_arr()?; + fill_matrix(&a, &ip.gs.ctm)?; + ip.push(Obj::Array(a, false)) +} + +pub fn setmatrix(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + if !m.finite() { + return err("undefinedresult"); + } + ip.gs.ctm = m; + Ok(()) +} + +/// Operators that either change the CTM or, given a matrix operand, fill it in. +fn modify(ip: &mut Interp, args: usize, make: fn(&[f64]) -> M) -> R { + if let Ok(Obj::Array(a, _)) = ip.top(0).cloned() { + ip.pop()?; + let mut v = vec![0.0; args]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + fill_matrix(&a, &make(&v))?; + return ip.push(Obj::Array(a, false)); + } + let mut v = vec![0.0; args]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + let m = make(&v).then(&ip.gs.ctm); + if !m.finite() { + return err("undefinedresult"); + } + ip.gs.ctm = m; + Ok(()) +} + +fn arg(v: &[f64], i: usize) -> f64 { + v.get(i).copied().unwrap_or(0.0) +} + +pub fn translate(ip: &mut Interp) -> R { + modify(ip, 2, |v| M([1.0, 0.0, 0.0, 1.0, arg(v, 0), arg(v, 1)])) +} + +pub fn scale(ip: &mut Interp) -> R { + modify(ip, 2, |v| M([arg(v, 0), 0.0, 0.0, arg(v, 1), 0.0, 0.0])) +} + +pub fn rotate(ip: &mut Interp) -> R { + modify(ip, 1, |v| { + let a = arg(v, 0).to_radians(); + let (s, c) = a.sin_cos(); + M([c, s, -s, c, 0.0, 0.0]) + }) +} + +pub fn concat(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + let r = m.then(&ip.gs.ctm); + if !r.finite() { + return err("undefinedresult"); + } + ip.gs.ctm = r; + Ok(()) +} + +pub fn concatmatrix(ip: &mut Interp) -> R { + let dst = ip.pop_arr()?; + let m2 = ip.pop_matrix()?; + let m1 = ip.pop_matrix()?; + fill_matrix(&dst, &m1.then(&m2))?; + ip.push(Obj::Array(dst, false)) +} + +pub fn invertmatrix(ip: &mut Interp) -> R { + let dst = ip.pop_arr()?; + let m = ip.pop_matrix()?; + let inv = m.inv().ok_or(PsErr::Ps("undefinedresult"))?; + fill_matrix(&dst, &inv)?; + ip.push(Obj::Array(dst, false)) +} + +fn xform(ip: &mut Interp, f: fn(&M, f64, f64) -> Option<(f64, f64)>) -> R { + let m = match ip.top(0)? { + Obj::Array(..) => ip.pop_matrix()?, + _ => ip.gs.ctm, + }; + let y = ip.pop_num()?; + let x = ip.pop_num()?; + let (x, y) = f(&m, x, y).ok_or(PsErr::Ps("undefinedresult"))?; + ip.push(Obj::Real(x))?; + ip.push(Obj::Real(y)) +} + +pub fn transform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.apply(x, y))) +} + +pub fn itransform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.inv()?.apply(x, y))) +} + +pub fn dtransform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.delta(x, y))) +} + +pub fn idtransform(ip: &mut Interp) -> R { + xform(ip, |m, x, y| Some(m.inv()?.delta(x, y))) +} + +// ----- paths ----- + +fn add_seg(ip: &mut Interp, s: Seg) -> R { + if ip.gs.path.len() >= MAX_PATH { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + ip.gs.path.push(s); + Ok(()) +} + +pub fn newpath(ip: &mut Interp) -> R { + ip.gs.path.clear(); + ip.gs.cur = None; + ip.gs.start = None; + Ok(()) +} + +fn user_point(ip: &mut Interp) -> R<(f64, f64)> { + let y = ip.pop_num()?; + let x = ip.pop_num()?; + Ok(ip.gs.ctm.apply(x, y)) +} + +fn rel_point(ip: &mut Interp) -> R<(f64, f64)> { + let dy = ip.pop_num()?; + let dx = ip.pop_num()?; + let (cx, cy) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (dx, dy) = ip.gs.ctm.delta(dx, dy); + Ok((cx + dx, cy + dy)) +} + +fn move_dev(ip: &mut Interp, p: (f64, f64)) -> R { + // Consecutive movetos keep only the last. + if let Some(Seg::Move(..)) = ip.gs.path.last() { + ip.gs.path.pop(); + } + add_seg(ip, Seg::Move(p.0, p.1))?; + ip.gs.cur = Some(p); + ip.gs.start = Some(p); + Ok(()) +} + +fn line_dev(ip: &mut Interp, p: (f64, f64)) -> R { + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + if matches!(ip.gs.path.last(), Some(Seg::Close)) + && let Some(s) = ip.gs.start + { + add_seg(ip, Seg::Move(s.0, s.1))?; + } + add_seg(ip, Seg::Line(p.0, p.1))?; + ip.gs.cur = Some(p); + Ok(()) +} + +fn curve_dev(ip: &mut Interp, a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> R { + if ip.gs.cur.is_none() { + return err("nocurrentpoint"); + } + if matches!(ip.gs.path.last(), Some(Seg::Close)) + && let Some(s) = ip.gs.start + { + add_seg(ip, Seg::Move(s.0, s.1))?; + } + add_seg(ip, Seg::Curve(a.0, a.1, b.0, b.1, c.0, c.1))?; + ip.gs.cur = Some(c); + Ok(()) +} + +pub fn moveto(ip: &mut Interp) -> R { + let p = user_point(ip)?; + move_dev(ip, p) +} + +pub fn rmoveto(ip: &mut Interp) -> R { + let p = rel_point(ip)?; + move_dev(ip, p) +} + +pub fn lineto(ip: &mut Interp) -> R { + let p = user_point(ip)?; + line_dev(ip, p) +} + +pub fn rlineto(ip: &mut Interp) -> R { + let p = rel_point(ip)?; + line_dev(ip, p) +} + +pub fn curveto(ip: &mut Interp) -> R { + let c = user_point(ip)?; + let b = user_point(ip)?; + let a = user_point(ip)?; + curve_dev(ip, a, b, c) +} + +pub fn rcurveto(ip: &mut Interp) -> R { + let mut v = [0.0; 6]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + let (cx, cy) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let m = ip.gs.ctm; + let d = |x: f64, y: f64| { + let (dx, dy) = m.delta(x, y); + (cx + dx, cy + dy) + }; + curve_dev(ip, d(v[0], v[1]), d(v[2], v[3]), d(v[4], v[5])) +} + +pub fn closepath(ip: &mut Interp) -> R { + // Keep a Close element for every explicit operator call, as existing EPS consumers do. + // Consecutive closes paint identically, but each one counts toward bounded path storage. + if ip.gs.cur.is_some() { + add_seg(ip, Seg::Close)?; + ip.gs.cur = ip.gs.start; + } + Ok(()) +} + +fn arc_common(ip: &mut Interp, negative: bool) -> R { + let a1 = ip.pop_num()?; + let a0 = ip.pop_num()?; + let r = ip.pop_num()?; + let cy = ip.pop_num()?; + let cx = ip.pop_num()?; + let (sweep, shortened) = bounded_arc_sweep(a0, a1, negative); + if shortened { + ip.warnings.push("arc (too many turns)".into()); + } + let start_angle = a0 % 360.0; + let available = MAX_PATH.saturating_sub(ip.gs.path.len()); + let max_curves = available.saturating_sub(1); + let connector = 1 + usize::from(ip.gs.cur.is_some() && matches!(ip.gs.path.last(), Some(Seg::Close))); + ip.alloc(connector.min(available).saturating_mul(SEG_BYTES))?; + if let Some(curves) = arc_curve_count(r, start_angle, start_angle + sweep, max_curves) { + ip.charge(curves as u64)?; + ip.alloc(curves.saturating_mul(std::mem::size_of::<[f64; 6]>()).saturating_add(curves.saturating_mul(SEG_BYTES)))?; + } + let (start, curves, truncated) = arc_curves(cx, cy, r, start_angle, start_angle + sweep, available.saturating_sub(1)); + let m = ip.gs.ctm; + let s = m.apply(start.0, start.1); + if ip.gs.cur.is_some() { + line_dev(ip, s)? + } else { + move_dev(ip, s)? + } + for c in curves { + curve_dev(ip, m.apply(c[0], c[1]), m.apply(c[2], c[3]), m.apply(c[4], c[5]))?; + } + if truncated { + return Err(PsErr::Fatal("PostScript (path limit)".into())); + } + Ok(()) +} + +pub fn arc(ip: &mut Interp) -> R { + arc_common(ip, false) +} + +pub fn arcn(ip: &mut Interp) -> R { + arc_common(ip, true) +} + +/// `arct` and `arcto`: a line toward (x1, y1), then an arc of radius r tangent to both lines. +fn arct_common(ip: &mut Interp, push_points: bool) -> R { + let r = ip.pop_num()?; + let y2 = ip.pop_num()?; + let x2 = ip.pop_num()?; + let y1 = ip.pop_num()?; + let x1 = ip.pop_num()?; + let inv = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?; + let (dx0, dy0) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (x0, y0) = inv.apply(dx0, dy0); + let (ux, uy) = (x0 - x1, y0 - y1); + let (vx, vy) = (x2 - x1, y2 - y1); + let (lu, lv) = (ux.hypot(uy), vx.hypot(vy)); + let m = ip.gs.ctm; + if lu == 0.0 || lv == 0.0 || r == 0.0 { + line_dev(ip, m.apply(x1, y1))?; + if push_points { + for v in [x1, y1, x1, y1] { + ip.push(Obj::Real(v))?; + } + } + return Ok(()); + } + let cos = ((ux * vx + uy * vy) / (lu * lv)).clamp(-1.0, 1.0); + let theta = cos.acos(); + let t = r / (theta / 2.0).tan(); + if !t.is_finite() { + line_dev(ip, m.apply(x1, y1))?; + return Ok(()); + } + let (t1x, t1y) = (x1 + ux / lu * t, y1 + uy / lu * t); + let (t2x, t2y) = (x1 + vx / lv * t, y1 + vy / lv * t); + line_dev(ip, m.apply(t1x, t1y))?; + // One cubic for the arc between the tangent points. + let sweep = std::f64::consts::PI - theta; + let k = 4.0 / 3.0 * (sweep / 4.0).tan(); + let c1 = (t1x + (x1 - t1x) / t.max(1e-12) * k * r, t1y + (y1 - t1y) / t.max(1e-12) * k * r); + let c2 = (t2x + (x1 - t2x) / t.max(1e-12) * k * r, t2y + (y1 - t2y) / t.max(1e-12) * k * r); + curve_dev(ip, m.apply(c1.0, c1.1), m.apply(c2.0, c2.1), m.apply(t2x, t2y))?; + if push_points { + for v in [t1x, t1y, t2x, t2y] { + ip.push(Obj::Real(v))?; + } + } + Ok(()) +} + +pub fn arct(ip: &mut Interp) -> R { + arct_common(ip, false) +} + +pub fn arcto(ip: &mut Interp) -> R { + arct_common(ip, true) +} + +pub fn currentpoint(ip: &mut Interp) -> R { + let (x, y) = ip.gs.cur.ok_or(PsErr::Ps("nocurrentpoint"))?; + let (x, y) = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?.apply(x, y); + ip.push(Obj::Real(x))?; + ip.push(Obj::Real(y)) +} + +pub fn flattenpath(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len().saturating_mul(16))?; + let tol = ip.gs.flat; + let flat = flatten(&ip.gs.path, tol); + if flat.len() > MAX_PATH { + return err("limitcheck"); + } + ip.gs.path = flat; + Ok(()) +} + +pub fn reversepath(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + // Reverse each subpath. + let mut out = Vec::with_capacity(ip.gs.path.len()); + let mut sub: Vec = Vec::new(); + let flush = |sub: &mut Vec, out: &mut Vec| { + let closed = matches!(sub.last(), Some(Seg::Close)); + let pts: Vec<(f64, f64, Option<[f64; 4]>)> = sub + .iter() + .filter_map(|s| match *s { + Seg::Move(x, y) | Seg::Line(x, y) => Some((x, y, None)), + Seg::Curve(a, b, c, d, e, f) => Some((e, f, Some([a, b, c, d]))), + Seg::Close => None, + }) + .collect(); + if let Some(last) = pts.last() { + out.push(Seg::Move(last.0, last.1)); + for i in (1..pts.len()).rev() { + let (Some(cur), Some(prev)) = (pts.get(i), pts.get(i - 1)) else { continue }; + match cur.2 { + Some([a, b, c, d]) => out.push(Seg::Curve(c, d, a, b, prev.0, prev.1)), + None => out.push(Seg::Line(prev.0, prev.1)), + } + } + if closed { + out.push(Seg::Close); + } + } + sub.clear(); + }; + for s in ip.gs.path.clone() { + if matches!(s, Seg::Move(..)) { + flush(&mut sub, &mut out); + } + sub.push(s); + } + flush(&mut sub, &mut out); + ip.gs.path = out; + Ok(()) +} + +/// `strokepath`: the outline of what `stroke` would paint, as the current path. The pen is +/// shaped in user space (width, caps, joins, miter limit, dashes), as for `stroke`. +pub fn strokepath(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len().saturating_mul(4))?; + use kurbo::{Cap, Join, PathEl, Point, Stroke, StrokeOpts}; + let ctm = ip.gs.ctm; + let Some(inv) = ctm.inv() else { + ip.gs.path.clear(); + return Ok(()); + }; + let p = |x: f64, y: f64| { + let (x, y) = inv.apply(x, y); + Point::new(x, y) + }; + let mut els = Vec::with_capacity(ip.gs.path.len()); + for s in &ip.gs.path { + els.push(match *s { + Seg::Move(x, y) => PathEl::MoveTo(p(x, y)), + Seg::Line(x, y) => PathEl::LineTo(p(x, y)), + Seg::Curve(a, b, c, d, e, f) => PathEl::CurveTo(p(a, b), p(c, d), p(e, f)), + Seg::Close => PathEl::ClosePath, + }); + } + let g = &ip.gs; + let cap = match g.cap { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }; + let join = match g.join { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }; + let mut style = Stroke::new(g.line_width.max(1e-3)).with_caps(cap).with_join(join).with_miter_limit(g.miter.max(1.0)); + let user: Vec = g.path.iter().map(|s| s.map(&inv)).collect(); + if !user.iter().all(|s| match *s { + Seg::Move(x, y) | Seg::Line(x, y) => x.is_finite() && y.is_finite(), + Seg::Curve(a, b, c, d, e, f) => [a, b, c, d, e, f].iter().all(|v| v.is_finite()), + Seg::Close => true, + }) { + ip.gs.path.clear(); + return Ok(()); + } + if crate::read::gstate::dashes_ok(&user, &g.dash.0) && g.dash.1.is_finite() { + style = style.with_dashes(g.dash.1, g.dash.0.clone()); + } + // Tolerance in user space, about a twentieth of a device unit. + let scale = (ctm.0[0] * ctm.0[3] - ctm.0[1] * ctm.0[2]).abs().sqrt().max(1e-9); + let out = kurbo::stroke(els, &style, &StrokeOpts::default(), (0.05 / scale).max(1e-6)); + let mut path = Vec::with_capacity(out.elements().len()); + let mut cur = (0.0, 0.0); + for el in out.elements() { + if path.len() >= MAX_PATH { + return err("limitcheck"); + } + let d = |q: Point| ctm.apply(q.x, q.y); + match *el { + PathEl::MoveTo(q) => { + cur = d(q); + path.push(Seg::Move(cur.0, cur.1)); + } + PathEl::LineTo(q) => { + cur = d(q); + path.push(Seg::Line(cur.0, cur.1)); + } + PathEl::QuadTo(c, q) => { + let (c, e) = (d(c), d(q)); + let a = (cur.0 + 2.0 / 3.0 * (c.0 - cur.0), cur.1 + 2.0 / 3.0 * (c.1 - cur.1)); + let b = (e.0 + 2.0 / 3.0 * (c.0 - e.0), e.1 + 2.0 / 3.0 * (c.1 - e.1)); + path.push(Seg::Curve(a.0, a.1, b.0, b.1, e.0, e.1)); + cur = e; + } + PathEl::CurveTo(a, b, q) => { + let (a, b, e) = (d(a), d(b), d(q)); + path.push(Seg::Curve(a.0, a.1, b.0, b.1, e.0, e.1)); + cur = e; + } + PathEl::ClosePath => path.push(Seg::Close), + } + } + ip.gs.path = path; + ip.gs.cur = Some(cur); + Ok(()) +} + +pub fn pathbbox(ip: &mut Interp) -> R { + ip.charge(ip.gs.path.len() as u64 / 4 + 1)?; + let b = bbox(&ip.gs.path).ok_or(PsErr::Ps("nocurrentpoint"))?; + let inv = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?; + let corners = [inv.apply(b[0], b[1]), inv.apply(b[2], b[1]), inv.apply(b[0], b[3]), inv.apply(b[2], b[3])]; + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for (x, y) in corners { + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x); + y1 = y1.max(y); + } + for v in [x0, y0, x1, y1] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn pathforall(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + let close = ip.pop()?; + let curve = ip.pop()?; + let line = ip.pop()?; + let mv = ip.pop()?; + let inv = ip.gs.ctm.inv().ok_or(PsErr::Ps("undefinedresult"))?; + for s in ip.gs.path.clone() { + let (proc, pts) = match s { + Seg::Move(x, y) => (&mv, vec![inv.apply(x, y)]), + Seg::Line(x, y) => (&line, vec![inv.apply(x, y)]), + Seg::Curve(a, b, c, d, e, f) => (&curve, vec![inv.apply(a, b), inv.apply(c, d), inv.apply(e, f)]), + Seg::Close => (&close, vec![]), + }; + for (x, y) in pts { + ip.push(Obj::Real(x))?; + ip.push(Obj::Real(y))?; + } + ip.call(proc.clone())?; + } + Ok(()) +} + +pub fn rect_path(ip: &mut Interp) -> R> { + let mut rects: Vec<[f64; 4]> = Vec::new(); + match ip.pop()? { + Obj::Array(a, _) => { + ip.charge_path(a.len)?; + let v: Vec = a.items().iter().filter_map(Obj::num).collect(); + for r in v.as_chunks::<4>().0 { + rects.push(*r); + } + } + Obj::Str(_, _) => return err("typecheck"), + h => { + let h = h.num().ok_or(PsErr::Ps("typecheck"))?; + let w = ip.pop_num()?; + let y = ip.pop_num()?; + let x = ip.pop_num()?; + rects.push([x, y, w, h]); + } + } + let m = ip.gs.ctm; + let mut path = Vec::with_capacity(rects.len() * 5); + for [x, y, w, h] in rects { + let p = |a: f64, b: f64| m.apply(a, b); + let (a, b, c, d) = (p(x, y), p(x + w, y), p(x + w, y + h), p(x, y + h)); + path.extend([Seg::Move(a.0, a.1), Seg::Line(b.0, b.1), Seg::Line(c.0, c.1), Seg::Line(d.0, d.1), Seg::Close]); + } + Ok(path) +} + +// ----- painting ----- + +pub fn fill_path(ip: &mut Interp, path: &[Seg], eo: bool) -> R { + ip.charge(path.len() as u64 / 4 + 1)?; + if ip.gs.nulldev { + return Ok(()); + } + if matches!(ip.gs.space, Space::Pattern) && crate::read::ops::shading::fill_pattern(ip, path, eo)? { + return Ok(()); + } + let color = current_color(ip)?; + ip.out.fill(&ip.gs.clip, path, eo, color).map_err(PsErr::Fatal) +} + +pub fn fill(ip: &mut Interp) -> R { + let path = std::mem::take(&mut ip.gs.path); + fill_path(ip, &path, false)?; + newpath(ip) +} + +pub fn eofill(ip: &mut Interp) -> R { + let path = std::mem::take(&mut ip.gs.path); + fill_path(ip, &path, true)?; + newpath(ip) +} + +pub fn stroke_path(ip: &mut Interp, path: &[Seg]) -> R { + ip.charge_path(path.len())?; + if ip.gs.nulldev { + return Ok(()); + } + let color = current_color(ip)?; + let g = &ip.gs; + let p = StrokeParams { width: g.line_width, cap: g.cap, join: g.join, miter: g.miter, dash: &g.dash }; + ip.out.stroke(&g.clip, path, &g.ctm, &p, color).map_err(PsErr::Fatal) +} + +pub fn stroke(ip: &mut Interp) -> R { + let path = std::mem::take(&mut ip.gs.path); + stroke_path(ip, &path)?; + newpath(ip) +} + +pub fn rectfill(ip: &mut Interp) -> R { + let path = rect_path(ip)?; + fill_path(ip, &path, false) +} + +pub fn rectstroke(ip: &mut Interp) -> R { + // An optional matrix operand changes the pen: applied to the CTM for this stroke. + let m = match ip.top(0)? { + Obj::Array(a, _) if a.len == 6 && ip.o.len() >= 2 && !matches!(ip.top(1), Ok(Obj::Array(..)) | Err(_)) => Some(ip.pop_matrix()?), + _ => None, + }; + let path = rect_path(ip)?; + match m { + Some(m) => { + let saved = ip.gs.ctm; + ip.gs.ctm = m.then(&saved); + let r = stroke_path(ip, &path); + ip.gs.ctm = saved; + r + } + None => stroke_path(ip, &path), + } +} + +fn clip_with(ip: &mut Interp, path: Vec, eo: bool) -> R { + let depth = ip.gs.clip.as_ref().map_or(0, |c| c.depth + 1); + if depth > 2000 { + return err("limitcheck"); + } + ip.gs.clip = Some(Rc::new(Clip { path, eo, parent: ip.gs.clip.clone(), depth })); + Ok(()) +} + +pub fn clip(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + let path = ip.gs.path.clone(); + clip_with(ip, path, false) +} + +pub fn eoclip(ip: &mut Interp) -> R { + ip.charge_path(ip.gs.path.len())?; + let path = ip.gs.path.clone(); + clip_with(ip, path, true) +} + +pub fn rectclip(ip: &mut Interp) -> R { + let path = rect_path(ip)?; + clip_with(ip, path, false)?; + newpath(ip) +} + +pub fn clipsave(ip: &mut Interp) -> R { + if ip.gs.clip_saves.len() >= 1000 { + return err("limitcheck"); + } + let c = ip.gs.clip.clone(); + ip.gs.clip_saves.push(c); + Ok(()) +} + +pub fn cliprestore(ip: &mut Interp) -> R { + if let Some(c) = ip.gs.clip_saves.pop() { + ip.gs.clip = c; + } + Ok(()) +} + +pub fn initclip(ip: &mut Interp) -> R { + ip.gs.clip = None; + Ok(()) +} + +pub fn clippath(ip: &mut Interp) -> R { + let n = ip.gs.clip.as_ref().map_or(0, |c| c.path.len()); + ip.charge_path(n)?; + let path = match &ip.gs.clip { + Some(c) => c.path.clone(), + None => { + // The whole page: a generous square. + let s = 1.0e5; + vec![Seg::Move(-s, -s), Seg::Line(s, -s), Seg::Line(s, s), Seg::Line(-s, s), Seg::Close] + } + }; + ip.gs.cur = path.iter().rev().find_map(|s| match s { + Seg::Move(x, y) | Seg::Line(x, y) => Some((*x, *y)), + _ => None, + }); + ip.gs.path = path; + Ok(()) +} + +// ----- colour ----- + +/// A colour space from a name or array operand. +pub fn parse_space(ip: &mut Interp, o: &Obj, depth: usize) -> R { + if depth > 8 { + return err("limitcheck"); + } + let (family, params) = match o { + Obj::Name(n, _) => (n.to_vec(), Vec::new()), + Obj::Array(a, _) => { + let items = a.items(); + match items.first() { + Some(Obj::Name(n, _)) => (n.to_vec(), items.get(1..).map(<[Obj]>::to_vec).unwrap_or_default()), + _ => return err("typecheck"), + } + } + _ => return err("typecheck"), + }; + Ok(match family.as_slice() { + b"DeviceGray" | b"CalGray" | b"G" | b"CIEBasedA" => Space::Gray, + b"DeviceRGB" | b"CalRGB" | b"RGB" | b"CIEBasedABC" | b"CIEBasedDEF" => Space::Rgb, + b"DeviceCMYK" | b"CMYK" | b"CIEBasedDEFG" => Space::Cmyk, + b"Lab" => Space::Lab, + b"Pattern" => Space::Pattern, + b"ICCBased" => { + let n = match params.first() { + Some(Obj::Dict(d)) => d.get_name(b"N").and_then(|o| o.num()).unwrap_or(3.0) as usize, + _ => 3, + }; + match n { + 1 => Space::Gray, + 4 => Space::Cmyk, + _ => Space::Rgb, + } + } + b"Separation" | b"DeviceN" => { + let names = match params.first() { + Some(Obj::Array(a, _)) => a.items().iter().map(crate::read::ops::basic::text_of).collect(), + Some(o) => vec![crate::read::ops::basic::text_of(o)], + None => return err("rangecheck"), + }; + let alt = parse_space(ip, params.get(1).ok_or(PsErr::Ps("rangecheck"))?, depth + 1)?; + let tint = params.get(2).cloned().ok_or(PsErr::Ps("rangecheck"))?; + Space::Tint { names, alt: Box::new(alt), tint } + } + b"Indexed" | b"I" => { + let base = parse_space(ip, params.first().ok_or(PsErr::Ps("rangecheck"))?, depth + 1)?; + let hival = params.get(1).and_then(Obj::num).unwrap_or(0.0).clamp(0.0, 4095.0) as usize; + let n = base.comps(); + let lookup = match params.get(2) { + Some(Obj::Str(s, _)) => s.bytes(), + Some(p @ Obj::Array(_, true)) => { + let mut out = Vec::with_capacity((hival + 1) * n); + for i in 0..=hival { + ip.push(Obj::Int(i as i64))?; + ip.call(p.clone())?; + let mut comps = vec![0.0; n]; + for c in comps.iter_mut().rev() { + *c = ip.pop_num()?; + } + out.extend(comps.iter().map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)); + } + out + } + _ => return err("typecheck"), + }; + Space::Indexed { base: Box::new(base), hival, lookup } + } + _ => return err("undefined"), + }) +} + +/// Evaluate a tint transform (a procedure or a Type 2 function dictionary) on `comps`. +fn eval_tint(ip: &mut Interp, tint: &Obj, comps: &[f64], out_n: usize) -> R> { + match tint { + Obj::Dict(d) => { + // Type 2 exponential: C0 + x^N (C1 − C0). + let get = |k: &[u8], dflt: f64| -> Vec { + match d.get_name(k) { + Some(Obj::Array(a, _)) => a.items().iter().filter_map(Obj::num).collect(), + _ => vec![dflt; out_n], + } + }; + let c0 = get(b"C0", 0.0); + let c1 = get(b"C1", 1.0); + let n = d.get_name(b"N").and_then(|o| o.num()).unwrap_or(1.0); + let x = comps.first().copied().unwrap_or(0.0).clamp(0.0, 1.0).powf(n); + Ok((0..out_n) + .map(|i| c0.get(i).copied().unwrap_or(0.0) + x * (c1.get(i).copied().unwrap_or(1.0) - c0.get(i).copied().unwrap_or(0.0))) + .collect()) + } + _ => { + for c in comps { + ip.push(Obj::Real(*c))?; + } + ip.call(tint.clone())?; + let mut v = vec![0.0; out_n]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + Ok(v) + } + } +} + +pub fn lab_to_rgb(l: f64, a: f64, b: f64) -> (f64, f64, f64) { + let fy = (l + 16.0) / 116.0; + let fx = fy + a / 500.0; + let fz = fy - b / 200.0; + let g = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) }; + let (x, y, z) = (0.9505 * g(fx), g(fy), 1.089 * g(fz)); + let lin = [3.2406 * x - 1.5372 * y - 0.4986 * z, -0.9689 * x + 1.8758 * y + 0.0415 * z, 0.0557 * x - 0.2040 * y + 1.0570 * z]; + let enc = |c: f64| { + let c = c.clamp(0.0, 1.0); + if c <= 0.0031308 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } + }; + (enc(lin[0]), enc(lin[1]), enc(lin[2])) +} + +/// A colour in `space` as a device colour. +pub fn to_device(ip: &mut Interp, space: &Space, comps: &[f64], depth: usize) -> R { + if depth > 8 { + return err("limitcheck"); + } + let c = |i: usize| comps.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0); + Ok(match space { + Space::Gray => DevColor::Gray(c(0)), + Space::Rgb => DevColor::Rgb(c(0), c(1), c(2)), + Space::Cmyk => DevColor::Cmyk(c(0), c(1), c(2), c(3)), + Space::Lab => { + let (r, g, b) = + lab_to_rgb(comps.first().copied().unwrap_or(0.0), comps.get(1).copied().unwrap_or(0.0), comps.get(2).copied().unwrap_or(0.0)); + DevColor::Rgb(r, g, b) + } + Space::Tint { names, alt, tint } => { + // The colourant "None" paints nothing; "All" is registration black. + if names.len() == 1 && names.first().is_some_and(|n| n == b"All") { + return Ok(DevColor::Cmyk(c(0), c(0), c(0), c(0))); + } + let v = eval_tint(ip, &tint.clone(), comps, alt.comps())?; + to_device(ip, &alt.clone(), &v, depth + 1)? + } + Space::Indexed { base, hival, lookup } => { + let i = (comps.first().copied().unwrap_or(0.0).round().max(0.0) as usize).min(*hival); + let n = base.comps(); + let v: Vec = (0..n).map(|k| f64::from(lookup.get(i * n + k).copied().unwrap_or(0)) / 255.0).collect(); + to_device(ip, &base.clone(), &v, depth + 1)? + } + // Patterns aren't painted yet: a mid grey stands in. + Space::Pattern => DevColor::Gray(0.5), + }) +} + +pub fn current_color(ip: &mut Interp) -> R { + let space = ip.gs.space.clone(); + let comps = ip.gs.color.clone(); + to_device(ip, &space, &comps, 0) +} + +fn set_space(ip: &mut Interp, space: Space) { + if ip.gs.color_locked { + return; + } + ip.gs.color = space.initial(); + ip.gs.space = space; + ip.gs.pattern = None; +} + +/// Set the colour values (not inside an uncoloured pattern cell). +fn set_color(ip: &mut Interp, v: Vec) { + if !ip.gs.color_locked { + ip.gs.color = v; + } +} + +pub fn setgray(ip: &mut Interp) -> R { + let g = ip.pop_num()?; + set_space(ip, Space::Gray); + set_color(ip, vec![g]); + Ok(()) +} + +pub fn setrgbcolor(ip: &mut Interp) -> R { + let b = ip.pop_num()?; + let g = ip.pop_num()?; + let r = ip.pop_num()?; + set_space(ip, Space::Rgb); + set_color(ip, vec![r, g, b]); + Ok(()) +} + +pub fn setcmykcolor(ip: &mut Interp) -> R { + let k = ip.pop_num()?; + let y = ip.pop_num()?; + let m = ip.pop_num()?; + let c = ip.pop_num()?; + set_space(ip, Space::Cmyk); + set_color(ip, vec![c, m, y, k]); + Ok(()) +} + +pub fn sethsbcolor(ip: &mut Interp) -> R { + let v = ip.pop_num()?.clamp(0.0, 1.0); + let s = ip.pop_num()?.clamp(0.0, 1.0); + let h = ip.pop_num()?.rem_euclid(1.0) * 6.0; + let i = h.floor(); + let f = h - i; + let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); + let (r, g, b) = match i as i64 { + 0 => (v, t, p), + 1 => (q, v, p), + 2 => (p, v, t), + 3 => (p, q, v), + 4 => (t, p, v), + _ => (v, p, q), + }; + set_space(ip, Space::Rgb); + set_color(ip, vec![r, g, b]); + Ok(()) +} + +pub fn currentgray(ip: &mut Interp) -> R { + let g = match current_color(ip)? { + DevColor::Gray(g) => g, + DevColor::Rgb(r, g, b) => 0.3 * r + 0.59 * g + 0.11 * b, + DevColor::Cmyk(c, m, y, k) => 1.0 - (0.3 * c + 0.59 * m + 0.11 * y + k).min(1.0), + }; + ip.push(Obj::Real(g)) +} + +fn rgb_of(d: DevColor) -> (f64, f64, f64) { + match d { + DevColor::Gray(g) => (g, g, g), + DevColor::Rgb(r, g, b) => (r, g, b), + DevColor::Cmyk(c, m, y, k) => (1.0 - (c + k).min(1.0), 1.0 - (m + k).min(1.0), 1.0 - (y + k).min(1.0)), + } +} + +pub fn currentrgbcolor(ip: &mut Interp) -> R { + let (r, g, b) = rgb_of(current_color(ip)?); + for v in [r, g, b] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn currenthsbcolor(ip: &mut Interp) -> R { + let (r, g, b) = rgb_of(current_color(ip)?); + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let d = max - min; + let h = if d == 0.0 { + 0.0 + } else if max == r { + ((g - b) / d).rem_euclid(6.0) / 6.0 + } else if max == g { + ((b - r) / d + 2.0) / 6.0 + } else { + ((r - g) / d + 4.0) / 6.0 + }; + let s = if max == 0.0 { 0.0 } else { d / max }; + for v in [h, s, max] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn currentcmykcolor(ip: &mut Interp) -> R { + let (c, m, y, k) = match current_color(ip)? { + DevColor::Cmyk(c, m, y, k) => (c, m, y, k), + DevColor::Gray(g) => (0.0, 0.0, 0.0, 1.0 - g), + DevColor::Rgb(r, g, b) => { + let (c, m, y) = (1.0 - r, 1.0 - g, 1.0 - b); + let k = c.min(m).min(y); + (c - k, m - k, y - k, k) + } + }; + for v in [c, m, y, k] { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn setcolorspace(ip: &mut Interp) -> R { + let o = ip.pop()?; + let space = parse_space(ip, &o, 0)?; + let base = match (&space, &o) { + (Space::Pattern, Obj::Array(a, _)) => match a.get(1) { + Some(b) => Some(Box::new(parse_space(ip, &b, 1)?)), + None => None, + }, + _ => None, + }; + set_space(ip, space); + if !ip.gs.color_locked { + ip.gs.pattern_base = base; + } + Ok(()) +} + +pub fn currentcolorspace(ip: &mut Interp) -> R { + let n: &[u8] = match ip.gs.space { + Space::Gray => b"DeviceGray", + Space::Rgb => b"DeviceRGB", + Space::Cmyk => b"DeviceCMYK", + Space::Pattern => b"Pattern", + Space::Lab => b"Lab", + Space::Indexed { .. } => b"Indexed", + Space::Tint { .. } => b"Separation", + }; + ip.push(Obj::Array(PArr::new(vec![Obj::lit(n)]), false)) +} + +pub fn setcolor(ip: &mut Interp) -> R { + if let Space::Pattern = ip.gs.space { + // An uncoloured pattern comes after its colour: `c1 … cn pattern setcolor`. + if let Obj::Dict(d) = ip.pop()? + && !ip.gs.color_locked + { + let uncolored = d.get_name(b"PaintType").and_then(|o| o.num()) == Some(2.0); + let mut under = Vec::new(); + while uncolored && ip.top(0).is_ok_and(|o| o.num().is_some()) && under.len() < 4 { + under.push(ip.pop_num()?); + } + under.reverse(); + ip.gs.color = under; + ip.gs.pattern = Some(d); + } + return Ok(()); + } + let n = ip.gs.space.comps(); + let mut v = vec![0.0; n]; + for slot in v.iter_mut().rev() { + *slot = ip.pop_num()?; + } + set_color(ip, v); + Ok(()) +} + +pub fn currentcolor(ip: &mut Interp) -> R { + for v in ip.gs.color.clone() { + ip.push(Obj::Real(v))?; + } + Ok(()) +} + +pub fn setpattern(ip: &mut Interp) -> R { + let d: PDict = ip.pop_dict()?; + if ip.gs.color_locked { + return Ok(()); + } + // Under an uncoloured pattern, the current colour stays its colour. + let under = ip.gs.color.clone(); + set_space(ip, Space::Pattern); + if d.get_name(b"PaintType").and_then(|o| o.num()) == Some(2.0) { + ip.gs.color = under; + } + ip.gs.pattern = Some(d); + Ok(()) +} + +/// A pattern instance: a copy of the prototype with its pattern space (matrix · CTM). +pub fn makepattern(ip: &mut Interp) -> R { + let m = ip.pop_matrix()?; + let d = ip.pop_dict()?; + let inst = PDict::new(d.len() + 2); + for (k, v) in d.entries() { + inst.put(k, v); + } + inst.put_name(b"CraftPsMatrix", matrix_obj(&m.then(&ip.gs.ctm))); + ip.push(Obj::Dict(inst)) +} diff --git a/crates/ps/src/read/ops/image.rs b/crates/ps/src/read/ops/image.rs new file mode 100644 index 0000000000..a58864d6d3 --- /dev/null +++ b/crates/ps/src/read/ops/image.rs @@ -0,0 +1,374 @@ +//! Sampled images: `image`, `colorimage`, `imagemask`. + +use crate::read::gstate::{DevColor, M, Space}; +use crate::read::interp::{Interp, PsErr, R, err, matrix_of}; +use crate::read::obj::{Obj, PDict}; +use crate::read::ops::gfx; +use crate::read::pdf::{Image, ImgSpace}; + +/// The most samples one image may hold. +const MAX_SAMPLES: usize = 400_000_000; + +/// Where samples come from: a string (reused), a file, or a procedure (called for more). +fn read_source(ip: &mut Interp, src: &Obj, need: usize) -> R<(Vec, bool)> { + let mut out = Vec::new(); + match src { + Obj::Str(s, _) => { + let b = s.bytes(); + if b.is_empty() { + return Ok((vec![0; need], false)); + } + while out.len() < need { + out.extend_from_slice(&b); + } + } + Obj::File(id) => { + if let Some(raw) = ip.srcs.dct(*id) { + return Ok((raw.to_vec(), true)); + } + while out.len() < need { + match ip.srcs.read(*id) { + Some(c) => out.push(c), + None => break, + } + } + // A filter is read to its end, as printers do: its end marker is part of the data. + if ip.srcs.is_filter(*id) { + ip.srcs.drain(*id); + } + } + p @ Obj::Array(_, true) => { + let mut empty_runs = 0; + while out.len() < need { + ip.call(p.clone())?; + let s = ip.pop_str()?; + let b = s.bytes(); + if b.is_empty() { + empty_runs += 1; + if empty_runs > 1 || out.is_empty() { + break; + } + continue; + } + out.extend_from_slice(&b); + } + } + _ => return err("typecheck"), + } + out.resize(need, 0); + Ok((out, false)) +} + +struct Params { + w: usize, + h: usize, + bpc: usize, + matrix: M, + sources: Vec, + decode: Option>, + interpolate: bool, +} + +fn dict_params(ip: &mut Interp, d: &PDict, comps: usize) -> R { + let num = |k: &[u8]| d.get_name(k).and_then(|o| o.num()); + let w = num(b"Width").ok_or(PsErr::Ps("typecheck"))?.max(0.0) as usize; + let h = num(b"Height").ok_or(PsErr::Ps("typecheck"))?.max(0.0) as usize; + let bpc = num(b"BitsPerComponent").unwrap_or(8.0) as usize; + let matrix = match d.get_name(b"ImageMatrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => return err("typecheck"), + }; + let multi = matches!(d.get_name(b"MultipleDataSources"), Some(Obj::Bool(true))); + let sources = match d.get_name(b"DataSource").ok_or(PsErr::Ps("typecheck"))? { + Obj::Array(a, false) if multi => a.items(), + o => vec![o], + }; + if multi && sources.len() < comps { + return err("rangecheck"); + } + let decode = match d.get_name(b"Decode") { + Some(Obj::Array(a, _)) => Some(a.items().iter().filter_map(Obj::num).collect()), + _ => None, + }; + let interpolate = matches!(d.get_name(b"Interpolate"), Some(Obj::Bool(true))); + let _ = ip; + Ok(Params { w, h, bpc, matrix, sources, decode, interpolate }) +} + +/// Read all samples, pixel-interleaved (`comps` per pixel), rows padded to bytes. +fn samples(ip: &mut Interp, p: &Params, comps: usize) -> R<(Vec, bool)> { + let total = p.w.checked_mul(p.h).and_then(|n| n.checked_mul(comps)).ok_or(PsErr::Ps("limitcheck"))?; + if total > MAX_SAMPLES || !matches!(p.bpc, 1 | 2 | 4 | 8 | 12 | 16) { + return err("limitcheck"); + } + ip.alloc(total)?; + ip.charge_bytes(total)?; + if p.sources.len() <= 1 { + let row = (p.w * comps * p.bpc).div_ceil(8); + let src = p.sources.first().cloned().ok_or(PsErr::Ps("typecheck"))?; + return read_source(ip, &src, row * p.h); + } + // One source per component, read in turn (each call or string gives the next piece of its + // component, as Photoshop's row-by-row procedures expect), then interleaved (8-bit only). + if p.bpc != 8 { + return err("limitcheck"); + } + let plane = p.w * p.h; + let mut planes: Vec> = vec![Vec::new(); comps]; + let sources: Vec = p.sources.iter().take(comps).cloned().collect(); + let mut stalled = 0; + while planes.iter().any(|pl| pl.len() < plane) && stalled < 2 { + let mut progress = false; + for (pl, src) in planes.iter_mut().zip(&sources) { + if pl.len() >= plane { + continue; + } + let piece = match src { + p @ Obj::Array(_, true) => { + ip.call(p.clone())?; + ip.pop_str()?.bytes() + } + Obj::Str(s, _) => s.bytes(), + Obj::File(id) => { + let row = p.w.max(1); + let mut v = Vec::with_capacity(row); + while v.len() < row { + match ip.srcs.read(*id) { + Some(c) => v.push(c), + None => break, + } + } + v + } + _ => return err("typecheck"), + }; + progress |= !piece.is_empty(); + pl.extend_from_slice(&piece); + } + stalled = if progress { 0 } else { stalled + 1 }; + } + for pl in &mut planes { + pl.resize(plane, 0); + } + let mut out = Vec::with_capacity(total); + for i in 0..plane { + for pl in &planes { + out.push(pl.get(i).copied().unwrap_or(0)); + } + } + Ok((out, false)) +} + +/// The unit square → page matrix for an image of w × h samples. +fn placement(ip: &Interp, p: &Params) -> R { + let inv = p.matrix.inv().ok_or(PsErr::Ps("undefinedresult"))?; + let s = M([p.w as f64, 0.0, 0.0, -(p.h as f64), 0.0, p.h as f64]); + Ok(s.then(&inv).then(&ip.gs.ctm)) +} + +/// 12- and 16-bit samples as 8-bit. +fn to_8bit(data: Vec, bpc: usize) -> Vec { + match bpc { + 16 => data.chunks(2).map(|c| c.first().copied().unwrap_or(0)).collect(), + 12 => { + let mut out = Vec::with_capacity(data.len() * 2 / 3); + for c in data.chunks(3) { + let (a, b, d) = (c.first().copied().unwrap_or(0), c.get(1).copied().unwrap_or(0), c.get(2).copied().unwrap_or(0)); + out.push(a); + out.push((b << 4) | (d >> 4)); + } + out + } + _ => data, + } +} + +fn paint(ip: &mut Interp, p: Params, space: Space) -> R { + let comps = space.comps(); + let (data, dct) = samples(ip, &p, comps)?; + if ip.limits.skip_images { + ip.warnings.push("image".into()); + return Ok(()); + } + let cm = placement(ip, &p)?; + if ip.gs.nulldev { + return Ok(()); + } + let (data, bpc) = if !dct && matches!(p.bpc, 12 | 16) { (to_8bit(data, p.bpc), 8) } else { (data, p.bpc) }; + let decode = p.decode.map(|d| d.iter().map(|v| *v as f32).collect::>()); + let img_space = match &space { + Space::Gray => Some(ImgSpace::Gray), + Space::Rgb => Some(ImgSpace::Rgb), + Space::Cmyk => Some(ImgSpace::Cmyk), + Space::Indexed { base, hival, lookup } if matches!(**base, Space::Gray | Space::Rgb | Space::Cmyk) => Some(ImgSpace::Indexed { + base: Box::new(match **base { + Space::Rgb => ImgSpace::Rgb, + Space::Cmyk => ImgSpace::Cmyk, + _ => ImgSpace::Gray, + }), + hival: u8::try_from(*hival).unwrap_or(255), + lookup: lookup.clone(), + }), + _ => None, + }; + if let Some(space) = img_space { + let img = + Image { w: p.w as u32, h: p.h as u32, bpc: bpc as u8, space: Some(space), decode, data, dct, interpolate: p.interpolate, smask: None }; + return ip.out.image(&ip.gs.clip, &cm, img, None).map_err(PsErr::Fatal); + } + // Other spaces (Separation, DeviceN, Indexed over them, Lab): convert each pixel, through a + // table of the 256 values when there is one component. + if dct || bpc != 8 { + ip.warnings.push("image in an unsupported colour space skipped".into()); + return Ok(()); + } + // Converting each pixel: work and the converted copy. + ip.charge(data.len() as u64 / 4 + 1)?; + ip.alloc(p.w.saturating_mul(p.h).saturating_mul(4))?; + let mut rgb = Vec::with_capacity(p.w * p.h * 4); + if comps == 1 { + let mut table = Vec::with_capacity(256); + let dmax = match &space { + Space::Indexed { hival, .. } => *hival as f64, + _ => 1.0, + }; + for v in 0..256 { + let x = f64::from(v) / 255.0 * dmax; + table.push(gfx::to_device(ip, &space, &[x], 0)?); + } + let cmyk = table.iter().any(|c| matches!(c, DevColor::Cmyk(..))); + for s in &data { + push_color(&mut rgb, table.get(usize::from(*s)).copied().unwrap_or(DevColor::Gray(0.0)), cmyk); + } + let space = if cmyk { ImgSpace::Cmyk } else { ImgSpace::Rgb }; + let img = Image { + w: p.w as u32, + h: p.h as u32, + bpc: 8, + space: Some(space), + decode: None, + data: rgb, + dct: false, + interpolate: p.interpolate, + smask: None, + }; + return ip.out.image(&ip.gs.clip, &cm, img, None).map_err(PsErr::Fatal); + } + if p.w * p.h > 2_000_000 { + ip.warnings.push("multi-component image in a special colour space too large to convert".into()); + return Ok(()); + } + let mut cache: std::collections::HashMap, DevColor> = std::collections::HashMap::new(); + let mut colors = Vec::with_capacity(p.w * p.h); + for px in data.chunks(comps) { + let c = match cache.get(px) { + Some(c) => *c, + None => { + let v: Vec = px.iter().map(|b| f64::from(*b) / 255.0).collect(); + let c = gfx::to_device(ip, &space, &v, 0)?; + if cache.len() < 65536 { + cache.insert(px.to_vec(), c); + } + c + } + }; + colors.push(c); + } + let cmyk = colors.iter().any(|c| matches!(c, DevColor::Cmyk(..))); + for c in colors { + push_color(&mut rgb, c, cmyk); + } + let space = if cmyk { ImgSpace::Cmyk } else { ImgSpace::Rgb }; + let img = Image { + w: p.w as u32, + h: p.h as u32, + bpc: 8, + space: Some(space), + decode: None, + data: rgb, + dct: false, + interpolate: p.interpolate, + smask: None, + }; + ip.out.image(&ip.gs.clip, &cm, img, None).map_err(PsErr::Fatal) +} + +fn push_color(out: &mut Vec, c: DevColor, cmyk: bool) { + let b = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + match (c, cmyk) { + (DevColor::Cmyk(c, m, y, k), true) => out.extend([b(c), b(m), b(y), b(k)]), + (DevColor::Gray(g), true) => out.extend([0, 0, 0, b(1.0 - g)]), + (DevColor::Rgb(r, g, bl), true) => out.extend([b(1.0 - r), b(1.0 - g), b(1.0 - bl), 0]), + (DevColor::Gray(g), false) => out.extend([b(g); 3]), + (DevColor::Rgb(r, g, bl), false) => out.extend([b(r), b(g), b(bl)]), + (DevColor::Cmyk(c, m, y, k), false) => out.extend([b(1.0 - (c + k).min(1.0)), b(1.0 - (m + k).min(1.0)), b(1.0 - (y + k).min(1.0))]), + } +} + +pub fn image(ip: &mut Interp) -> R { + if let Obj::Dict(d) = ip.top(0)?.clone() { + ip.pop()?; + let space = ip.gs.space.clone(); + let p = dict_params(ip, &d, space.comps())?; + return paint(ip, p, space); + } + let src = ip.pop()?; + let matrix = ip.pop_matrix()?; + let bpc = ip.pop_usize()?; + let h = ip.pop_usize()?; + let w = ip.pop_usize()?; + paint(ip, Params { w, h, bpc, matrix, sources: vec![src], decode: None, interpolate: false }, Space::Gray) +} + +pub fn colorimage(ip: &mut Interp) -> R { + let ncomp = ip.pop_usize()?; + let multi = ip.pop_bool()?; + let space = match ncomp { + 1 => Space::Gray, + 3 => Space::Rgb, + 4 => Space::Cmyk, + _ => return err("rangecheck"), + }; + let mut sources = Vec::new(); + for _ in 0..if multi { ncomp } else { 1 } { + sources.push(ip.pop()?); + } + sources.reverse(); + let matrix = ip.pop_matrix()?; + let bpc = ip.pop_usize()?; + let h = ip.pop_usize()?; + let w = ip.pop_usize()?; + paint(ip, Params { w, h, bpc, matrix, sources, decode: None, interpolate: false }, space) +} + +pub fn imagemask(ip: &mut Interp) -> R { + let (p, polarity) = if let Obj::Dict(d) = ip.top(0)?.clone() { + ip.pop()?; + let mut p = dict_params(ip, &d, 1)?; + let inverted = p.decode.as_ref().and_then(|d| d.first()).is_some_and(|v| *v > 0.5); + p.decode = None; + (p, inverted) + } else { + let src = ip.pop()?; + let matrix = ip.pop_matrix()?; + let polarity = ip.pop_bool()?; + let h = ip.pop_usize()?; + let w = ip.pop_usize()?; + (Params { w, h, bpc: 1, matrix, sources: vec![src], decode: None, interpolate: false }, polarity) + }; + let p = Params { bpc: 1, ..p }; + let (data, _) = samples(ip, &p, 1)?; + if ip.limits.skip_images { + ip.warnings.push("image".into()); + return Ok(()); + } + let cm = placement(ip, &p)?; + if ip.gs.nulldev { + return Ok(()); + } + let color = gfx::current_color(ip)?; + // PDF stencil masks paint 0 bits; polarity true paints the 1 bits. + let decode = if polarity { Some(vec![1.0, 0.0]) } else { None }; + let img = Image { w: p.w as u32, h: p.h as u32, bpc: 1, space: None, decode, data, dct: false, interpolate: false, smask: None }; + ip.out.image(&ip.gs.clip, &cm, img, Some(color)).map_err(PsErr::Fatal) +} diff --git a/crates/ps/src/read/ops/mesh.rs b/crates/ps/src/read/ops/mesh.rs new file mode 100644 index 0000000000..01a499b869 --- /dev/null +++ b/crates/ps/src/read/ops/mesh.rs @@ -0,0 +1,262 @@ +//! Mesh shadings (types 4–7): free-form and lattice triangles, Coons and tensor patches, read +//! from an array, a string or a file, their colours made device colours, and written to the PDF +//! as meshes again (each triangle and patch whole, so shared edges need no state there). + +use crate::read::gstate::{DevColor, Space}; +use crate::read::interp::{Interp, R, err}; +use crate::read::obj::{Obj, PDict}; +use crate::read::ops::gfx; +use crate::read::ops::shading::{Func, eval, pack}; +use crate::read::pdf::{ShadeKind, Shading}; + +/// A patch's control points and corner colours (the next patch may share an edge of it). +type Patch = (Vec<(f64, f64)>, Vec); + +/// The most vertices or patches read from one shading. +const MAX_ELEMENTS: usize = 2_000_000; + +/// The numbers of a mesh: from an array as they are, or unpacked from bits with Decode. +struct Reader { + nums: Vec, + bits: Option<(Vec, usize)>, + pos: usize, + bpc: usize, + bpcomp: usize, + bpflag: usize, + decode: Vec, +} + +impl Reader { + fn raw(&mut self, n: usize) -> Option { + let (data, bit) = self.bits.as_mut()?; + let mut v = 0u64; + for _ in 0..n { + let byte = *data.get(*bit / 8)?; + v = v << 1 | u64::from(byte >> (7 - *bit % 8) & 1); + *bit += 1; + } + Some(v) + } + + fn align(&mut self) { + if let Some((_, bit)) = self.bits.as_mut() { + *bit = bit.div_ceil(8) * 8; + } + } + + fn array_next(&mut self) -> Option { + let v = self.nums.get(self.pos).copied(); + self.pos += 1; + v + } + + fn decoded(&mut self, bits: usize, range: usize) -> Option { + if self.bits.is_none() { + return self.array_next(); + } + let v = self.raw(bits)?; + let max = ((1u128 << bits) - 1) as f64; + let (d0, d1) = (self.decode.get(2 * range).copied().unwrap_or(0.0), self.decode.get(2 * range + 1).copied().unwrap_or(1.0)); + Some(d0 + v as f64 / max * (d1 - d0)) + } + + fn flag(&mut self) -> Option { + if self.bits.is_none() { + return self.array_next().map(|v| v as u8); + } + self.raw(self.bpflag).map(|v| v as u8) + } + + fn point(&mut self) -> Option<(f64, f64)> { + let b = self.bpc; + Some((self.decoded(b, 0)?, self.decoded(b, 1)?)) + } + + fn color(&mut self, n: usize) -> Option> { + let b = self.bpcomp; + (0..n).map(|i| self.decoded(b, 2 + i)).collect() + } +} + +#[allow(clippy::cognitive_complexity, reason = "one stateful reader handles the PostScript mesh record layouts")] +pub fn build(ip: &mut Interp, d: &PDict, kind: i64, space: &Space, func: Option<&Func>) -> R> { + let num = |k: &[u8]| d.get_name(k).and_then(|o| o.num()).unwrap_or(0.0); + let ncomp = if func.is_some() { 1 } else { space.comps() }; + let decode: Vec = match d.get_name(b"Decode") { + Some(Obj::Array(a, _)) => a.items().iter().filter_map(Obj::num).collect(), + _ => Vec::new(), + }; + let mut r = Reader { + nums: Vec::new(), + bits: None, + pos: 0, + bpc: num(b"BitsPerCoordinate").clamp(1.0, 32.0) as usize, + bpcomp: num(b"BitsPerComponent").clamp(1.0, 16.0) as usize, + bpflag: num(b"BitsPerFlag").clamp(2.0, 8.0) as usize, + decode, + }; + match d.get_name(b"DataSource") { + Some(Obj::Array(a, _)) => r.nums = a.items().iter().filter_map(Obj::num).collect(), + Some(Obj::Str(s, _)) => r.bits = Some((s.bytes(), 0)), + Some(Obj::File(id)) => { + let mut v = Vec::new(); + while let Some(c) = ip.srcs.read(id) { + v.push(c); + if v.len() > 64 << 20 { + break; + } + } + r.bits = Some((v, 0)); + } + _ => return err("typecheck"), + } + let to_dev = |ip: &mut Interp, c: &[f64]| -> R { + let comps = match func { + Some(f) => eval(ip, f, c, 0)?, + None => c.to_vec(), + }; + gfx::to_device(ip, space, &comps, 0) + }; + let mut points: Vec<(f64, f64)> = Vec::new(); + let mut colors: Vec = Vec::new(); + let shade = match kind { + 4 | 5 => { + // Vertices, then triangles of them. + let mut verts: Vec<((f64, f64), DevColor)> = Vec::new(); + let mut tris: Vec<[usize; 3]> = Vec::new(); + let per_row = num(b"VerticesPerRow").max(2.0) as usize; + let mut pending: Vec = Vec::new(); + while verts.len() < MAX_ELEMENTS { + ip.charge(1)?; + let flag = if kind == 4 { + match r.flag() { + Some(f) => f, + None => break, + } + } else { + 0 + }; + let (Some(p), Some(c)) = (r.point(), r.color(ncomp)) else { break }; + if kind == 4 && r.bits.is_some() { + r.align(); + } + let c = to_dev(ip, &c)?; + verts.push((p, c)); + let n = verts.len() - 1; + if kind != 4 { + continue; + } + // Flag 0 starts a triangle of three new vertices; 1 and 2 continue from the + // last triangle's (b, c) or (a, c) edge. + match (flag, tris.last().copied()) { + (1, Some([_, b, c])) => tris.push([b, c, n]), + (2, Some([a, _, c])) => tris.push([a, c, n]), + _ => { + pending.push(n); + if pending.len() == 3 { + tris.push([pending[0], pending[1], pending[2]]); + pending.clear(); + } + } + } + } + if kind == 5 { + let rows = verts.len() / per_row; + for row in 0..rows.saturating_sub(1) { + for i in 0..per_row - 1 { + let a = row * per_row + i; + let (b, c, e) = (a + 1, a + per_row, a + per_row + 1); + tris.push([a, b, c]); + tris.push([b, e, c]); + } + } + } + for t in tris { + for i in t { + let Some((p, c)) = verts.get(i) else { return err("rangecheck") }; + points.push(*p); + colors.push(*c); + } + } + ShadeKind::Triangles + } + _ => { + // Coons (12 control points) and tensor (16) patches; flags 1–3 share an edge. + let npts = if kind == 6 { 12 } else { 16 }; + let mut prev: Option = None; + let mut count = 0; + loop { + if count >= MAX_ELEMENTS { + break; + } + ip.charge(4)?; + let Some(flag) = r.flag() else { break }; + let (shared_pts, shared_cols) = match (flag, &prev) { + (1..=3, Some((pp, pc))) => { + // The edge of the previous patch this one starts from (per the patch order). + let (pi, ci): (&[usize], [usize; 2]) = match flag { + 1 => (&[3, 4, 5, 6], [1, 2]), + 2 => (&[6, 7, 8, 9], [2, 3]), + _ => (&[9, 10, 11, 0], [3, 0]), + }; + ( + pi.iter().filter_map(|i| pp.get(*i).copied()).collect::>(), + ci.iter().filter_map(|i| pc.get(*i).copied()).collect::>(), + ) + } + _ => (Vec::new(), Vec::new()), + }; + let new_pts = if shared_pts.len() == 4 { npts - 4 } else { npts }; + let new_cols = if shared_cols.len() == 2 { 2 } else { 4 }; + let mut pts = shared_pts.clone(); + if pts.len() != 4 { + pts.clear(); + } + let mut ok = true; + for _ in 0..new_pts { + match r.point() { + Some(p) => pts.push(p), + None => { + ok = false; + break; + } + } + } + let mut cols = if shared_cols.len() == 2 { shared_cols } else { Vec::new() }; + for _ in 0..new_cols { + match r.color(ncomp) { + Some(c) => cols.push(to_dev(ip, &c)?), + None => { + ok = false; + break; + } + } + } + if r.bits.is_some() { + r.align(); + } + if !ok || pts.len() != npts || cols.len() != 4 { + break; + } + points.extend(&pts); + colors.extend(&cols); + prev = Some((pts, cols)); + count += 1; + } + if kind == 6 { ShadeKind::Coons } else { ShadeKind::Tensor } + } + }; + if points.is_empty() { + return Ok(None); + } + let bbox = match d.get_name(b"BBox") { + Some(Obj::Array(a, _)) => { + let v: Vec = a.items().iter().filter_map(Obj::num).collect(); + <[f64; 4]>::try_from(v).ok() + } + _ => None, + }; + let (space, data) = pack(&colors); + let n = colors.len(); + Ok(Some(Shading { kind: shade, extend: [false, false], space, data, samples: n, bbox, points })) +} diff --git a/crates/ps/src/read/ops/misc.rs b/crates/ps/src/read/ops/misc.rs new file mode 100644 index 0000000000..03f7ece9b8 --- /dev/null +++ b/crates/ps/src/read/ops/misc.rs @@ -0,0 +1,789 @@ +//! Files, filters, resources, forms, output, and device parameters EPS programs query or set. + +use crate::read::interp::{Interp, PsErr, R, err, matrix_of}; +use crate::read::obj::{Key, Obj, PArr, PDict, name}; +use crate::read::source::{FilterParams, Kind, Source}; + +// ----- files ----- + +pub fn currentfile(ip: &mut Interp) -> R { + let id = + ip.e.iter() + .rev() + .find_map(|f| match f { + crate::read::interp::Frame::File { id } => Some(*id), + _ => None, + }) + .unwrap_or(ip.main); + ip.push(Obj::File(id)) +} + +fn pop_file(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::File(id) => Ok(id), + _ => err("typecheck"), + } +} + +pub fn read(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + match ip.srcs.read(f) { + Some(c) => { + ip.push(Obj::Int(i64::from(c)))?; + ip.push(Obj::Bool(true)) + } + None => ip.push(Obj::Bool(false)), + } +} + +pub fn readstring(ip: &mut Interp) -> R { + let s = ip.pop_str()?; + let f = pop_file(ip)?; + let mut n = 0; + while n < s.len { + match ip.srcs.read(f) { + Some(c) => { + s.set(n, c); + n += 1; + } + None => break, + } + } + let full = n == s.len; + let sub = s.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(sub, false))?; + ip.push(Obj::Bool(full)) +} + +pub fn readhexstring(ip: &mut Interp) -> R { + let s = ip.pop_str()?; + let f = pop_file(ip)?; + let mut n = 0; + let mut hi: Option = None; + while n < s.len { + let Some(c) = ip.srcs.read(f) else { break }; + let v = match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + b'A'..=b'F' => c - b'A' + 10, + _ => continue, + }; + match hi.take() { + Some(h) => { + s.set(n, h << 4 | v); + n += 1; + } + None => hi = Some(v), + } + } + let full = n == s.len; + let sub = s.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(sub, false))?; + ip.push(Obj::Bool(full)) +} + +pub fn readline(ip: &mut Interp) -> R { + let s = ip.pop_str()?; + let f = pop_file(ip)?; + let mut n = 0; + let mut eol = false; + while let Some(c) = ip.srcs.read(f) { + if c == b'\n' { + eol = true; + break; + } + if c == b'\r' { + if ip.srcs.peek(f) == Some(b'\n') { + ip.srcs.read(f); + } + eol = true; + break; + } + if n >= s.len { + return err("rangecheck"); + } + s.set(n, c); + n += 1; + } + let sub = s.interval(0, n).ok_or(PsErr::Ps("rangecheck"))?; + ip.push(Obj::Str(sub, false))?; + ip.push(Obj::Bool(eol || n > 0)) +} + +pub fn bytesavailable(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + let n = ip.srcs.available(f); + ip.push(Obj::Int(n)) +} + +pub fn closefile(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + let is_eexec = matches!(ip.srcs.list.get(f).map(|source| &source.kind), Some(Kind::Eexec { .. })); + ip.srcs.close(f); + if is_eexec + && let Some(font) = ip.d.iter().rev().find(|dict| dict.get_name(b"FontName").is_some()).cloned() + && let Some(name) = font.get_name(b"FontName") + { + // Some embedded programs leave `/CharStrings dict` on the operand stack instead of + // installing it with `ND` before closing eexec. Attach that completed table to its font. + if font.get_name(b"CharStrings").is_none() { + ip.charge(ip.o.len() as u64)?; + if let Some(chars) = ip.o.windows(2).rev().find_map(|pair| match pair { + [Obj::Name(key, _), Obj::Dict(chars)] if key.as_ref() == b"CharStrings" => Some(chars.clone()), + _ => None, + }) { + font.put_name(b"CharStrings", Obj::Dict(chars)); + } + } + // Embedded Type 1 programs conventionally leave their completed font dictionary in + // the current dictionary stack; closefile marks the end of eexec, so make it findable. + crate::read::font::add_fid(ip, &font); + ip.fontdir.put(name, Obj::Dict(font)); + } + Ok(()) +} + +pub fn resetfile(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + ip.srcs.reset(f); + Ok(()) +} + +pub fn fileposition(ip: &mut Interp) -> R { + let f = pop_file(ip)?; + let p = ip.srcs.position(f).ok_or(PsErr::Ps("ioerror"))?; + ip.push(Obj::Int(i64::try_from(p).unwrap_or(i64::MAX))) +} + +pub fn setfileposition(ip: &mut Interp) -> R { + let p = ip.pop_usize()?; + let f = pop_file(ip)?; + if ip.srcs.set_position(f, p) { Ok(()) } else { err("ioerror") } +} + +pub fn flushfile(ip: &mut Interp) -> R { + // On an input file: read and discard to its end. + let f = pop_file(ip)?; + if f != ip.main { + while ip.srcs.read(f).is_some() {} + } + Ok(()) +} + +pub fn status(ip: &mut Interp) -> R { + match ip.pop()? { + Obj::File(f) => { + let open = ip.srcs.available(f) >= 0; + ip.push(Obj::Bool(open)) + } + _ => ip.push(Obj::Bool(false)), + } +} + +pub fn file(ip: &mut Interp) -> R { + let _access = ip.pop()?; + let fname = ip.pop_name()?; + match fname.as_slice() { + b"%stdin" => ip.push(Obj::File(ip.main)), + // Output files swallow what is written. + b"%stdout" | b"%stderr" | b"%lineedit" | b"%statementedit" => { + let id = ip.add_source(Source::bytes(Vec::new()))?; + ip.push(Obj::File(id)) + } + // An EPS can't reach the disk. + _ => err("invalidfileaccess"), + } +} + +pub fn write_ops(ip: &mut Interp) -> R { + // `file int write`, `file string writestring`: discarded. + ip.pop()?; + ip.pop()?; + Ok(()) +} + +pub fn eexec(ip: &mut Interp) -> R { + let up = match ip.pop()? { + Obj::File(id) => id, + Obj::Str(s, _) => { + ip.alloc(s.len)?; + ip.add_source(Source::bytes(s.bytes()))? + } + _ => return err("typecheck"), + }; + let id = ip.add_source(Source::eexec(up))?; + // A number of embedded Type 1 programs omit the usual `currentdict end` before eexec; + // their encrypted prolog starts with `dup /Private ...` and expects its font dictionary. + // Supply it only when the caller has not already left an operand on the stack. + let font_prolog = ip.d.last().is_some_and(|font| { + font.get_name(b"FontName").is_some() + && font.get_name(b"FontType").and_then(|value| value.num()) == Some(1.0) + && font.get_name(b"FontMatrix").is_some() + }); + if ip.o.is_empty() + && font_prolog + && let Some(font) = ip.d.last() + { + ip.push(Obj::Dict(font.clone()))?; + } + // eexec runs with systemdict on top, which its program removes with `end` (`closefile`). + let sd = ip.systemdict.clone(); + ip.begin(sd)?; + ip.push_frame(crate::read::interp::Frame::File { id }) +} + +/// `src [params] /Name filter`, with SubFileDecode's own `count string` operands. +pub fn filter(ip: &mut Interp) -> R { + let fname = ip.pop_name()?; + let mut params = FilterParams { early_change: true, ..Default::default() }; + if fname == b"SubFileDecode" { + let eod = ip.pop()?; + params.eod_string = match eod { + Obj::Str(s, _) => s.bytes(), + _ => return err("typecheck"), + }; + params.eod_count = ip.pop_usize()?; + if let Ok(Obj::Dict(_)) = ip.top(0) { + ip.pop()?; + } + } else if let Ok(Obj::Dict(d)) = ip.top(0).cloned() { + // A dictionary operand is parameters unless it is the data source itself (never: a + // dictionary can't be a source). + ip.pop()?; + let num = |k: &[u8]| d.get_name(k).and_then(|o| o.num()); + params.early_change = num(b"EarlyChange").is_none_or(|v| v != 0.0); + params.predictor = num(b"Predictor").unwrap_or(1.0) as i64; + params.colors = num(b"Colors").unwrap_or(1.0) as i64; + params.bpc = num(b"BitsPerComponent").unwrap_or(8.0) as i64; + params.columns = num(b"Columns").unwrap_or(1.0) as i64; + } + let src = ip.pop()?; + let up = match src { + Obj::File(id) => id, + Obj::Str(s, _) => { + ip.alloc(s.len)?; + ip.add_source(Source::bytes(s.bytes()))? + } + p @ Obj::Array(_, true) => { + // A procedure source: call it until it gives an empty string. + let mut data = Vec::new(); + for _ in 0..1_000_000 { + ip.call(p.clone())?; + let s = ip.pop_str()?.bytes(); + if s.is_empty() { + break; + } + data.extend_from_slice(&s); + ip.alloc(s.len())?; + } + ip.add_source(Source::bytes(data))? + } + _ => return err("typecheck"), + }; + if fname.ends_with(b"Encode") && fname != b"NullEncode" { + // Encoding filters write; an EPS has nowhere to write to. + let id = ip.add_source(Source::bytes(Vec::new()))?; + return ip.push(Obj::File(id)); + } + // Reserve the retained source record before constructing any filter-owned buffers. The + // filter separately checks its predictor/reusable-stream storage against the remaining cap. + ip.alloc(crate::read::interp::SOURCE_BYTES)?; + let max_owned = ip.limits.memory.saturating_sub(ip.memory); + match ip.srcs.filter(up, &fname, ¶ms, max_owned) { + Ok((source, owned_bytes)) => { + ip.alloc(owned_bytes)?; + let id = ip.srcs.add(source); + ip.push(Obj::File(id)) + } + Err(e) => { + ip.warnings.push(e); + err("ioerror") + } + } +} + +// ----- output ----- + +pub fn pop1(ip: &mut Interp) -> R { + ip.pop().map(|_| ()) +} + +pub fn noop(_ip: &mut Interp) -> R { + Ok(()) +} + +pub fn showpage(_ip: &mut Interp) -> R { + Ok(()) +} + +// ----- environment ----- + +pub fn languagelevel(ip: &mut Interp) -> R { + ip.push(Obj::Int(3)) +} + +pub fn version(ip: &mut Interp) -> R { + ip.push(Obj::str(b"3010")) +} + +pub fn product(ip: &mut Interp) -> R { + ip.push(Obj::str(b"craft-ps")) +} + +pub fn revision(ip: &mut Interp) -> R { + ip.push(Obj::Int(1)) +} + +pub fn zero(ip: &mut Interp) -> R { + ip.push(Obj::Int(0)) +} + +pub fn vmstatus(ip: &mut Interp) -> R { + let used = i64::try_from(ip.memory).unwrap_or(i64::MAX); + ip.push(Obj::Int(i64::try_from(ip.saves.len()).unwrap_or(0)))?; + ip.push(Obj::Int(used))?; + ip.push(Obj::Int(1 << 30)) +} + +pub fn push_false(ip: &mut Interp) -> R { + ip.push(Obj::Bool(false)) +} + +pub fn empty_dict(ip: &mut Interp) -> R { + ip.push(Obj::Dict(PDict::new(4))) +} + +pub fn pop_dict(ip: &mut Interp) -> R { + ip.pop_dict().map(|_| ()) +} + +/// The system and user parameters programs read (all limits generous). +pub fn currentsystemparams(ip: &mut Interp) -> R { + let d = PDict::new(24); + for k in [ + "MaxPatternCache", + "MaxFontCache", + "MaxFormCache", + "MaxScreenStorage", + "MaxDisplayList", + "MaxOutlineCache", + "MaxUPathCache", + "MaxStoredScreenCache", + "MaxSourceList", + "MaxDisplayAndSourceList", + "MaxImageBuffer", + "MaxRasterMemory", + "MaxStackSize", + "CurFontCache", + "CurFormCache", + "CurPatternCache", + "CurOutlineCache", + "CurUPathCache", + "CurScreenStorage", + "CurDisplayList", + "CurSourceList", + "CurStoredScreenCache", + "CurInputDevice", + "CurOutputDevice", + ] { + let v = if k.starts_with("Cur") { 0 } else { 8 << 20 }; + d.put_name(k.as_bytes(), Obj::Int(v)); + } + d.put_name(b"ByteOrder", Obj::Bool(false)); + d.put_name(b"RealFormat", Obj::str(b"IEEE")); + d.put_name(b"BuildTime", Obj::Int(0)); + ip.push(Obj::Dict(d)) +} + +pub fn currentuserparams(ip: &mut Interp) -> R { + let d = PDict::new(20); + for (k, v) in [ + ("MaxPatternItem", 20_000), + ("MaxFormItem", 100_000), + ("MaxFontItem", 12_500), + ("MaxUPathItem", 0), + ("MaxLocalVM", 1 << 30), + ("MaxGlobalVM", 1 << 30), + ("VMReclaim", 0), + ("VMThreshold", 1 << 20), + ("MaxDictStack", 1000), + ("MaxExecStack", 100_000), + ("MaxOpStack", 500_000), + ("MinFontCompress", 100), + ("MaxSuperScreen", 1016), + ("MaxLocalVM", 1 << 30), + ("JobTimeout", 0), + ("WaitTimeout", 0), + ] { + d.put_name(k.as_bytes(), Obj::Int(v)); + } + d.put_name(b"AccurateScreens", Obj::Bool(false)); + d.put_name(b"HalftoneMode", Obj::Int(0)); + d.put_name(b"IdiomRecognition", Obj::Bool(false)); + ip.push(Obj::Dict(d)) +} + +pub fn currentpagedevice(ip: &mut Interp) -> R { + let d = PDict::new(8); + d.put_name(b"PageSize", Obj::Array(PArr::new(vec![Obj::Int(612), Obj::Int(792)]), false)); + d.put_name(b"HWResolution", Obj::Array(PArr::new(vec![Obj::Int(72), Obj::Int(72)]), false)); + d.put_name(b"Policies", Obj::Dict(PDict::new(2))); + d.put_name(b"ProcessColorModel", Obj::lit(b"DeviceCMYK")); + d.put_name(b"Separations", Obj::Bool(false)); + ip.push(Obj::Dict(d)) +} + +pub fn currentscreen(ip: &mut Interp) -> R { + ip.push(Obj::Real(60.0))?; + ip.push(Obj::Real(45.0))?; + ip.push(Obj::proc(vec![Obj::Op(crate::read::ops::op_id(b"pop").unwrap_or(0)), Obj::Real(0.0)])) +} + +pub fn setscreen(ip: &mut Interp) -> R { + for _ in 0..3 { + ip.pop()?; + } + Ok(()) +} + +pub fn setcolorscreen(ip: &mut Interp) -> R { + for _ in 0..12 { + ip.pop()?; + } + Ok(()) +} + +pub fn currentcolorscreen(ip: &mut Interp) -> R { + for _ in 0..4 { + currentscreen(ip)?; + } + Ok(()) +} + +pub fn empty_proc(ip: &mut Interp) -> R { + ip.push(Obj::proc(Vec::new())) +} + +pub fn currentcolortransfer(ip: &mut Interp) -> R { + for _ in 0..4 { + empty_proc(ip)?; + } + Ok(()) +} + +pub fn setcolortransfer(ip: &mut Interp) -> R { + for _ in 0..4 { + ip.pop()?; + } + Ok(()) +} + +pub fn findcolorrendering(ip: &mut Interp) -> R { + let n = ip.pop()?; + ip.push(n)?; + ip.push(Obj::Bool(true)) +} + +pub fn realtime(ip: &mut Interp) -> R { + ip.push(Obj::Int(0)) +} + +pub fn internaldict(ip: &mut Interp) -> R { + ip.pop_int()?; + let d = match ip.systemdict.get_name(b"CraftPsInternal") { + Some(Obj::Dict(d)) => d, + _ => { + let d = PDict::new(10); + ip.systemdict.put_name(b"CraftPsInternal", Obj::Dict(d.clone())); + d + } + }; + ip.push(Obj::Dict(d)) +} + +pub fn setglobal(ip: &mut Interp) -> R { + ip.pop_bool().map(|_| ()) +} + +pub fn print_any(ip: &mut Interp) -> R { + ip.pop().map(|_| ()) +} + +pub fn pstack(_ip: &mut Interp) -> R { + Ok(()) +} + +pub fn nulldevice(ip: &mut Interp) -> R { + ip.gs.nulldev = true; + Ok(()) +} + +pub fn execform(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + let m = match d.get_name(b"Matrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => crate::read::gstate::M::ID, + }; + let paint = d.get_name(b"PaintProc").ok_or(PsErr::Ps("undefined"))?; + ip.gsave()?; + ip.gs.ctm = m.then(&ip.gs.ctm); + let r = (|| { + if let Some(Obj::Array(bb, _)) = d.get_name(b"BBox") { + ip.push(Obj::Array(bb, false))?; + crate::read::ops::gfx::rectclip(ip)?; + } + ip.push(Obj::Dict(d.clone()))?; + ip.call(paint) + })(); + ip.grestore(); + r +} + +// ----- resources ----- + +fn category(ip: &mut Interp, cat: &[u8]) -> PDict { + match ip.resources.get_name(cat) { + Some(Obj::Dict(d)) => d, + _ => { + let d = PDict::new(20); + ip.resources.put_name(cat, Obj::Dict(d.clone())); + d + } + } +} + +pub fn findresource(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let key = ip.pop()?; + if cat == b"Font" { + let f = crate::read::font::find_font(ip, &key)?; + return ip.push(Obj::Dict(f)); + } + if cat == b"Category" { + let d = category(ip, &crate::read::ops::basic::text_of(&key)); + return ip.push(Obj::Dict(d)); + } + let d = category(ip, &cat); + if let Some(v) = d.get(&key.key()) { + return ip.push(v); + } + if cat == b"Encoding" + && let Some(e) = ip.systemdict.get(&key.key()) + { + return ip.push(e); + } + if cat == b"ColorSpace" || cat == b"ColorRendering" || cat == b"Halftone" { + return ip.push(Obj::Dict(PDict::new(1))); + } + ip.dollar_error.put_name(b"command", Obj::lit(b"findresource")); + err("undefinedresource") +} + +pub fn defineresource(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let v = ip.pop()?; + let key = ip.pop()?; + if cat == b"CIDFont" + && let Obj::Dict(d) = &v + && !d.known(&Key::Name(name(b"FID"))) + { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } + if cat == b"Font" + && let Obj::Dict(d) = &v + { + if !d.known(&Key::Name(name(b"FID"))) { + d.put_name(b"FID", Obj::FontId(ip.next_fid)); + ip.next_fid += 1; + } + ip.fontdir.put(key.clone(), v.clone()); + } + category(ip, &cat).put(key, v.clone()); + ip.push(v) +} + +pub fn undefineresource(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let key = ip.pop()?; + category(ip, &cat).remove(&key.key()); + Ok(()) +} + +pub fn resourcestatus(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let key = ip.pop()?; + let known = category(ip, &cat).known(&key.key()) || (cat == b"Font" && ip.fontdir.known(&key.key())); + if known { + ip.push(Obj::Int(1))?; + ip.push(Obj::Int(0))?; + ip.push(Obj::Bool(true)) + } else { + ip.push(Obj::Bool(false)) + } +} + +pub fn resourceforall(ip: &mut Interp) -> R { + let cat = ip.pop_name()?; + let scratch = ip.pop_str()?; + let proc = ip.pop()?; + let _template = ip.pop()?; + let entries = category(ip, &cat).entries(); + ip.charge(entries.len() as u64)?; + ip.alloc(entries.len().saturating_mul(2 * crate::read::ops::basic::OBJ_BYTES))?; + for (k, _) in entries { + let t = crate::read::ops::basic::text_of(&k); + if let Some(w) = scratch.put_bytes(0, &t) { + ip.push(Obj::Str(w, false))?; + ip.call(proc.clone())?; + } + } + Ok(()) +} + +// ----- user paths and objects ----- + +pub fn ucache(_ip: &mut Interp) -> R { + Ok(()) +} + +/// Run a user path (an array of numbers and operator names) to build the current path. +fn user_path(ip: &mut Interp, o: Obj) -> R { + let items = match o { + Obj::Array(a, _) => a.items(), + _ => return err("typecheck"), + }; + crate::read::ops::gfx::newpath(ip)?; + for it in items { + match it { + Obj::Name(n, _) => { + let n: &[u8] = &n; + if matches!(n, b"ucache" | b"setbbox") { + if n == b"setbbox" { + for _ in 0..4 { + ip.pop()?; + } + } + continue; + } + let op = crate::read::ops::op_id(n).ok_or(PsErr::Ps("typecheck"))?; + ip.call_op(op)?; + } + Obj::Op(op) => { + if crate::read::ops::OPS.get(op as usize).is_some_and(|(n, _)| *n == b"setbbox") { + for _ in 0..4 { + ip.pop()?; + } + continue; + } + ip.call_op(op)?; + } + o => ip.push(o)?, + } + } + Ok(()) +} + +pub fn uappend(ip: &mut Interp) -> R { + let o = ip.pop()?; + let saved = std::mem::take(&mut ip.gs.path); + user_path(ip, o)?; + let mut p = saved; + p.append(&mut ip.gs.path); + ip.gs.path = p; + Ok(()) +} + +fn upaint(ip: &mut Interp, op: &[u8]) -> R { + let mut m = None; + if let Ok(Obj::Array(a, _)) = ip.top(0).cloned() + && a.len == 6 + && a.items().iter().all(|o| o.num().is_some()) + && ip.o.len() >= 2 + && matches!(ip.top(1), Ok(Obj::Array(..))) + { + m = Some(ip.pop_matrix()?); + } + let o = ip.pop()?; + ip.gsave()?; + let r = (|| { + user_path(ip, o)?; + if let Some(m) = m { + ip.gs.ctm = m.then(&ip.gs.ctm); + } + match op { + b"ufill" => crate::read::ops::gfx::fill(ip), + b"ueofill" => crate::read::ops::gfx::eofill(ip), + _ => crate::read::ops::gfx::stroke(ip), + } + })(); + ip.grestore(); + r +} + +pub fn ufill(ip: &mut Interp) -> R { + upaint(ip, b"ufill") +} + +pub fn ueofill(ip: &mut Interp) -> R { + upaint(ip, b"ueofill") +} + +pub fn ustroke(ip: &mut Interp) -> R { + upaint(ip, b"ustroke") +} + +pub fn setbbox(ip: &mut Interp) -> R { + for _ in 0..4 { + ip.pop_num()?; + } + Ok(()) +} + +pub fn defineuserobject(ip: &mut Interp) -> R { + let v = ip.pop()?; + let i = ip.pop_usize()?; + let arr = match ip.userdict.get_name(b"UserObjects") { + Some(Obj::Array(a, _)) if a.len > i => a, + old => { + let mut items = match old { + Some(Obj::Array(a, _)) => a.items(), + _ => Vec::new(), + }; + if i >= 100_000 { + return err("limitcheck"); + } + ip.charge((i + 1) as u64)?; + ip.alloc((i + 1).saturating_mul(crate::read::ops::basic::OBJ_BYTES))?; + items.resize(i + 1, Obj::Null); + let a = PArr::new(items); + ip.userdict.put_name(b"UserObjects", Obj::Array(a.clone(), false)); + a + } + }; + arr.set(i, v); + Ok(()) +} + +pub fn execuserobject(ip: &mut Interp) -> R { + let i = ip.pop_usize()?; + let v = match ip.userdict.get_name(b"UserObjects") { + Some(Obj::Array(a, _)) => a.get(i).ok_or(PsErr::Ps("undefined"))?, + _ => return err("undefined"), + }; + ip.exec_value(v) +} + +pub fn undefineuserobject(ip: &mut Interp) -> R { + ip.pop_usize().map(|_| ()) +} + +pub fn string_noop(ip: &mut Interp) -> R { + // `setsmoothness` and the like: one number. + ip.pop_num().map(|_| ()) +} + +pub fn gcheck(ip: &mut Interp) -> R { + ip.pop()?; + ip.push(Obj::Bool(false)) +} diff --git a/crates/ps/src/read/ops/mod.rs b/crates/ps/src/read/ops/mod.rs new file mode 100644 index 0000000000..2c88d646d7 --- /dev/null +++ b/crates/ps/src/read/ops/mod.rs @@ -0,0 +1,228 @@ +//! The operator table: every name `systemdict` binds to an operator. + +pub mod basic; +pub mod gfx; +pub mod image; +pub mod mesh; +pub mod misc; +pub mod shading; + +use crate::read::interp::{Interp, R}; +use crate::read::obj::{Obj, PArr, PDict}; +use crate::read::{composite, font}; + +pub type OpId = u16; +pub type OpFn = fn(&mut Interp) -> R; + +macro_rules! named { + ($($n:literal => $f:expr),* $(,)?) => { &[$(($n.as_bytes(), $f as OpFn)),*] }; +} + +pub static OPS: &[(&[u8], OpFn)] = named! { + // stack + "pop" => basic::pop, "exch" => basic::exch, "dup" => basic::dup, "copy" => basic::copy, "index" => basic::index, + "roll" => basic::roll, "clear" => basic::clear, "count" => basic::count, "mark" => basic::mark, "[" => basic::mark, + "<<" => basic::mark, "]" => basic::array_close, ">>" => basic::dict_close, "cleartomark" => basic::cleartomark, + "counttomark" => basic::counttomark, + // arithmetic + "add" => basic::add, "sub" => basic::sub, "mul" => basic::mul, "div" => basic::div, "idiv" => basic::idiv, + "mod" => basic::mod_, "neg" => basic::neg, "abs" => basic::abs, "ceiling" => basic::ceiling, "floor" => basic::floor, + "round" => basic::round, "truncate" => basic::truncate, "sqrt" => basic::sqrt, "sin" => basic::sin, "cos" => basic::cos, + "atan" => basic::atan, "exp" => basic::exp, "ln" => basic::ln, "log" => basic::log, "rand" => basic::rand, + "srand" => basic::srand, "rrand" => basic::rrand, + // relations + "eq" => basic::eq, "ne" => basic::ne, "gt" => basic::gt, "ge" => basic::ge, "lt" => basic::lt, "le" => basic::le, + "and" => basic::and, "or" => basic::or, "xor" => basic::xor, "not" => basic::not, "bitshift" => basic::bitshift, + "true" => basic::true_, "false" => basic::false_, "null" => basic::null, + // control + "exec" => basic::exec, "if" => basic::if_, "ifelse" => basic::ifelse, "for" => basic::for_, "repeat" => basic::repeat, + "loop" => basic::loop_, "exit" => basic::exit, "stop" => basic::stop, "stopped" => basic::stopped, "quit" => basic::quit, + "forall" => basic::forall, "countexecstack" => basic::countexecstack, "execstack" => basic::execstack, + // types + "type" => basic::type_, "cvlit" => basic::cvlit, "cvx" => basic::cvx, "xcheck" => basic::xcheck, + "readonly" => basic::noop_keep, "executeonly" => basic::noop_keep, "noaccess" => basic::noop_keep, + "rcheck" => basic::check_true, "wcheck" => basic::check_true, "cvi" => basic::cvi, "cvr" => basic::cvr, + "cvn" => basic::cvn, "cvs" => basic::cvs, "cvrs" => basic::cvrs, "bind" => basic::bind, + // dictionaries + "dict" => basic::dict, "maxlength" => basic::maxlength, "begin" => basic::begin, "end" => basic::end, "def" => basic::def, + // Conventional Type 1 font-prolog aliases. + "ND" => basic::def, "NP" => basic::put, + "load" => basic::load, "store" => basic::store, "get" => basic::get, "put" => basic::put, "known" => basic::known, + "undef" => basic::undef, "where" => basic::where_, "currentdict" => basic::currentdict, + "countdictstack" => basic::countdictstack, "dictstack" => basic::dictstack, "cleardictstack" => basic::cleardictstack, + // strings and arrays + "array" => basic::array, "string" => basic::string, "length" => basic::length, "getinterval" => basic::getinterval, + "putinterval" => basic::putinterval, "aload" => basic::aload, "astore" => basic::astore, + "packedarray" => basic::packedarray, "search" => basic::search, "anchorsearch" => basic::anchorsearch, + "token" => basic::token, + // graphics state + "gsave" => gfx::gsave, "grestore" => gfx::grestore, "grestoreall" => gfx::grestoreall, "initgraphics" => gfx::initgraphics, + "save" => gfx::save, "restore" => gfx::restore, "gstate" => gfx::gstate, "currentgstate" => gfx::currentgstate, + "setgstate" => gfx::setgstate, "setlinewidth" => gfx::setlinewidth, "currentlinewidth" => gfx::currentlinewidth, + "setlinecap" => gfx::setlinecap, "currentlinecap" => gfx::currentlinecap, "setlinejoin" => gfx::setlinejoin, + "currentlinejoin" => gfx::currentlinejoin, "setmiterlimit" => gfx::setmiterlimit, + "currentmiterlimit" => gfx::currentmiterlimit, "setdash" => gfx::setdash, "currentdash" => gfx::currentdash, + "setflat" => gfx::setflat, "currentflat" => gfx::currentflat, "setstrokeadjust" => gfx::setstrokeadjust, + "currentstrokeadjust" => gfx::currentstrokeadjust, "setoverprint" => gfx::setoverprint, + "currentoverprint" => gfx::currentoverprint, + // matrices + "matrix" => gfx::matrix, "initmatrix" => gfx::initmatrix, "identmatrix" => gfx::identmatrix, + "defaultmatrix" => gfx::defaultmatrix, "currentmatrix" => gfx::currentmatrix, "setmatrix" => gfx::setmatrix, + "translate" => gfx::translate, "scale" => gfx::scale, "rotate" => gfx::rotate, "concat" => gfx::concat, + "concatmatrix" => gfx::concatmatrix, "invertmatrix" => gfx::invertmatrix, "transform" => gfx::transform, + "itransform" => gfx::itransform, "dtransform" => gfx::dtransform, "idtransform" => gfx::idtransform, + // paths + "newpath" => gfx::newpath, "moveto" => gfx::moveto, "rmoveto" => gfx::rmoveto, "lineto" => gfx::lineto, + "rlineto" => gfx::rlineto, "curveto" => gfx::curveto, "rcurveto" => gfx::rcurveto, "closepath" => gfx::closepath, + "arc" => gfx::arc, "arcn" => gfx::arcn, "arct" => gfx::arct, "arcto" => gfx::arcto, "currentpoint" => gfx::currentpoint, + "flattenpath" => gfx::flattenpath, "reversepath" => gfx::reversepath, "strokepath" => gfx::strokepath, + "pathbbox" => gfx::pathbbox, "pathforall" => gfx::pathforall, "clippath" => gfx::clippath, "initclip" => gfx::initclip, + "clipsave" => gfx::clipsave, "cliprestore" => gfx::cliprestore, "clip" => gfx::clip, "eoclip" => gfx::eoclip, "rectclip" => gfx::rectclip, + // painting + "fill" => gfx::fill, "eofill" => gfx::eofill, "stroke" => gfx::stroke, "rectfill" => gfx::rectfill, + "rectstroke" => gfx::rectstroke, "shfill" => shading::shfill, "erasepage" => misc::noop, + "image" => image::image, "colorimage" => image::colorimage, "imagemask" => image::imagemask, + // colour + "setgray" => gfx::setgray, "currentgray" => gfx::currentgray, "setrgbcolor" => gfx::setrgbcolor, + "currentrgbcolor" => gfx::currentrgbcolor, "sethsbcolor" => gfx::sethsbcolor, "currenthsbcolor" => gfx::currenthsbcolor, + "setcmykcolor" => gfx::setcmykcolor, "currentcmykcolor" => gfx::currentcmykcolor, "setcolorspace" => gfx::setcolorspace, + "currentcolorspace" => gfx::currentcolorspace, "setcolor" => gfx::setcolor, "currentcolor" => gfx::currentcolor, + "setpattern" => gfx::setpattern, "makepattern" => gfx::makepattern, + // fonts + "findfont" => font::findfont, "definefont" => font::definefont, "undefinefont" => font::undefinefont, + "scalefont" => font::scalefont, "makefont" => font::makefont, "setfont" => font::setfont, + "currentfont" => font::currentfont, "rootfont" => font::currentfont, "selectfont" => font::selectfont, + "show" => font::show, "ashow" => font::ashow, "widthshow" => font::widthshow, "awidthshow" => font::awidthshow, + "xshow" => font::xshow, "yshow" => font::yshow, "xyshow" => font::xyshow, "kshow" => font::kshow, "cshow" => font::cshow, + "glyphshow" => font::glyphshow, "stringwidth" => font::stringwidth, "charpath" => font::charpath, + "setcharwidth" => font::setcharwidth, "setcachedevice" => font::setcachedevice, + "setcachedevice2" => font::setcachedevice2, "setcachelimit" => misc::pop1, "cachestatus" => misc::noop, + // files + "currentfile" => misc::currentfile, "read" => misc::read, "readstring" => misc::readstring, + "readhexstring" => misc::readhexstring, "readline" => misc::readline, "bytesavailable" => misc::bytesavailable, + "closefile" => misc::closefile, "resetfile" => misc::resetfile, "fileposition" => misc::fileposition, + "setfileposition" => misc::setfileposition, "flushfile" => misc::flushfile, "status" => misc::status, + "file" => misc::file, "write" => misc::write_ops, "writestring" => misc::write_ops, "writehexstring" => misc::write_ops, + "eexec" => misc::eexec, "filter" => misc::filter, "flush" => misc::noop, + "print" => misc::print_any, "=" => misc::print_any, "==" => misc::print_any, "stack" => misc::pstack, + "pstack" => misc::pstack, + // resources and forms + "findresource" => misc::findresource, "defineresource" => misc::defineresource, + "undefineresource" => misc::undefineresource, "resourcestatus" => misc::resourcestatus, + "resourceforall" => misc::resourceforall, "execform" => misc::execform, + // user paths and objects + "ucache" => misc::ucache, "setbbox" => misc::setbbox, "uappend" => misc::uappend, "ufill" => misc::ufill, + "ueofill" => misc::ueofill, "ustroke" => misc::ustroke, "defineuserobject" => misc::defineuserobject, + "execuserobject" => misc::execuserobject, "undefineuserobject" => misc::undefineuserobject, + // environment and device + "showpage" => misc::showpage, "copypage" => misc::noop, "nulldevice" => misc::nulldevice, + "languagelevel" => misc::languagelevel, "version" => misc::version, "product" => misc::product, + "revision" => misc::revision, "serialnumber" => misc::zero, "realtime" => misc::realtime, "usertime" => misc::realtime, + "vmstatus" => misc::vmstatus, "vmreclaim" => misc::pop1, "setvmthreshold" => misc::pop1, + "setglobal" => misc::setglobal, "currentglobal" => misc::push_false, "setpacking" => misc::setglobal, + "currentpacking" => misc::push_false, "gcheck" => misc::gcheck, "setshared" => misc::setglobal, + "currentshared" => misc::push_false, "setpagedevice" => misc::pop_dict, "currentpagedevice" => misc::currentpagedevice, + "setuserparams" => misc::pop_dict, "currentuserparams" => misc::currentuserparams, "setsystemparams" => misc::pop_dict, + "currentsystemparams" => misc::currentsystemparams, "setdevparams" => misc::write_ops, "currentdevparams" => misc::empty_dict, + "setscreen" => misc::setscreen, "currentscreen" => misc::currentscreen, "setcolorscreen" => misc::setcolorscreen, + "currentcolorscreen" => misc::currentcolorscreen, "sethalftone" => misc::pop_dict, "currenthalftone" => misc::empty_dict, + "settransfer" => misc::pop1, "currenttransfer" => misc::empty_proc, "setcolortransfer" => misc::setcolortransfer, + "currentcolortransfer" => misc::currentcolortransfer, "setblackgeneration" => misc::pop1, + "currentblackgeneration" => misc::empty_proc, "setundercolorremoval" => misc::pop1, + "currentundercolorremoval" => misc::empty_proc, "setcolorrendering" => misc::pop_dict, + "currentcolorrendering" => misc::empty_dict, "findcolorrendering" => misc::findcolorrendering, + "setsmoothness" => misc::string_noop, "currentsmoothness" => misc::zero, "internaldict" => misc::internaldict, + "setucacheparams" => misc::noop, "ucachestatus" => misc::noop, "setobjectformat" => misc::pop1, + "currentobjectformat" => misc::zero, "sethalftonephase" => misc::setbbox, "echo" => misc::pop1, + "prompt" => misc::noop, "executive" => misc::noop, "start" => misc::noop, + // CFF font sets, CMaps and composite fonts + "StartData" => composite::startdata, "composefont" => composite::composefont, + "begincmap" => composite::begincmap, "endcmap" => composite::endcmap, "usecmap" => composite::usecmap, + "begincodespacerange" => composite::begin_block, "endcodespacerange" => composite::endcodespacerange, + "begincidrange" => composite::begin_block, "endcidrange" => composite::endcidrange, + "begincidchar" => composite::begin_block, "endcidchar" => composite::endcidchar, + "beginbfchar" => composite::begin_block, "endbfchar" => composite::end_ignored, + "beginbfrange" => composite::begin_block, "endbfrange" => composite::end_ignored, + "beginnotdefrange" => composite::begin_block, "endnotdefrange" => composite::end_ignored, + "beginnotdefchar" => composite::begin_block, "endnotdefchar" => composite::end_ignored, +}; + +pub fn op_id(n: &[u8]) -> Option { + OPS.iter().position(|(name, _)| *name == n).and_then(|i| OpId::try_from(i).ok()) +} + +fn encoding(names: Vec<&'static str>) -> Obj { + Obj::Array(PArr::new(names.into_iter().map(|n| Obj::lit(n.as_bytes())).collect()), false) +} + +/// Fill systemdict and the standard dictionaries. +pub fn install(ip: &mut Interp) { + for (i, (n, _)) in OPS.iter().enumerate() { + if let Ok(id) = OpId::try_from(i) { + ip.systemdict.put_name(n, Obj::Op(id)); + } + } + // Environment queries are plain values: executing the name pushes them, and programs that + // `get` them from systemdict (`systemdict /languagelevel get 2 ge`) find a number. + ip.systemdict.put_name(b"languagelevel", Obj::Int(3)); + for (n, d) in [ + (&b"systemdict"[..], ip.systemdict.clone()), + (b"userdict", ip.userdict.clone()), + (b"globaldict", ip.globaldict.clone()), + (b"errordict", ip.errordict.clone()), + (b"$error", ip.dollar_error.clone()), + (b"statusdict", ip.statusdict.clone()), + (b"FontDirectory", ip.fontdir.clone()), + (b"GlobalFontDirectory", ip.fontdir.clone()), + (b"SharedFontDirectory", ip.fontdir.clone()), + ] { + ip.systemdict.put_name(n, Obj::Dict(d)); + } + ip.systemdict.put_name(b"version", Obj::str(b"3010")); + ip.systemdict.put_name(b"product", Obj::str(b"craft-ps")); + ip.systemdict.put_name(b"revision", Obj::Int(1)); + ip.systemdict.put_name(b"serialnumber", Obj::Int(0)); + ip.systemdict.put_name(b"StandardEncoding", encoding(crate::read::encodings::standard())); + ip.systemdict.put_name(b"ISOLatin1Encoding", encoding(crate::read::encodings::iso_latin1())); + // Errors are handled by `stopped`; the handlers exist for programs that look at them. + for e in [ + "dictfull", + "dictstackoverflow", + "dictstackunderflow", + "execstackoverflow", + "handleerror", + "interrupt", + "invalidaccess", + "invalidexit", + "invalidfileaccess", + "invalidfont", + "invalidrestore", + "ioerror", + "limitcheck", + "nocurrentpoint", + "rangecheck", + "stackoverflow", + "stackunderflow", + "syntaxerror", + "timeout", + "typecheck", + "undefined", + "undefinedfilename", + "undefinedresult", + "unmatchedmark", + "unregistered", + "VMerror", + "configurationerror", + "undefinedresource", + ] { + let stop = op_id(b"stop").map(Obj::Op).unwrap_or(Obj::Null); + ip.errordict.put_name(e.as_bytes(), Obj::proc(vec![stop])); + } + ip.dollar_error.put_name(b"newerror", Obj::Bool(false)); + ip.statusdict.put_name(b"product", Obj::str(b"craft-ps")); + ip.statusdict.put_name(b"processcolors", Obj::proc(vec![Obj::Int(4)])); + ip.userdict.put_name(b"#copies", Obj::Int(1)); + let cats = PDict::new(4); + ip.resources.put_name(b"Category", Obj::Dict(cats)); + composite::install(ip); +} diff --git a/crates/ps/src/read/ops/shading.rs b/crates/ps/src/read/ops/shading.rs new file mode 100644 index 0000000000..599a069211 --- /dev/null +++ b/crates/ps/src/read/ops/shading.rs @@ -0,0 +1,389 @@ +//! Smooth shading: `shfill` and shading patterns. Functions (types 0, 2 and 3, or procedures) +//! are evaluated here in the shading's colour space and sampled into device colours, which the +//! PDF carries as a sampled function. + +use crate::read::gstate::{DevColor, M, Seg}; +use crate::read::interp::{Interp, PsErr, R, err, matrix_of}; +use crate::read::obj::{Obj, PDict}; +use crate::read::ops::gfx; +use crate::read::pdf::{OutSpace, ShadeKind, Shading}; + +/// Samples along an axial or radial shading, and per side of a function-based one. +const SAMPLES: usize = 256; +const GRID: usize = 48; +/// The most inputs a sampled function may take. +const MAX_INPUTS: usize = 4; +/// The most samples a sampled function may hold. +const MAX_SAMPLES: usize = 1 << 22; + +pub enum Func { + Exp { + c0: Vec, + c1: Vec, + n: f64, + domain: [f64; 2], + }, + Stitch { + fns: Vec, + bounds: Vec, + encode: Vec, + domain: [f64; 2], + }, + Sampled { + size: Vec, + domain: Vec, + encode: Vec, + decode: Vec, + samples: Vec, + outs: usize, + }, + Proc(Obj), + /// One function per output. + Each(Vec), +} + +fn nums(o: Option) -> Option> { + match o? { + Obj::Array(a, _) => Some(a.items().iter().filter_map(Obj::num).collect()), + _ => None, + } +} + +fn pair(v: &[f64], dflt: [f64; 2]) -> [f64; 2] { + [v.first().copied().unwrap_or(dflt[0]), v.get(1).copied().unwrap_or(dflt[1])] +} + +fn parse_fn(ip: &mut Interp, o: &Obj, depth: usize) -> R { + if depth > 8 { + return err("limitcheck"); + } + let d = match o { + Obj::Dict(d) => d.clone(), + Obj::Array(a, false) => return a.items().iter().map(|f| parse_fn(ip, f, depth + 1)).collect::>>().map(Func::Each), + p @ Obj::Array(_, true) => return Ok(Func::Proc(p.clone())), + _ => return err("typecheck"), + }; + let domain = nums(d.get_name(b"Domain")).unwrap_or_else(|| vec![0.0, 1.0]); + match d.get_name(b"FunctionType").and_then(|o| o.num()).unwrap_or(-1.0) as i64 { + 2 => Ok(Func::Exp { + c0: nums(d.get_name(b"C0")).unwrap_or_else(|| vec![0.0]), + c1: nums(d.get_name(b"C1")).unwrap_or_else(|| vec![1.0]), + n: d.get_name(b"N").and_then(|o| o.num()).unwrap_or(1.0), + domain: pair(&domain, [0.0, 1.0]), + }), + 3 => { + let fns = match d.get_name(b"Functions") { + Some(Obj::Array(a, _)) => a.items().iter().map(|f| parse_fn(ip, f, depth + 1)).collect::>>()?, + _ => return err("typecheck"), + }; + Ok(Func::Stitch { + fns, + bounds: nums(d.get_name(b"Bounds")).unwrap_or_default(), + encode: nums(d.get_name(b"Encode")).unwrap_or_default(), + domain: pair(&domain, [0.0, 1.0]), + }) + } + 0 => { + let size: Vec = nums(d.get_name(b"Size")).unwrap_or_default().iter().map(|v| v.max(1.0) as usize).collect(); + let range = nums(d.get_name(b"Range")).unwrap_or_default(); + let outs = range.len() / 2; + let bps = d.get_name(b"BitsPerSample").and_then(|o| o.num()).unwrap_or(8.0) as usize; + let count = size.iter().try_fold(outs.max(1), |a, s| a.checked_mul(*s)).filter(|n| *n <= MAX_SAMPLES).ok_or(PsErr::Ps("limitcheck"))?; + // At most four inputs: interpolation visits 2^inputs corners per value. + if size.is_empty() || size.len() > MAX_INPUTS || outs == 0 || !matches!(bps, 1 | 2 | 4 | 8 | 12 | 16 | 24 | 32) { + return err("rangecheck"); + } + ip.charge(count as u64)?; + ip.alloc(count.saturating_mul(8))?; + let bytes_needed = (count * bps).div_ceil(8); + let data = match d.get_name(b"DataSource") { + Some(Obj::Str(s, _)) => s.bytes(), + Some(Obj::File(id)) => { + let mut v = Vec::with_capacity(bytes_needed); + while v.len() < bytes_needed { + match ip.srcs.read(id) { + Some(c) => v.push(c), + None => break, + } + } + v + } + _ => return err("typecheck"), + }; + let max = ((1u64 << bps) - 1) as f64; + let mut samples = Vec::with_capacity(count); + let mut bit = 0usize; + for _ in 0..count { + let mut v = 0u64; + for _ in 0..bps { + let byte = data.get(bit / 8).copied().unwrap_or(0); + v = v << 1 | u64::from(byte >> (7 - bit % 8) & 1); + bit += 1; + } + samples.push(v as f64 / max); + } + let encode = nums(d.get_name(b"Encode")).unwrap_or_else(|| size.iter().flat_map(|s| [0.0, (*s as f64 - 1.0).max(0.0)]).collect()); + let decode = nums(d.get_name(b"Decode")).unwrap_or(range); + Ok(Func::Sampled { size, domain, encode, decode, samples, outs }) + } + _ => err("rangecheck"), + } +} + +pub fn eval(ip: &mut Interp, f: &Func, x: &[f64], depth: usize) -> R> { + if depth > 16 { + return err("limitcheck"); + } + Ok(match f { + Func::Exp { c0, c1, n, domain } => { + let t = x.first().copied().unwrap_or(0.0).clamp(domain[0].min(domain[1]), domain[0].max(domain[1])); + let k = t.powf(*n); + let len = c0.len().max(c1.len()); + (0..len) + .map(|i| c0.get(i).copied().unwrap_or(0.0) + k * (c1.get(i).copied().unwrap_or(1.0) - c0.get(i).copied().unwrap_or(0.0))) + .collect() + } + Func::Stitch { fns, bounds, encode, domain } => { + let t = x.first().copied().unwrap_or(0.0).clamp(domain[0], domain[1]); + let i = bounds.iter().take_while(|b| t >= **b).count().min(fns.len().saturating_sub(1)); + let lo = if i == 0 { domain[0] } else { bounds.get(i - 1).copied().unwrap_or(domain[0]) }; + let hi = bounds.get(i).copied().unwrap_or(domain[1]); + let (e0, e1) = (encode.get(2 * i).copied().unwrap_or(0.0), encode.get(2 * i + 1).copied().unwrap_or(1.0)); + let u = if hi > lo { e0 + (t - lo) / (hi - lo) * (e1 - e0) } else { e0 }; + match fns.get(i) { + Some(sub) => eval(ip, sub, &[u], depth + 1)?, + None => vec![0.0], + } + } + Func::Sampled { size, domain, encode, decode, samples, outs } => { + // Multilinear interpolation between the samples around the point. + let m = size.len(); + let mut base = 0usize; + let mut stride = *outs; + let mut corners: Vec<(usize, f64)> = vec![(0, 1.0)]; + for k in 0..m { + let (d0, d1) = (domain.get(2 * k).copied().unwrap_or(0.0), domain.get(2 * k + 1).copied().unwrap_or(1.0)); + let s = size.get(k).copied().unwrap_or(1); + let xk = x.get(k).copied().unwrap_or(0.0).clamp(d0.min(d1), d0.max(d1)); + let (e0, e1) = (encode.get(2 * k).copied().unwrap_or(0.0), encode.get(2 * k + 1).copied().unwrap_or((s - 1) as f64)); + let e = if d1 != d0 { e0 + (xk - d0) / (d1 - d0) * (e1 - e0) } else { e0 }; + let e = e.clamp(0.0, (s - 1) as f64); + let i0 = e.floor() as usize; + let i1 = (i0 + 1).min(s - 1); + let frac = e - i0 as f64; + base += i0 * stride; + let step = (i1 - i0) * stride; + corners = corners.into_iter().flat_map(|(off, w)| [(off, w * (1.0 - frac)), (off + step, w * frac)]).collect(); + stride *= s; + } + (0..*outs) + .map(|j| { + let v: f64 = corners.iter().map(|(off, w)| samples.get(base + off + j).copied().unwrap_or(0.0) * w).sum(); + let (d0, d1) = (decode.get(2 * j).copied().unwrap_or(0.0), decode.get(2 * j + 1).copied().unwrap_or(1.0)); + d0 + v * (d1 - d0) + }) + .collect() + } + Func::Proc(p) => { + for v in x { + ip.push(Obj::Real(*v))?; + } + let before = ip.o.len() - x.len(); + ip.call(p.clone())?; + let n = ip.o.len().saturating_sub(before); + let mut out = vec![0.0; n]; + for slot in out.iter_mut().rev() { + *slot = ip.pop_num()?; + } + out + } + Func::Each(fns) => { + let mut out = Vec::with_capacity(fns.len()); + for f in fns { + out.push(eval(ip, f, x, depth + 1)?.first().copied().unwrap_or(0.0)); + } + out + } + }) +} + +/// Device colours as bytes in one output space (CMYK when every colour is CMYK). +pub fn pack(colors: &[DevColor]) -> (OutSpace, Vec) { + let b = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let all_cmyk = colors.iter().all(|c| matches!(c, DevColor::Cmyk(..))); + let all_gray = colors.iter().all(|c| matches!(c, DevColor::Gray(..))); + let mut out = Vec::new(); + for c in colors { + match (*c, all_cmyk, all_gray) { + (DevColor::Cmyk(c, m, y, k), true, _) => out.extend([b(c), b(m), b(y), b(k)]), + (DevColor::Gray(g), _, true) => out.push(b(g)), + (DevColor::Gray(g), _, _) => out.extend([b(g); 3]), + (DevColor::Rgb(r, g, bl), _, _) => out.extend([b(r), b(g), b(bl)]), + (DevColor::Cmyk(c, m, y, k), _, _) => out.extend([b(1.0 - (c + k).min(1.0)), b(1.0 - (m + k).min(1.0)), b(1.0 - (y + k).min(1.0))]), + } + } + let space = if all_cmyk { + OutSpace::Cmyk + } else if all_gray { + OutSpace::Gray + } else { + OutSpace::Rgb + }; + (space, out) +} + +/// A shading dictionary as the PDF will draw it, or None for kinds not drawn (with a warning). +pub fn build(ip: &mut Interp, d: &PDict) -> R> { + let kind = d.get_name(b"ShadingType").and_then(|o| o.num()).unwrap_or(0.0) as i64; + let space_obj = d.get_name(b"ColorSpace").ok_or(PsErr::Ps("undefined"))?; + let space = gfx::parse_space(ip, &space_obj, 0)?; + let func = match d.get_name(b"Function") { + Some(f) => Some(parse_fn(ip, &f, 0)?), + None => None, + }; + let bbox = nums(d.get_name(b"BBox")).filter(|b| b.len() == 4).map(|b| [b[0], b[1], b[2], b[3]]); + let extend = match d.get_name(b"Extend") { + Some(Obj::Array(a, _)) => [matches!(a.get(0), Some(Obj::Bool(true))), matches!(a.get(1), Some(Obj::Bool(true)))], + _ => [false, false], + }; + let color_at = |ip: &mut Interp, x: &[f64]| -> R { + let comps = match &func { + Some(f) => eval(ip, f, x, 0)?, + None => x.to_vec(), + }; + gfx::to_device(ip, &space, &comps, 0) + }; + let shade = match kind { + 2 | 3 => { + let coords = nums(d.get_name(b"Coords")).unwrap_or_default(); + let domain = pair(&nums(d.get_name(b"Domain")).unwrap_or_default(), [0.0, 1.0]); + let mut colors = Vec::with_capacity(SAMPLES); + for i in 0..SAMPLES { + let t = domain[0] + (domain[1] - domain[0]) * i as f64 / (SAMPLES - 1) as f64; + colors.push(color_at(ip, &[t])?); + } + let k = if kind == 2 { + let [a, b, c, e] = <[f64; 4]>::try_from(coords).map_err(|_| PsErr::Ps("rangecheck"))?; + ShadeKind::Axial([a, b, c, e]) + } else { + let [a, b, c, e, f, g] = <[f64; 6]>::try_from(coords).map_err(|_| PsErr::Ps("rangecheck"))?; + ShadeKind::Radial([a, b, c, e, f, g]) + }; + let (space, data) = pack(&colors); + Shading { kind: k, extend, space, data, samples: SAMPLES, bbox, points: Vec::new() } + } + 1 => { + let dom = nums(d.get_name(b"Domain")).unwrap_or_else(|| vec![0.0, 1.0, 0.0, 1.0]); + let [x0, x1, y0, y1] = <[f64; 4]>::try_from(dom).map_err(|_| PsErr::Ps("rangecheck"))?; + let matrix = match d.get_name(b"Matrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => M::ID, + }; + let mut colors = Vec::with_capacity(GRID * GRID); + for j in 0..GRID { + for i in 0..GRID { + let x = x0 + (x1 - x0) * i as f64 / (GRID - 1) as f64; + let y = y0 + (y1 - y0) * j as f64 / (GRID - 1) as f64; + colors.push(color_at(ip, &[x, y])?); + } + } + let (space, data) = pack(&colors); + Shading { kind: ShadeKind::Function { domain: [x0, x1, y0, y1], matrix }, extend, space, data, samples: GRID, bbox, points: Vec::new() } + } + 4..=7 => match crate::read::ops::mesh::build(ip, d, kind, &space, func.as_ref())? { + Some(s) => s, + None => return Ok(None), + }, + _ => { + ip.warnings.push(format!("shading type {kind} not drawn")); + return Ok(None); + } + }; + Ok(Some(shade)) +} + +pub fn shfill(ip: &mut Interp) -> R { + let d = ip.pop_dict()?; + if ip.gs.nulldev { + return Ok(()); + } + let Some(s) = build(ip, &d)? else { return Ok(()) }; + let ctm = ip.gs.ctm; + ip.out.shade(&ip.gs.clip, None, false, &ctm, s).map_err(PsErr::Fatal) +} + +/// Fill `path` with the current shading pattern; false when the pattern isn't a shading. +pub fn fill_pattern(ip: &mut Interp, path: &[Seg], eo: bool) -> R { + let Some(p) = ip.gs.pattern.clone() else { return Ok(false) }; + if p.get_name(b"PatternType").and_then(|o| o.num()) == Some(1.0) { + return tiling(ip, &p, path, eo).map(|()| true); + } + if p.get_name(b"PatternType").and_then(|o| o.num()) != Some(2.0) { + return Ok(false); + } + let Some(Obj::Dict(sh)) = p.get_name(b"Shading") else { return Ok(false) }; + let m = match p.get_name(b"CraftPsMatrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => M::ID, + }; + let Some(s) = build(ip, &sh)? else { return Ok(true) }; + ip.out.shade(&ip.gs.clip, Some(path), eo, &m, s).map_err(PsErr::Fatal)?; + Ok(true) +} + +/// Fill with a tiling pattern: its cell painted once (per colour, for an uncoloured one) into a +/// PDF tiling pattern, cached on the pattern. +fn tiling(ip: &mut Interp, p: &PDict, path: &[Seg], eo: bool) -> R { + let uncolored = p.get_name(b"PaintType").and_then(|o| o.num()) == Some(2.0); + let color = if uncolored { Some(ip.gs.color.clone()) } else { None }; + let key = (crate::read::obj::Obj::Dict(p.clone()).key(), color.clone().unwrap_or_default().iter().map(|v| v.to_bits()).collect::>()); + let n = match ip.cells.get(&key) { + Some(n) => *n, + None => { + let n = cell(ip, p, color)?; + if ip.cells.len() < 10_000 { + ip.cells.insert(key, n); + } + n + } + }; + ip.out.fill_tiling(&ip.gs.clip, path, eo, n).map_err(PsErr::Fatal) +} + +fn cell(ip: &mut Interp, p: &PDict, color: Option>) -> R { + let bbox = nums(p.get_name(b"BBox")).filter(|b| b.len() == 4).map(|b| [b[0], b[1], b[2], b[3]]).ok_or(PsErr::Ps("rangecheck"))?; + let num = |k: &[u8]| p.get_name(k).and_then(|o| o.num()); + let step = (num(b"XStep").unwrap_or(bbox[2] - bbox[0]), num(b"YStep").unwrap_or(bbox[3] - bbox[1])); + if step.0 == 0.0 || step.1 == 0.0 || !step.0.is_finite() || !step.1.is_finite() { + return err("rangecheck"); + } + let m = match p.get_name(b"CraftPsMatrix") { + Some(Obj::Array(a, _)) => matrix_of(&a)?, + _ => M::ID, + }; + let paint = p.get_name(b"PaintProc").ok_or(PsErr::Ps("undefined"))?; + let under = ip.gs.pattern_base.as_deref().cloned(); + let cap = ip.out.begin_cell(); + ip.gsave()?; + // The cell is drawn in pattern space, unclipped, from a fresh path. + ip.gs.ctm = M::ID; + ip.gs.clip = None; + ip.gs.path.clear(); + ip.gs.cur = None; + ip.gs.nulldev = false; + if let Some(c) = color { + // An uncoloured cell paints in the colour given with the pattern. + ip.gs.space = under.unwrap_or(match c.len() { + 3 => crate::read::gstate::Space::Rgb, + 4 => crate::read::gstate::Space::Cmyk, + _ => crate::read::gstate::Space::Gray, + }); + ip.gs.color = c; + ip.gs.pattern = None; + ip.gs.color_locked = true; + } + let r = ip.push(Obj::Dict(p.clone())).and_then(|()| ip.call(paint)); + ip.grestore(); + let n = ip.out.end_cell(cap, bbox, step, m).map_err(PsErr::Fatal)?; + r.map(|()| n) +} diff --git a/crates/ps/src/read/pdf.rs b/crates/ps/src/read/pdf.rs new file mode 100644 index 0000000000..0faabe09a3 --- /dev/null +++ b/crates/ps/src/read/pdf.rs @@ -0,0 +1,629 @@ +//! What the program paints, written as a one-page PDF. +//! +//! Paths arrive in device space (the EPS's default user space). Clipping is applied lazily: +//! before each painting operation the clips in force are matched against those the content +//! stream has applied, popping (`Q`) and pushing (`q … W n`) the difference, so the PostScript +//! program's own gsave/grestore pattern doesn't matter. + +use std::rc::Rc; + +use pdf_writer::types::{LineCapStyle, LineJoinStyle}; +use pdf_writer::{Content, Filter, Finish, Name, Pdf, Rect, Ref}; + +use crate::read::gstate::{Clip, DevColor, M, Seg, clip_chain}; + +/// The most path segments and images written. +const MAX_SEGMENTS: usize = 20_000_000; +const MAX_IMAGES: usize = 100_000; + +#[derive(Clone, Debug, PartialEq)] +pub enum ImgSpace { + Gray, + Rgb, + Cmyk, + Indexed { base: Box, hival: u8, lookup: Vec }, +} + +#[derive(Debug)] +pub struct Image { + pub w: u32, + pub h: u32, + pub bpc: u8, + /// None for a stencil mask (`imagemask`). + pub space: Option, + pub decode: Option>, + pub data: Vec, + /// `data` is a JPEG (DCTDecode passed through). + pub dct: bool, + pub interpolate: bool, + /// An 8-bit soft mask (w, h, alpha). + pub smask: Option<(u32, u32, Vec)>, +} + +/// The device space a shading's colours were sampled in. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum OutSpace { + Gray, + Rgb, + Cmyk, +} + +impl OutSpace { + fn comps(self) -> usize { + match self { + OutSpace::Gray => 1, + OutSpace::Rgb => 3, + OutSpace::Cmyk => 4, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ShadeKind { + Axial([f64; 4]), + Radial([f64; 6]), + /// A function of (x, y) over its domain, mapped by `matrix`. + Function { + domain: [f64; 4], + matrix: M, + }, + /// Vertices in threes; `Coons` and `Tensor` patches of 12 and 16 points. + Triangles, + Coons, + Tensor, +} + +/// A smooth shading with its colours sampled: along the axis (`samples` of them), over a +/// `samples` × `samples` grid, or one per vertex or patch corner. +#[derive(Clone, Debug)] +pub struct Shading { + pub kind: ShadeKind, + pub extend: [bool; 2], + pub space: OutSpace, + pub data: Vec, + pub samples: usize, + pub bbox: Option<[f64; 4]>, + pub points: Vec<(f64, f64)>, +} + +/// A tiling pattern cell: its content (in pattern space), cell box, steps and pattern matrix. +pub struct Tiling { + content: Vec, + bbox: [f64; 4], + step: (f64, f64), + matrix: M, +} + +/// What a pattern cell's content replaces while it is captured. +pub struct Capture { + c: Content, + applied: Vec>, + state: PaintState, + saved: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq)] +struct PaintState { + fill: Option, + stroke: Option, +} + +pub struct StrokeParams<'a> { + pub width: f64, + pub cap: i64, + pub join: i64, + pub miter: f64, + pub dash: &'a (Vec, f64), +} + +pub struct Out { + c: Content, + images: Vec, + shadings: Vec, + tilings: Vec, + origin: (f64, f64), + applied: Vec>, + state: PaintState, + saved: Vec, + segments: usize, + /// Anything painted at all. + pub painted: bool, +} + +fn f(v: f64) -> f32 { + if v.is_finite() { v.clamp(-3.0e7, 3.0e7) as f32 } else { 0.0 } +} + +impl Out { + pub fn new(origin: (f64, f64)) -> Self { + let mut c = Content::new(); + c.transform([1.0, 0.0, 0.0, 1.0, f(-origin.0), f(-origin.1)]); + Out { + c, + images: Vec::new(), + shadings: Vec::new(), + tilings: Vec::new(), + origin, + applied: Vec::new(), + state: PaintState::default(), + saved: Vec::new(), + segments: 0, + painted: false, + } + } + + /// Preserve the semantic text for consumers that group outlined glyphs. + pub fn begin_actual_text(&mut self, text: &str) { + self.c.begin_marked_content_with_properties(Name(b"Span")).properties().actual_text(pdf_writer::TextStr(text)); + } + + pub fn end_actual_text(&mut self) { + self.c.end_marked_content(); + } + + fn sync_clip(&mut self, clip: &Option>) -> Result<(), String> { + let target = clip_chain(clip); + let common = self.applied.iter().zip(&target).take_while(|(a, b)| Rc::ptr_eq(a, b)).count(); + while self.applied.len() > common { + self.applied.pop(); + self.c.restore_state(); + self.state = self.saved.pop().unwrap_or_default(); + } + for node in target.into_iter().skip(common) { + self.c.save_state(); + self.saved.push(self.state.clone()); + self.path(&node.path)?; + if node.eo { + self.c.clip_even_odd(); + } else { + self.c.clip_nonzero(); + } + self.c.end_path(); + self.applied.push(node); + } + Ok(()) + } + + fn path(&mut self, path: &[Seg]) -> Result<(), String> { + self.segments = self.segments.saturating_add(path.len()); + if self.segments > MAX_SEGMENTS { + return Err("too many path segments".into()); + } + for s in path { + match *s { + Seg::Move(x, y) => { + self.c.move_to(f(x), f(y)); + } + Seg::Line(x, y) => { + self.c.line_to(f(x), f(y)); + } + Seg::Curve(a, b, c, d, e, g) => { + self.c.cubic_to(f(a), f(b), f(c), f(d), f(e), f(g)); + } + Seg::Close => { + self.c.close_path(); + } + } + } + Ok(()) + } + + fn set_fill(&mut self, color: DevColor) { + if self.state.fill == Some(color) { + return; + } + match color { + DevColor::Gray(g) => self.c.set_fill_gray(f(g)), + DevColor::Rgb(r, g, b) => self.c.set_fill_rgb(f(r), f(g), f(b)), + DevColor::Cmyk(c, m, y, k) => self.c.set_fill_cmyk(f(c), f(m), f(y), f(k)), + }; + self.state.fill = Some(color); + } + + fn set_stroke(&mut self, color: DevColor) { + if self.state.stroke == Some(color) { + return; + } + match color { + DevColor::Gray(g) => self.c.set_stroke_gray(f(g)), + DevColor::Rgb(r, g, b) => self.c.set_stroke_rgb(f(r), f(g), f(b)), + DevColor::Cmyk(c, m, y, k) => self.c.set_stroke_cmyk(f(c), f(m), f(y), f(k)), + }; + self.state.stroke = Some(color); + } + + pub fn fill(&mut self, clip: &Option>, path: &[Seg], eo: bool, color: DevColor) -> Result<(), String> { + if !path.iter().any(|s| !matches!(s, Seg::Move(..))) { + return Ok(()); + } + self.sync_clip(clip)?; + self.set_fill(color); + self.path(path)?; + if eo { + self.c.fill_even_odd(); + } else { + self.c.fill_nonzero(); + } + self.painted = true; + Ok(()) + } + + /// Stroke a device-space path drawn under `ctm` (the pen is shaped in user space). + pub fn stroke(&mut self, clip: &Option>, path: &[Seg], ctm: &M, p: &StrokeParams, color: DevColor) -> Result<(), String> { + if !path.iter().any(|s| !matches!(s, Seg::Move(..))) { + return Ok(()); + } + let Some(inv) = ctm.inv() else { return Ok(()) }; + self.sync_clip(clip)?; + self.set_stroke(color); + self.c.save_state(); + self.c.transform(ctm.0.map(f)); + let user: Vec = path.iter().map(|s| s.map(&inv)).collect(); + self.c.set_line_width(f(p.width.max(0.0))); + self.c.set_line_cap(match p.cap { + 1 => LineCapStyle::RoundCap, + 2 => LineCapStyle::ProjectingSquareCap, + _ => LineCapStyle::ButtCap, + }); + self.c.set_line_join(match p.join { + 1 => LineJoinStyle::RoundJoin, + 2 => LineJoinStyle::BevelJoin, + _ => LineJoinStyle::MiterJoin, + }); + self.c.set_miter_limit(f(p.miter.max(1.0))); + if crate::read::gstate::dashes_ok(&user, &p.dash.0) { + self.c.set_dash_pattern(p.dash.0.iter().map(|d| f(*d)), f(p.dash.1)); + } + self.path(&user)?; + self.c.stroke(); + self.c.restore_state(); + self.painted = true; + Ok(()) + } + + /// Paint an image: `cm` maps the unit square onto the page; stencil masks use `fill`. + pub fn image(&mut self, clip: &Option>, cm: &M, img: Image, fill: Option) -> Result<(), String> { + if self.images.len() >= MAX_IMAGES { + return Err("too many images".into()); + } + if !cm.finite() || img.w == 0 || img.h == 0 { + return Ok(()); + } + self.sync_clip(clip)?; + if let Some(color) = fill { + self.set_fill(color); + } + let n = self.images.len(); + self.images.push(img); + self.c.save_state(); + self.c.transform(cm.0.map(f)); + let name = format!("Im{n}"); + self.c.x_object(Name(name.as_bytes())); + self.c.restore_state(); + self.painted = true; + Ok(()) + } + + /// Start a pattern cell: painting goes to its own content until [`Out::end_cell`]. + pub fn begin_cell(&mut self) -> Capture { + Capture { + c: std::mem::replace(&mut self.c, Content::new()), + applied: std::mem::take(&mut self.applied), + state: std::mem::take(&mut self.state), + saved: std::mem::take(&mut self.saved), + } + } + + /// Finish a pattern cell: its pattern number. + pub fn end_cell(&mut self, cap: Capture, bbox: [f64; 4], step: (f64, f64), matrix: M) -> Result { + let mut cell = std::mem::replace(&mut self.c, cap.c); + for _ in 0..self.applied.len() { + cell.restore_state(); + } + self.applied = cap.applied; + self.state = cap.state; + self.saved = cap.saved; + if self.tilings.len() >= MAX_IMAGES { + return Err("too many patterns".into()); + } + // Pattern space maps to the page's default space, which the content moved to the origin. + let matrix = matrix.then(&M([1.0, 0.0, 0.0, 1.0, -self.origin.0, -self.origin.1])); + self.tilings.push(Tiling { content: cell.finish().into_vec(), bbox, step, matrix }); + Ok(self.tilings.len() - 1) + } + + /// Fill a device-space path with tiling pattern `n`. + pub fn fill_tiling(&mut self, clip: &Option>, path: &[Seg], eo: bool, n: usize) -> Result<(), String> { + if !path.iter().any(|s| !matches!(s, Seg::Move(..))) { + return Ok(()); + } + self.sync_clip(clip)?; + self.c.set_fill_color_space(pdf_writer::types::ColorSpaceOperand::Pattern); + let name = format!("P{n}"); + self.c.set_fill_pattern(None, Name(name.as_bytes())); + self.state.fill = None; + self.path(path)?; + if eo { + self.c.fill_even_odd(); + } else { + self.c.fill_nonzero(); + } + self.painted = true; + Ok(()) + } + + /// Paint a shading in shading space `m` (inside `path` too, for a shading pattern fill). + pub fn shade(&mut self, clip: &Option>, path: Option<&[Seg]>, eo: bool, m: &M, s: Shading) -> Result<(), String> { + if self.shadings.len() >= MAX_IMAGES { + return Err("too many shadings".into()); + } + if !m.finite() || m.inv().is_none() { + return Ok(()); + } + self.sync_clip(clip)?; + self.c.save_state(); + if let Some(p) = path { + self.path(p)?; + if eo { + self.c.clip_even_odd(); + } else { + self.c.clip_nonzero(); + } + self.c.end_path(); + } + self.c.transform(m.0.map(f)); + if let Some([x0, y0, x1, y1]) = s.bbox { + self.c.rect(f(x0), f(y0), f(x1 - x0), f(y1 - y0)); + self.c.clip_nonzero(); + self.c.end_path(); + } + let name = format!("Sh{}", self.shadings.len()); + self.shadings.push(s); + self.c.shading(Name(name.as_bytes())); + self.c.restore_state(); + self.painted = true; + Ok(()) + } + + /// The PDF: one page of `size`, its content, images and shadings. + /// Path segments written so far (clips included). + pub fn segments(&self) -> usize { + self.segments + } + + pub fn finish(self, size: (f64, f64)) -> Vec { + let mut pdf = Pdf::new(); + // ActualText marked content is defined in PDF 1.5; the rest of this output uses basic + // page content, without transparency groups. + pdf.set_version(1, 5); + let (catalog, pages, page, content) = (Ref::new(1), Ref::new(2), Ref::new(3), Ref::new(4)); + let mut next = 5; + let mut alloc = || { + let r = Ref::new(next); + next += 1; + r + }; + let image_refs: Vec<(Ref, Option)> = self.images.iter().map(|i| (alloc(), i.smask.as_ref().map(|_| alloc()))).collect(); + let shading_refs: Vec<(Ref, Ref)> = self.shadings.iter().map(|_| (alloc(), alloc())).collect(); + let tiling_refs: Vec = self.tilings.iter().map(|_| alloc()).collect(); + // Every resource is listed for the page and for each pattern cell (names are global). + let resources = |res: &mut pdf_writer::writers::Resources<'_>| { + let mut xo = res.x_objects(); + for (i, (r, _)) in image_refs.iter().enumerate() { + let name = format!("Im{i}"); + xo.pair(Name(name.as_bytes()), *r); + } + xo.finish(); + let mut sh = res.shadings(); + for (i, (r, _)) in shading_refs.iter().enumerate() { + let name = format!("Sh{i}"); + sh.pair(Name(name.as_bytes()), *r); + } + sh.finish(); + let mut pa = res.patterns(); + for (i, r) in tiling_refs.iter().enumerate() { + let name = format!("P{i}"); + pa.pair(Name(name.as_bytes()), *r); + } + pa.finish(); + }; + pdf.catalog(catalog).pages(pages); + pdf.pages(pages).kids([page]).count(1); + { + let mut p = pdf.page(page); + p.parent(pages); + p.media_box(Rect::new(0.0, 0.0, f(size.0.max(1.0)), f(size.1.max(1.0)))); + p.contents(content); + let mut res = p.resources(); + resources(&mut res); + res.finish(); + p.finish(); + } + let mut c = self.c; + for _ in 0..self.applied.len() { + c.restore_state(); + } + let raw = c.finish().into_vec(); + let z = miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6); + pdf.stream(content, &z).filter(Filter::FlateDecode); + for (img, (r, smask)) in self.images.iter().zip(&image_refs) { + let packed; + let (data, filter) = if img.dct { + (&img.data[..], Filter::DctDecode) + } else { + packed = miniz_oxide::deflate::compress_to_vec_zlib(&img.data, 6); + (&packed[..], Filter::FlateDecode) + }; + let mut x = pdf.image_xobject(*r, data); + x.filter(filter); + x.width(i32::try_from(img.w).unwrap_or(i32::MAX)); + x.height(i32::try_from(img.h).unwrap_or(i32::MAX)); + match &img.space { + None => { + x.image_mask(true); + } + Some(space) => { + x.bits_per_component(i32::from(img.bpc)); + match space { + ImgSpace::Gray => x.color_space().device_gray(), + ImgSpace::Rgb => x.color_space().device_rgb(), + ImgSpace::Cmyk => x.color_space().device_cmyk(), + ImgSpace::Indexed { base, hival, lookup } => { + let base = match **base { + ImgSpace::Rgb => Name(b"DeviceRGB"), + ImgSpace::Cmyk => Name(b"DeviceCMYK"), + _ => Name(b"DeviceGray"), + }; + x.color_space().indexed(base, i32::from(*hival), lookup); + } + } + } + } + if img.space.is_none() { + x.bits_per_component(1); + } + if let Some(d) = &img.decode { + x.decode(d.iter().copied()); + } + if img.interpolate { + x.interpolate(true); + } + if let Some(m) = smask { + x.s_mask(*m); + } + x.finish(); + if let (Some(m), Some((w, h, alpha))) = (smask, &img.smask) { + let z = miniz_oxide::deflate::compress_to_vec_zlib(alpha, 6); + let mut s = pdf.image_xobject(*m, &z); + s.filter(Filter::FlateDecode); + s.width(i32::try_from(*w).unwrap_or(i32::MAX)); + s.height(i32::try_from(*h).unwrap_or(i32::MAX)); + s.color_space().device_gray(); + s.bits_per_component(8); + s.finish(); + } + } + for (s, (r, fr)) in self.shadings.iter().zip(&shading_refs) { + write_shading(&mut pdf, s, *r, *fr); + } + for (t, r) in self.tilings.iter().zip(&tiling_refs) { + let z = miniz_oxide::deflate::compress_to_vec_zlib(&t.content, 6); + let mut p = pdf.tiling_pattern(*r, &z); + p.filter(Filter::FlateDecode); + p.paint_type(pdf_writer::types::PaintType::Colored); + p.tiling_type(pdf_writer::types::TilingType::ConstantSpacing); + let [x0, y0, x1, y1] = t.bbox; + p.bbox(Rect::new(f(x0), f(y0), f(x1), f(y1))); + p.x_step(f(t.step.0)); + p.y_step(f(t.step.1)); + p.matrix(t.matrix.0.map(f)); + let mut res = p.resources(); + resources(&mut res); + res.finish(); + p.finish(); + } + pdf.finish() + } +} + +fn set_space(cs: pdf_writer::writers::ColorSpace<'_>, s: OutSpace) { + match s { + OutSpace::Gray => cs.device_gray(), + OutSpace::Rgb => cs.device_rgb(), + OutSpace::Cmyk => cs.device_cmyk(), + } +} + +fn write_shading(pdf: &mut Pdf, s: &Shading, r: Ref, fr: Ref) { + use pdf_writer::types::FunctionShadingType; + use pdf_writer::writers::StreamShadingType; + let n = s.space.comps(); + let range: Vec = (0..n).flat_map(|_| [0.0, 1.0]).collect(); + let samples = i32::try_from(s.samples.max(2)).unwrap_or(2); + match &s.kind { + ShadeKind::Axial(_) | ShadeKind::Radial(_) | ShadeKind::Function { .. } => { + { + let mut func = pdf.sampled_function(fr, &s.data); + if let ShadeKind::Function { domain, .. } = &s.kind { + func.domain(domain.map(f)); + func.size([samples, samples]); + } else { + func.domain([0.0, 1.0]); + func.size([samples]); + } + func.range(range.iter().copied()); + func.bits_per_sample(8); + } + let mut sh = pdf.function_shading(r); + match &s.kind { + ShadeKind::Axial(c) => { + sh.shading_type(FunctionShadingType::Axial); + sh.coords(c.map(f)); + sh.extend(s.extend); + } + ShadeKind::Radial(c) => { + sh.shading_type(FunctionShadingType::Radial); + sh.coords(c.map(f)); + sh.extend(s.extend); + } + ShadeKind::Function { domain, matrix } => { + sh.shading_type(FunctionShadingType::Function); + sh.domain(domain.map(f)); + sh.matrix(matrix.0.map(f)); + } + _ => {} + } + set_space(sh.color_space(), s.space); + sh.function(fr); + } + ShadeKind::Triangles | ShadeKind::Coons | ShadeKind::Tensor => { + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for (x, y) in &s.points { + x0 = x0.min(*x); + y0 = y0.min(*y); + x1 = x1.max(*x); + y1 = y1.max(*y); + } + if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) { + return; + } + let (x1, y1) = (x1.max(x0 + 1e-3), y1.max(y0 + 1e-3)); + let q = |v: f64, lo: f64, hi: f64| (((v - lo) / (hi - lo)).clamp(0.0, 1.0) * f64::from(u32::MAX)).round() as u32; + let mut data = Vec::new(); + let (per, cols) = match s.kind { + ShadeKind::Triangles => (1, 1), + ShadeKind::Coons => (12, 4), + _ => (16, 4), + }; + let colors: Vec<&[u8]> = s.data.chunks(n).collect(); + for (i, chunk) in s.points.chunks(per).enumerate() { + if chunk.len() != per { + break; + } + data.push(0u8); + for (x, y) in chunk { + data.extend(q(*x, x0, x1).to_be_bytes()); + data.extend(q(*y, y0, y1).to_be_bytes()); + } + for k in 0..cols { + data.extend_from_slice(colors.get(i * cols + k).copied().unwrap_or(&[])); + } + } + let z = miniz_oxide::deflate::compress_to_vec_zlib(&data, 6); + let mut sh = pdf.stream_shading(r, &z); + sh.filter(Filter::FlateDecode); + sh.shading_type(match s.kind { + ShadeKind::Triangles => StreamShadingType::FreeformGouraud, + ShadeKind::Coons => StreamShadingType::CoonsPatch, + _ => StreamShadingType::TensorProductPatch, + }); + set_space(sh.color_space(), s.space); + sh.bits_per_coordinate(32); + sh.bits_per_component(8); + sh.bits_per_flag(8); + let mut decode = vec![f(x0), f(x1), f(y0), f(y1)]; + decode.extend(range); + sh.decode(decode); + } + } +} diff --git a/crates/ps/src/read/scan.rs b/crates/ps/src/read/scan.rs new file mode 100644 index 0000000000..9f6aa14c3b --- /dev/null +++ b/crates/ps/src/read/scan.rs @@ -0,0 +1,375 @@ +//! The scanner: turns a file's bytes into objects, building procedures `{ … }` whole. + +use crate::read::obj::{Obj, PArr, PStr, name}; +use crate::read::source::Sources; + +/// How deeply procedures may nest. +const MAX_NESTING: usize = 1000; +/// The longest string or name token. +const MAX_TOKEN: usize = 64 << 20; + +pub enum Token { + Obj(Obj), + /// `//name`: replaced by its value when scanned. + Immediate(Vec), +} + +pub fn is_ws(c: u8) -> bool { + matches!(c, 0 | b'\t' | b'\n' | 0x0c | b'\r' | b' ') +} + +pub fn is_delim(c: u8) -> bool { + matches!(c, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +/// One token from `src`, or None at its end. Procedures come back whole, as executable arrays; +/// `//name` inside them is resolved through `resolve`. +pub fn next(srcs: &mut Sources, src: usize, resolve: &mut dyn FnMut(&[u8]) -> Option) -> Result, String> { + let mut stack: Vec> = Vec::new(); + loop { + let Some(tok) = token(srcs, src)? else { + return if stack.is_empty() { Ok(None) } else { Err("unterminated procedure".into()) }; + }; + let obj = match tok { + Token::Obj(Obj::Name(n, true)) if &*n == b"{" => { + if stack.len() >= MAX_NESTING { + return Err("procedures nest too deeply".into()); + } + stack.push(Vec::new()); + continue; + } + Token::Obj(Obj::Name(n, true)) if &*n == b"}" => { + let Some(body) = stack.pop() else { return Err("unmatched }".into()) }; + Obj::Array(PArr::new(body), true) + } + Token::Obj(o) => o, + Token::Immediate(n) => resolve(&n).ok_or_else(|| format!("undefined //{}", String::from_utf8_lossy(&n)))?, + }; + match stack.last_mut() { + Some(body) => body.push(obj), + None => return Ok(Some(obj)), + } + } +} + +fn token(srcs: &mut Sources, src: usize) -> Result, String> { + // Whitespace and comments. + let c = loop { + let Some(c) = srcs.read(src) else { return Ok(None) }; + if is_ws(c) { + continue; + } + if c == b'%' { + while let Some(c) = srcs.read(src) { + if c == b'\n' || c == b'\r' { + break; + } + } + continue; + } + break c; + }; + match c { + b'(' => string(srcs, src).map(|s| Some(Token::Obj(Obj::Str(PStr::new(s), false)))), + b'<' => match srcs.read(src) { + Some(b'<') => Ok(Some(Token::Obj(Obj::Name(name(b"<<"), true)))), + Some(b'~') => ascii85(srcs, src).map(|s| Some(Token::Obj(Obj::Str(PStr::new(s), false)))), + Some(c) => { + srcs.unread(src); + let _ = c; + hex(srcs, src).map(|s| Some(Token::Obj(Obj::Str(PStr::new(s), false)))) + } + None => Err("unterminated hex string".into()), + }, + b'>' => match srcs.read(src) { + Some(b'>') => Ok(Some(Token::Obj(Obj::Name(name(b">>"), true)))), + _ => Err("stray >".into()), + }, + b'[' | b']' | b'{' | b'}' => Ok(Some(Token::Obj(Obj::Name(name(&[c]), true)))), + b')' => Err("stray )".into()), + b'/' => { + let immediate = srcs.peek(src) == Some(b'/'); + if immediate { + srcs.read(src); + } + let n = regular(srcs, src, None)?; + Ok(Some(if immediate { Token::Immediate(n) } else { Token::Obj(Obj::Name(name(&n), false)) })) + } + _ => { + let t = regular(srcs, src, Some(c))?; + Ok(Some(Token::Obj(number(&t).unwrap_or_else(|| Obj::Name(name(&t), true))))) + } + } +} + +/// A run of regular characters. The whitespace character that ends it is consumed (a CR LF +/// pair as one), a delimiter is left for the next token. +fn regular(srcs: &mut Sources, src: usize, first: Option) -> Result, String> { + let mut t: Vec = first.into_iter().collect(); + while let Some(c) = srcs.read(src) { + if is_ws(c) { + if c == b'\r' && srcs.peek(src) == Some(b'\n') { + srcs.read(src); + } + break; + } + if is_delim(c) { + srcs.unread(src); + break; + } + t.push(c); + if t.len() > MAX_TOKEN { + return Err("token too long".into()); + } + } + Ok(t) +} + +fn string(srcs: &mut Sources, src: usize) -> Result, String> { + let mut out = Vec::new(); + let mut depth = 0usize; + loop { + let c = srcs.read(src).ok_or("unterminated string")?; + match c { + b'(' => { + depth += 1; + out.push(c); + } + b')' => { + if depth == 0 { + return Ok(out); + } + depth -= 1; + out.push(c); + } + b'\\' => { + let e = srcs.read(src).ok_or("unterminated string")?; + match e { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'b' => out.push(8), + b'f' => out.push(12), + b'\r' => { + if srcs.peek(src) == Some(b'\n') { + srcs.read(src); + } + } + b'\n' => {} + b'0'..=b'7' => { + let mut v = u32::from(e - b'0'); + for _ in 0..2 { + match srcs.peek(src) { + Some(d @ b'0'..=b'7') => { + srcs.read(src); + v = v * 8 + u32::from(d - b'0'); + } + _ => break, + } + } + out.push((v & 0xFF) as u8); + } + other => out.push(other), + } + } + // An end of line inside a string is a newline, whatever its form. + b'\r' => { + if srcs.peek(src) == Some(b'\n') { + srcs.read(src); + } + out.push(b'\n'); + } + _ => out.push(c), + } + if out.len() > MAX_TOKEN { + return Err("string too long".into()); + } + } +} + +fn hex(srcs: &mut Sources, src: usize) -> Result, String> { + let mut out = Vec::new(); + let mut hi: Option = None; + loop { + let c = srcs.read(src).ok_or("unterminated hex string")?; + if c == b'>' { + break; + } + if is_ws(c) { + continue; + } + let v = match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + b'A'..=b'F' => c - b'A' + 10, + _ => return Err("bad hex string".into()), + }; + match hi.take() { + Some(h) => out.push(h << 4 | v), + None => hi = Some(v), + } + if out.len() > MAX_TOKEN { + return Err("string too long".into()); + } + } + if let Some(h) = hi { + out.push(h << 4); + } + Ok(out) +} + +fn ascii85(srcs: &mut Sources, src: usize) -> Result, String> { + let mut out = Vec::new(); + let mut group = [0u64; 5]; + let mut n = 0; + loop { + let c = srcs.read(src).ok_or("unterminated ASCII85 string")?; + if is_ws(c) { + continue; + } + if c == b'~' { + if srcs.read(src) != Some(b'>') { + return Err("bad ASCII85 end".into()); + } + break; + } + if c == b'z' && n == 0 { + out.extend([0; 4]); + continue; + } + if !(b'!'..=b'u').contains(&c) { + return Err("bad ASCII85 string".into()); + } + if let Some(g) = group.get_mut(n) { + *g = u64::from(c - b'!'); + } + n += 1; + if n == 5 { + let v = group.iter().fold(0u64, |a, d| a * 85 + d); + out.extend(u32::try_from(v).map_err(|_| "ASCII85 overflow")?.to_be_bytes()); + n = 0; + } + if out.len() > MAX_TOKEN { + return Err("string too long".into()); + } + } + if n > 1 { + for g in group.iter_mut().skip(n) { + *g = 84; + } + let v = group.iter().fold(0u64, |a, d| a * 85 + d).min(u64::from(u32::MAX)); + let v = u32::try_from(v).unwrap_or(u32::MAX); + out.extend(v.to_be_bytes().iter().take(n - 1)); + } + Ok(out) +} + +/// An integer, radix number (`16#FF`) or real; None for anything else. +pub fn number(t: &[u8]) -> Option { + let s = std::str::from_utf8(t).ok()?; + let first = *t.first()?; + if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) { + return None; + } + if let Some((base, digits)) = s.split_once('#') { + let base: u32 = base.parse().ok()?; + if !(2..=36).contains(&base) || digits.is_empty() { + return None; + } + let v = u64::from_str_radix(digits, base).ok()?; + // Radix numbers are unsigned 32-bit patterns. + return Some(Obj::Int(i64::from(v as u32 as i32))); + } + let digits_only = s.strip_prefix(['+', '-']).unwrap_or(s); + if !digits_only.is_empty() && digits_only.bytes().all(|b| b.is_ascii_digit()) { + return Some(match s.parse::() { + Ok(i) if i32::try_from(i).is_ok() => Obj::Int(i), + _ => Obj::Real(s.parse::().ok()?), + }); + } + // Reals: digits with a point and/or an exponent; nothing else (`1e` or `.` alone are names). + let mut seen_digit = false; + let mut seen_e = false; + for (i, b) in digits_only.bytes().enumerate() { + match b { + b'0'..=b'9' => seen_digit = true, + b'.' if !seen_e => {} + b'e' | b'E' if seen_digit && !seen_e => seen_e = true, + b'+' | b'-' if seen_e && matches!(digits_only.as_bytes().get(i.wrapping_sub(1)), Some(b'e' | b'E')) => {} + _ => return None, + } + } + if !seen_digit || digits_only.ends_with(['e', 'E', '+', '-']) { + return None; + } + let v: f64 = s.parse().ok()?; + v.is_finite().then_some(Obj::Real(v)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::read::source::Source; + + fn all(text: &[u8]) -> Vec { + let mut s = Sources::default(); + let id = s.add(Source::bytes(text.to_vec())); + let mut out = Vec::new(); + while let Some(o) = next(&mut s, id, &mut |_| Some(Obj::Int(42))).unwrap() { + out.push(o); + } + out + } + + #[test] + fn scans_the_token_kinds() { + let t = all(b"12 -3.5 1e3 16#FF /lit name (a\\(b\\)\\101\\\n c) <41 42> <~87cURDZ~> {1 {2} add} //x [ ] << >> % note\n.5 1.e2 -."); + let kinds: Vec = t + .iter() + .map(|o| match o { + Obj::Int(i) => format!("i{i}"), + Obj::Real(r) => format!("r{r}"), + Obj::Name(n, x) => format!("{}{}", if *x { "x" } else { "/" }, String::from_utf8_lossy(n)), + Obj::Str(s, _) => format!("s{}", String::from_utf8_lossy(&s.bytes())), + Obj::Array(a, true) => format!("p{}", a.len), + _ => "?".into(), + }) + .collect(); + assert_eq!( + kinds, + [ + "i12", "r-3.5", "r1000", "i255", "/lit", "xname", "sa(b)A c", "sAB", "sHello", "p3", "i42", "x[", "x]", "x<<", "x>>", "r0.5", "r100", + "x-." + ] + ); + } + + #[test] + fn a_token_ending_in_whitespace_consumes_it() { + let mut s = Sources::default(); + let id = s.add(Source::bytes(b"image\r\nDATA".to_vec())); + let _ = next(&mut s, id, &mut |_| None).unwrap(); + assert_eq!(s.read(id), Some(b'D')); + } + + #[test] + fn malformed_input_is_an_error() { + for bad in [&b"(open"[..], b"<4g>", b"{ 1 2", b"}", b"<~ab~x"] { + let mut s = Sources::default(); + let id = s.add(Source::bytes(bad.to_vec())); + let mut r = Ok(None); + for _ in 0..5 { + r = next(&mut s, id, &mut |_| None); + if r.is_err() { + break; + } + } + assert!(r.is_err(), "{}", String::from_utf8_lossy(bad)); + } + // Deep nesting is refused, not a stack overflow. + let deep = vec![b'{'; 5000]; + let mut s = Sources::default(); + let id = s.add(Source::bytes(deep)); + assert!(next(&mut s, id, &mut |_| None).is_err()); + } +} diff --git a/crates/ps/src/read/source.rs b/crates/ps/src/read/source.rs new file mode 100644 index 0000000000..c2f6c8246e --- /dev/null +++ b/crates/ps/src/read/source.rs @@ -0,0 +1,986 @@ +//! Files: the program itself, strings run as code, decoding filters and `eexec` sections. +//! +//! Filters decode as they are read, so a filter made over `currentfile` before the operator +//! that consumes it (`currentfile /ASCII85Decode filter … image`) reads the data that follows +//! that operator. A filter takes from the file beneath only what its encoding needs: bytes a +//! decompressor fetched past its end are pushed back, so the program carries on after the data. + +use std::collections::VecDeque; +use std::rc::Rc; + +/// The most bytes one filter may decode to, and one reusable stream may hold. +const MAX_DECODED: usize = 256 << 20; +/// How deep files may sit on one another. +const MAX_CHAIN: usize = 16; + +pub enum Dec { + Hex { + hi: Option, + }, + A85 { + group: [u8; 5], + n: usize, + first: bool, + }, + RunLength, + Lzw { + dec: Box, + pending: Vec, + }, + Flate { + state: Box, + pending: Vec, + }, + SubFile { + eod: Vec, + count: usize, + left: Option, + skip_on_pop: bool, + window: VecDeque, + }, + /// JPEG data: only images take it (whole, as it is). + Dct, +} + +pub enum Kind { + Bytes(Rc>), + /// A window onto a string's storage, read in place (`token`, executing a string). + Shared { + buf: Rc>>, + off: usize, + len: usize, + }, + /// Decrypting `eexec` over another file. `hex` is decided by the first four bytes. + Eexec { + up: usize, + r: u16, + hex: Option, + skipped: u8, + }, + Filter { + up: usize, + dec: Dec, + out: VecDeque, + done: bool, + produced: usize, + }, +} + +pub struct Source { + pub kind: Kind, + pub pos: usize, + pub closed: bool, + /// Raw JPEG data for a DCTDecode filter, once taken. + pub dct: Option>>, + /// The last byte given, and bytes pushed back (read again first; the last pushed first). + pub last: Option, + pub back: Vec, + /// A PNG or TIFF predictor under Flate or LZW. + pub predictor: Option, +} + +impl Source { + pub fn bytes(data: Vec) -> Self { + Self::shared(Rc::new(data)) + } + + pub fn shared(data: Rc>) -> Self { + Self::of(Kind::Bytes(data)) + } + + /// A string read in place, without copying it. + pub fn string(s: &crate::read::obj::PStr) -> Self { + Self::of(Kind::Shared { buf: s.buf.clone(), off: s.off, len: s.len }) + } + + pub fn eexec(up: usize) -> Self { + Self::of(Kind::Eexec { up, r: 55665, hex: None, skipped: 0 }) + } + + fn of(kind: Kind) -> Self { + Source { kind, pos: 0, closed: false, dct: None, last: None, back: Vec::new(), predictor: None } + } +} + +fn is_ws(c: u8) -> bool { + matches!(c, 0 | b'\t' | b'\n' | 0x0c | b'\r' | b' ') +} + +fn hex_val(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } +} + +#[derive(Debug, Default)] +pub struct FilterParams { + pub early_change: bool, + pub predictor: i64, + pub colors: i64, + pub bpc: i64, + pub columns: i64, + pub eod_count: usize, + pub eod_string: Vec, +} + +#[derive(Debug, Clone)] +pub struct Predictor { + kind: i64, + bpp: usize, + row: usize, + prev: Vec, + cur: Vec, +} + +/// The sources, read through one another (`eexec` over the program, filters over both). +pub struct Sources { + pub list: Vec, + /// Bytes read so far, at every level (a filter's input and its output both count): the + /// interpreter charges them as work. + pub read: u64, + /// The most bytes that may be read; past it every file is at its end and `exhausted` is set. + pub max_read: u64, + pub exhausted: bool, +} + +impl Default for Sources { + fn default() -> Self { + Sources { list: Vec::new(), read: 0, max_read: u64::MAX, exhausted: false } + } +} + +impl Sources { + pub fn add(&mut self, s: Source) -> usize { + self.list.push(s); + self.list.len() - 1 + } + + pub fn is_subfile_filter(&self, id: usize) -> bool { + self.list.get(id).is_some_and(|source| matches!(&source.kind, Kind::Filter { dec: Dec::SubFile { skip_on_pop: true, .. }, .. })) + } + + pub fn read(&mut self, id: usize) -> Option { + self.read_depth(id, 0) + } + + fn read_depth(&mut self, id: usize, depth: usize) -> Option { + if self.read >= self.max_read { + self.exhausted = true; + return None; + } + let c = self.read_inner(id, depth); + if c.is_some() { + self.read += 1; + } + c + } + + fn read_inner(&mut self, id: usize, depth: usize) -> Option { + if depth > MAX_CHAIN { + return None; + } + let src = self.list.get_mut(id)?; + if src.closed { + return None; + } + if let Some(c) = src.back.pop() { + src.last = Some(c); + return Some(c); + } + let c = match &mut src.kind { + Kind::Bytes(data) => { + let c = data.get(src.pos).copied(); + if c.is_some() { + src.pos += 1; + } + return c; + } + Kind::Shared { buf, off, len } => { + let c = if src.pos < *len { off.checked_add(src.pos).and_then(|i| buf.borrow().get(i).copied()) } else { None }; + if c.is_some() { + src.pos += 1; + } + return c; + } + Kind::Eexec { .. } => self.read_eexec(id, depth), + Kind::Filter { .. } => self.read_filter(id, depth), + }; + if let Some(s) = self.list.get_mut(id) { + s.last = c; + if c.is_some() { + s.pos += 1; + } + } + c + } + + fn read_eexec(&mut self, id: usize, depth: usize) -> Option { + let Some(Source { kind: Kind::Eexec { up, hex, .. }, .. }) = self.list.get(id) else { return None }; + let (up, hex) = (*up, *hex); + let hex = match hex { + Some(h) => h, + None => { + let h = self.leading_hex(up, depth)?; + if let Some(Source { kind: Kind::Eexec { hex, .. }, .. }) = self.list.get_mut(id) { + *hex = Some(h); + } + h + } + }; + loop { + let cipher = if hex { + let mut digits = [0u8; 2]; + let mut n = 0; + while n < 2 { + let c = self.read_depth(up, depth + 1)?; + if is_ws(c) { + continue; + } + digits[n] = hex_val(c)?; + n += 1; + } + digits[0] << 4 | digits[1] + } else { + self.read_depth(up, depth + 1)? + }; + let Some(Source { kind: Kind::Eexec { r, skipped, .. }, .. }) = self.list.get_mut(id) else { return None }; + let plain = cipher ^ (*r >> 8) as u8; + *r = (u16::from(cipher).wrapping_add(*r)).wrapping_mul(52845).wrapping_add(22719); + // The first four plain bytes are random. + if *skipped < 4 { + *skipped += 1; + continue; + } + return Some(plain); + } + } + + /// Whether the next four bytes after whitespace are hex digits (the whitespace is consumed + /// when they are; the four bytes are pushed back either way). + fn leading_hex(&mut self, up: usize, depth: usize) -> Option { + let mut skipped = Vec::new(); + let first = loop { + let c = self.read_depth(up, depth + 1)?; + if !is_ws(c) { + break c; + } + skipped.push(c); + }; + let mut four = vec![first]; + while four.len() < 4 { + match self.read_depth(up, depth + 1) { + Some(c) => four.push(c), + None => break, + } + } + let hex = four.len() == 4 && four.iter().all(|c| hex_val(*c).is_some()); + self.unread_many(up, &four); + if !hex { + self.unread_many(up, &skipped); + } + Some(hex) + } + + /// Push bytes back so they are read again, in order. + pub fn unread_many(&mut self, id: usize, bytes: &[u8]) { + let Some(src) = self.list.get_mut(id) else { return }; + match src.kind { + Kind::Bytes(_) | Kind::Shared { .. } if src.back.is_empty() => src.pos = src.pos.saturating_sub(bytes.len()), + _ => src.back.extend(bytes.iter().rev()), + } + } + + /// Step back over the byte just read (the scanner's look-ahead). + pub fn unread(&mut self, id: usize) { + let Some(src) = self.list.get_mut(id) else { return }; + match src.kind { + Kind::Bytes(_) | Kind::Shared { .. } if src.back.is_empty() => src.pos = src.pos.saturating_sub(1), + _ => { + if let Some(c) = src.last { + src.back.push(c); + } + } + } + } + + pub fn peek(&mut self, id: usize) -> Option { + let c = self.read(id)?; + self.unread(id); + Some(c) + } + + /// Build a decoding source without retaining it, so the interpreter can charge its memory + /// budget before registering the source. + pub fn filter(&mut self, up: usize, name: &[u8], p: &FilterParams, max_owned: usize) -> Result<(Source, usize), String> { + let dec = match name { + b"ASCIIHexDecode" | b"AHx" => Dec::Hex { hi: None }, + b"ASCII85Decode" | b"A85" => Dec::A85 { group: [0; 5], n: 0, first: true }, + b"RunLengthDecode" | b"RL" => Dec::RunLength, + b"LZWDecode" | b"LZW" => { + let dec = if p.early_change { + weezl::decode::Decoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8) + } else { + weezl::decode::Decoder::new(weezl::BitOrder::Msb, 8) + }; + Dec::Lzw { dec: Box::new(dec), pending: Vec::new() } + } + b"FlateDecode" | b"Fl" => { + Dec::Flate { state: miniz_oxide::inflate::stream::InflateState::new_boxed(miniz_oxide::DataFormat::Zlib), pending: Vec::new() } + } + b"DCTDecode" | b"DCT" => Dec::Dct, + b"SubFileDecode" => Dec::SubFile { + eod: p.eod_string.clone(), + count: p.eod_count, + // A byte count; with no count and no end string, everything passes through. + left: (p.eod_string.is_empty() && p.eod_count > 0).then_some(p.eod_count), + skip_on_pop: true, + window: VecDeque::new(), + }, + b"NullEncode" => Dec::SubFile { eod: Vec::new(), count: 0, left: None, skip_on_pop: false, window: VecDeque::new() }, + b"ReusableStreamDecode" => { + // Reads its data when made, and can be read again (`resetfile`, positions). + let mut data = Vec::new(); + while let Some(c) = self.read(up) { + let next = data.len().saturating_add(1); + if next > MAX_DECODED || next > max_owned { + return Err("out of memory".into()); + } + if next > data.capacity() { + let target = next.saturating_add(4095).min(max_owned).min(MAX_DECODED); + data.try_reserve_exact(target.saturating_sub(data.len())).map_err(|_| "out of memory")?; + } + data.push(c); + } + // The capacity is retained by the reusable byte source, so charge it rather + // than only the initialized bytes. + let bytes = data.capacity(); + return Ok((Source::bytes(data), bytes)); + } + _ => return Err(format!("unsupported filter {}", String::from_utf8_lossy(name))), + }; + let mut s = Source::of(Kind::Filter { up, dec, out: VecDeque::new(), done: false, produced: 0 }); + if p.predictor > 1 && matches!(name, b"FlateDecode" | b"Fl" | b"LZWDecode" | b"LZW") { + let colors = usize::try_from(p.colors.clamp(1, 32)).unwrap_or(1); + let bpc = usize::try_from(p.bpc.clamp(1, 16)).unwrap_or(8); + let columns = usize::try_from(p.columns.clamp(1, 1 << 20)).unwrap_or(1); + let row = (colors * bpc * columns).div_ceil(8); + if row > max_owned { + return Err("out of memory".into()); + } + let mut prev = Vec::new(); + prev.try_reserve_exact(row).map_err(|_| "out of memory")?; + prev.resize(row, 0); + s.predictor = Some(Predictor { kind: p.predictor, bpp: (colors * bpc).div_ceil(8).max(1), row, prev, cur: Vec::new() }); + return Ok((s, row)); + } + Ok((s, 0)) + } + + fn read_filter(&mut self, id: usize, depth: usize) -> Option { + loop { + let src = self.list.get_mut(id)?; + let Kind::Filter { out, done, .. } = &mut src.kind else { return None }; + if let Some(c) = out.pop_front() { + return Some(c); + } + if *done { + return None; + } + if !self.fill(id, depth) + && let Some(Source { kind: Kind::Filter { done, .. }, .. }) = self.list.get_mut(id) + { + // What the last step produced is still read first. + *done = true; + } + } + } + + /// Decode some more of filter `id`; false once its data has ended. + #[allow(clippy::cognitive_complexity, reason = "one streaming decoder state machine preserves filter read-ahead and predictor ordering")] + fn fill(&mut self, id: usize, depth: usize) -> bool { + let Some(Source { kind: Kind::Filter { up, dec, .. }, .. }) = self.list.get(id) else { return false }; + let up = *up; + let mut produced: Vec = Vec::new(); + let mut more = true; + match dec { + Dec::Dct => more = false, + Dec::Hex { hi } => { + let mut hi = *hi; + while produced.is_empty() { + let Some(c) = self.read_depth(up, depth + 1) else { + more = false; + break; + }; + if c == b'>' { + more = false; + break; + } + let Some(v) = hex_val(c) else { continue }; + match hi.take() { + Some(h) => produced.push(h << 4 | v), + None => hi = Some(v), + } + } + if !more && let Some(h) = hi.take() { + produced.push(h << 4); + } + if let Some(Source { kind: Kind::Filter { dec: Dec::Hex { hi: slot }, .. }, .. }) = self.list.get_mut(id) { + *slot = hi; + } + } + Dec::A85 { group, n, first } => { + let (mut group, mut n, mut first) = (*group, *n, *first); + while produced.is_empty() { + let Some(c) = self.read_depth(up, depth + 1) else { + more = false; + break; + }; + if is_ws(c) { + continue; + } + if c == b'<' && first { + // A leading `<~` is optional; `<` is itself a valid ASCII85 digit. + let next = self.read_depth(up, depth + 1); + if next == Some(b'~') { + first = false; + continue; + } + if next.is_some() { + self.unread(up); + } + } + first = false; + if c == b'~' { + let _ = self.read_depth(up, depth + 1); + more = false; + break; + } + if c == b'z' && n == 0 { + produced.extend([0; 4]); + continue; + } + if !(b'!'..=b'u').contains(&c) { + more = false; + break; + } + if let Some(slot) = group.get_mut(n) { + *slot = c - b'!'; + } + n += 1; + if n == 5 { + let v = group.iter().fold(0u64, |a, &d| a * 85 + u64::from(d)).min(u64::from(u32::MAX)); + produced.extend(u32::try_from(v).unwrap_or(u32::MAX).to_be_bytes()); + n = 0; + } + } + if !more && n > 1 { + for slot in group.iter_mut().skip(n) { + *slot = 84; + } + let v = group.iter().fold(0u64, |a, &d| a * 85 + u64::from(d)).min(u64::from(u32::MAX)); + produced.extend(u32::try_from(v).unwrap_or(u32::MAX).to_be_bytes().iter().take(n - 1)); + n = 0; + } + if let Some(Source { kind: Kind::Filter { dec: Dec::A85 { group: g, n: nn, first: f }, .. }, .. }) = self.list.get_mut(id) { + *g = group; + *nn = n; + *f = first; + } + } + Dec::RunLength => match self.read_depth(up, depth + 1) { + None | Some(128) => more = false, + Some(len @ 0..=127) => { + for _ in 0..=len { + match self.read_depth(up, depth + 1) { + Some(c) => produced.push(c), + None => { + more = false; + break; + } + } + } + } + Some(len) => match self.read_depth(up, depth + 1) { + Some(c) => produced.extend(std::iter::repeat_n(c, 257 - usize::from(len))), + None => more = false, + }, + }, + Dec::SubFile { eod, count, left, window, .. } => { + let (eod, mut count, mut left, mut window) = (eod.clone(), *count, *left, window.clone()); + if let Some(n) = left.as_mut() { + if *n == 0 { + more = false; + } else if let Some(c) = self.read_depth(up, depth + 1) { + *n -= 1; + produced.push(c); + } else { + more = false; + } + } else if eod.is_empty() { + match self.read_depth(up, depth + 1) { + Some(c) => produced.push(c), + None => more = false, + } + } else { + while produced.is_empty() && more { + let Some(c) = self.read_depth(up, depth + 1) else { + produced.extend(window.drain(..)); + more = false; + break; + }; + window.push_back(c); + if window.len() >= eod.len() && window.iter().skip(window.len() - eod.len()).eq(eod.iter()) { + if count == 0 { + let keep = window.len() - eod.len(); + produced.extend(window.drain(..keep)); + window.clear(); + more = false; + break; + } + count -= 1; + if count == 0 { + // Positive EODCount includes the Nth terminating occurrence. + produced.extend(window.drain(..)); + more = false; + break; + } + } + while window.len() > eod.len() { + if let Some(b) = window.pop_front() { + produced.push(b); + } + } + } + } + if let Some(Source { kind: Kind::Filter { dec: Dec::SubFile { count: c, left: l, window: w, .. }, .. }, .. }) = self.list.get_mut(id) + { + *c = count; + *l = left; + *w = window; + } + } + Dec::Flate { .. } | Dec::Lzw { .. } => { + // Feed what is pending, or a chunk from beneath; keep what wasn't used. + let mut input = match self.list.get_mut(id).map(|s| &mut s.kind) { + Some(Kind::Filter { dec: Dec::Flate { pending, .. } | Dec::Lzw { pending, .. }, .. }) => std::mem::take(pending), + _ => Vec::new(), + }; + let mut eof = false; + if input.is_empty() { + while input.len() < 4096 { + match self.read_depth(up, depth + 1) { + Some(c) => input.push(c), + None => { + eof = true; + break; + } + } + } + } + let mut buf = vec![0u8; 64 * 1024]; + let (used, written, finished) = match self.list.get_mut(id).map(|s| &mut s.kind) { + Some(Kind::Filter { dec: Dec::Flate { state, .. }, .. }) => { + let r = miniz_oxide::inflate::stream::inflate(state, &input, &mut buf, miniz_oxide::MZFlush::None); + let finished = matches!(r.status, Ok(miniz_oxide::MZStatus::StreamEnd) | Err(_)); + (r.bytes_consumed, r.bytes_written, finished) + } + Some(Kind::Filter { dec: Dec::Lzw { dec, .. }, .. }) => { + // One byte at a time: the decoder must not read past its end code. + let (mut used, mut written, mut finished) = (0, 0, false); + while used < input.len() && written + 4096 < buf.len() { + let r = dec.decode_bytes(input.get(used..used + 1).unwrap_or(&[]), buf.get_mut(written..).unwrap_or(&mut [])); + used += r.consumed_in; + written += r.consumed_out; + if matches!(r.status, Ok(weezl::LzwStatus::Done) | Err(_)) { + finished = true; + break; + } + if r.consumed_in == 0 && r.consumed_out == 0 { + break; + } + } + (used, written, finished) + } + _ => (0, 0, true), + }; + produced.extend_from_slice(buf.get(..written).unwrap_or(&[])); + let rest = input.get(used..).unwrap_or(&[]).to_vec(); + if finished { + // The stream ended inside this chunk: what follows belongs to the file. + self.unread_many(up, &rest); + more = false; + } else if used == 0 && written == 0 && (eof || input.is_empty()) { + more = false; + } else if let Some(Source { kind: Kind::Filter { dec: Dec::Flate { pending, .. } | Dec::Lzw { pending, .. }, .. }, .. }) = + self.list.get_mut(id) + { + *pending = rest; + } + } + } + // Predictors work on whole rows. + let predicted = match self.list.get_mut(id).and_then(|s| s.predictor.as_mut()) { + Some(pr) => unpredict(pr, &produced, !more), + None => produced, + }; + let Some(Source { kind: Kind::Filter { out, produced: total, .. }, .. }) = self.list.get_mut(id) else { return false }; + *total = total.saturating_add(predicted.len()); + if *total > MAX_DECODED { + return false; + } + out.extend(predicted); + more + } + + /// The JPEG a DCTDecode filter reads: through its end marker when it sits on the program + /// itself, all of the filter beneath otherwise. + pub fn dct(&mut self, id: usize) -> Option>> { + let src = self.list.get(id)?; + if let Some(d) = &src.dct { + return Some(d.clone()); + } + let Kind::Filter { up, dec: Dec::Dct, .. } = &src.kind else { return None }; + let up = *up; + let direct = match self.list.get(up) { + Some(Source { kind: Kind::Bytes(data), pos, back, .. }) if back.is_empty() => Some((data.clone(), *pos)), + _ => None, + }; + let raw = match direct { + Some((data, pos)) => { + let rest = data.get(pos..).unwrap_or(&[]); + let end = jpeg_end(rest).unwrap_or(rest.len()); + if let Some(s) = self.list.get_mut(up) { + s.pos = s.pos.saturating_add(end); + } + rest.get(..end).unwrap_or(&[]).to_vec() + } + None => { + let mut raw = Vec::new(); + while let Some(c) = self.read(up) { + raw.push(c); + if raw.len() > MAX_DECODED { + break; + } + } + raw + } + }; + let raw = Rc::new(raw); + if let Some(s) = self.list.get_mut(id) { + s.dct = Some(raw.clone()); + } + Some(raw) + } + + pub fn is_filter(&self, id: usize) -> bool { + matches!(self.list.get(id).map(|s| &s.kind), Some(Kind::Filter { .. })) + } + + /// Read a filter to its end marker, so the file beneath carries on after the data. + pub fn drain(&mut self, id: usize) { + let mut n = 0usize; + while n < MAX_DECODED && self.read(id).is_some() { + n += 1; + } + } + + pub fn close(&mut self, id: usize) { + if let Some(s) = self.list.get_mut(id) { + s.closed = true; + } + } + + pub fn reset(&mut self, id: usize) { + if let Some(s) = self.list.get_mut(id) + && matches!(s.kind, Kind::Bytes(_) | Kind::Shared { .. }) + { + s.pos = 0; + s.back.clear(); + s.closed = false; + } + } + + pub fn position(&self, id: usize) -> Option { + let s = self.list.get(id)?; + Some(s.pos.saturating_sub(s.back.len())) + } + + pub fn set_position(&mut self, id: usize, pos: usize) -> bool { + match self.list.get_mut(id) { + Some(s) if matches!(&s.kind, Kind::Bytes(d) if pos <= d.len()) || matches!(&s.kind, Kind::Shared { len, .. } if pos <= *len) => { + s.pos = pos; + s.back.clear(); + s.closed = false; + true + } + _ => false, + } + } + + pub fn available(&self, id: usize) -> i64 { + match self.list.get(id) { + Some(s) if s.closed => -1, + Some(Source { kind: Kind::Bytes(d), pos, back, .. }) => i64::try_from(d.len().saturating_sub(*pos) + back.len()).unwrap_or(i64::MAX), + Some(Source { kind: Kind::Shared { len, .. }, pos, back, .. }) => { + i64::try_from(len.saturating_sub(*pos) + back.len()).unwrap_or(i64::MAX) + } + Some(_) => 1, + None => -1, + } + } +} + +/// Undo a predictor on newly decoded bytes (`last`: no more will come). +fn unpredict(p: &mut Predictor, data: &[u8], last: bool) -> Vec { + let mut out = Vec::new(); + if p.kind == 2 { + // TIFF: 8-bit horizontal differencing. + for &b in data { + p.cur.push(b); + if p.cur.len() == p.row { + for i in p.bpp..p.row { + let prev = p.cur.get(i - p.bpp).copied().unwrap_or(0); + if let Some(c) = p.cur.get_mut(i) { + *c = c.wrapping_add(prev); + } + } + out.append(&mut p.cur); + } + } + if last { + out.append(&mut p.cur); + } + return out; + } + // PNG: a filter byte before each row. + for &b in data { + p.cur.push(b); + if p.cur.len() == p.row + 1 { + let kind = p.cur.first().copied().unwrap_or(0); + let mut row: Vec = p.cur.get(1..).unwrap_or(&[]).to_vec(); + for i in 0..row.len() { + let a = if i >= p.bpp { row.get(i - p.bpp).copied().unwrap_or(0) } else { 0 }; + let up = p.prev.get(i).copied().unwrap_or(0); + let c = if i >= p.bpp { p.prev.get(i - p.bpp).copied().unwrap_or(0) } else { 0 }; + let add = match kind { + 1 => a, + 2 => up, + 3 => ((u16::from(a) + u16::from(up)) / 2) as u8, + 4 => { + let pp = i16::from(a) + i16::from(up) - i16::from(c); + let (pa, pb, pc) = ((pp - i16::from(a)).abs(), (pp - i16::from(up)).abs(), (pp - i16::from(c)).abs()); + if pa <= pb && pa <= pc { + a + } else if pb <= pc { + up + } else { + c + } + } + _ => 0, + }; + if let Some(v) = row.get_mut(i) { + *v = v.wrapping_add(add); + } + } + out.extend_from_slice(&row); + p.prev = row; + p.cur.clear(); + } + } + out +} + +/// The length of the JPEG at the start of `d` (through its EOI marker). +fn jpeg_end(d: &[u8]) -> Option { + if d.get(..2)? != [0xFF, 0xD8] { + return None; + } + let mut i = 2; + loop { + while d.get(i)? == &0xFF && d.get(i + 1)? == &0xFF { + i += 1; + } + if d.get(i)? != &0xFF { + return None; + } + let m = *d.get(i + 1)?; + i += 2; + match m { + 0xD9 => return Some(i), + 0x01 | 0xD0..=0xD7 => continue, + _ => { + let len = usize::from(u16::from_be_bytes([*d.get(i)?, *d.get(i + 1)?])); + i = i.checked_add(len)?; + if m == 0xDA { + // Entropy-coded data: up to the next marker that isn't a stuffed byte or restart. + loop { + if d.get(i)? == &0xFF { + let n = *d.get(i + 1)?; + if n != 0 && !(0xD0..=0xD7).contains(&n) { + break; + } + i += 2; + } else { + i += 1; + } + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn all(s: &mut Sources, id: usize) -> Vec { + let mut out = Vec::new(); + while let Some(c) = s.read(id) { + out.push(c); + } + out + } + + fn add_filter(s: &mut Sources, up: usize, name: &[u8], params: &FilterParams) -> usize { + let (source, _) = s.filter(up, name, params, usize::MAX).unwrap(); + s.add(source) + } + + #[test] + fn filter_owned_buffers_are_preflighted_against_memory_budget() { + let mut sources = Sources::default(); + let id = sources.add(Source::bytes(Vec::new())); + let predictor = FilterParams { predictor: 12, colors: 32, bpc: 16, columns: 1 << 20, ..Default::default() }; + assert!(matches!(sources.filter(id, b"FlateDecode", &predictor, 4096), Err(e) if e == "out of memory")); + + let id = sources.add(Source::bytes(vec![b'x'; 10])); + assert!(matches!(sources.filter(id, b"ReusableStreamDecode", &FilterParams::default(), 9), Err(e) if e == "out of memory")); + let id = sources.add(Source::bytes(vec![b'x'; 10])); + let (_, owned) = sources.filter(id, b"ReusableStreamDecode", &FilterParams::default(), 10).unwrap(); + assert_eq!(owned, 10); + } + + #[test] + fn filters_stop_at_their_end_markers() { + let mut s = Sources::default(); + let id = s.add(Source::bytes(b"48656c6c6f>rest".to_vec())); + let f = add_filter(&mut s, id, b"ASCIIHexDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"Hello"); + assert_eq!(all(&mut s, id), b"rest"); + let id = s.add(Source::bytes(b"87cURD]i,\"Ebo80~>rest".to_vec())); + let f = add_filter(&mut s, id, b"ASCII85Decode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"Hello World!"); + assert_eq!(all(&mut s, id), b"rest"); + let id = s.add(Source::bytes(b"rest".to_vec())); + let f = add_filter(&mut s, id, b"ASCII85Decode", &FilterParams::default()); + let value = 27u32 * 85u32.pow(4); + assert_eq!(all(&mut s, f), value.to_be_bytes()); + assert_eq!(all(&mut s, id), b"rest"); + let id = s.add(Source::bytes(vec![2, b'a', b'b', b'c', 254, b'x', 128, b'!'])); + let f = add_filter(&mut s, id, b"RunLengthDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"abcxxx"); + assert_eq!(all(&mut s, id), b"!"); + let id = s.add(Source::bytes(b"data%%EndBinary tail".to_vec())); + let p = FilterParams { eod_string: b"%%EndBinary".to_vec(), ..Default::default() }; + let f = add_filter(&mut s, id, b"SubFileDecode", &p); + assert_eq!(all(&mut s, f), b"data"); + assert_eq!(all(&mut s, id), b" tail"); + let id = s.add(Source::bytes(b"aENDtailENDrest".to_vec())); + let p = FilterParams { eod_count: 1, eod_string: b"END".to_vec(), ..Default::default() }; + let f = add_filter(&mut s, id, b"SubFileDecode", &p); + assert_eq!(all(&mut s, f), b"aEND"); + assert_eq!(all(&mut s, id), b"tailENDrest"); + } + + fn ascii85(data: &[u8]) -> String { + let mut out = String::new(); + for chunk in data.chunks(4) { + let mut b = [0u8; 4]; + b[..chunk.len()].copy_from_slice(chunk); + let mut v = u32::from_be_bytes(b); + let mut digits = [0u8; 5]; + for d in digits.iter_mut().rev() { + *d = (v % 85) as u8 + b'!'; + v /= 85; + } + out.push_str(std::str::from_utf8(&digits[..chunk.len() + 1]).unwrap()); + } + out + } + + #[test] + fn flate_and_lzw_read_only_their_streams() { + let mut z = miniz_oxide::deflate::compress_to_vec_zlib(&b"abcabcabc".repeat(2000), 6); + z.extend_from_slice(b"tail"); + let mut s = Sources::default(); + let id = s.add(Source::bytes(z)); + let f = add_filter(&mut s, id, b"FlateDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"abcabcabc".repeat(2000)); + assert_eq!(all(&mut s, id), b"tail"); + // Flate over ASCII85 over the program: bytes pushed back return to the filter beneath. + let z = miniz_oxide::deflate::compress_to_vec_zlib(b"xyz", 6); + let mut s = Sources::default(); + let id = s.add(Source::bytes(format!("{}~> after", ascii85(&z)).into_bytes())); + let a = add_filter(&mut s, id, b"ASCII85Decode", &FilterParams::default()); + let f = add_filter(&mut s, a, b"FlateDecode", &FilterParams::default()); + assert_eq!(all(&mut s, f), b"xyz"); + assert_eq!(all(&mut s, id), b" after"); + let mut enc = weezl::encode::Encoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8); + let mut l = enc.encode(b"lzw lzw lzw").unwrap(); + l.extend_from_slice(b"!"); + let mut s = Sources::default(); + let id = s.add(Source::bytes(l)); + let f = add_filter(&mut s, id, b"LZWDecode", &FilterParams { early_change: true, ..Default::default() }); + assert_eq!(all(&mut s, f), b"lzw lzw lzw"); + assert_eq!(all(&mut s, id), b"!"); + } + + #[test] + fn eexec_decrypts_binary_and_hex() { + let encrypt = |plain: &[u8]| { + let mut r: u16 = 55665; + let mut out = Vec::new(); + for &p in [0u8, 0, 0, 0].iter().chain(plain) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + out.push(c); + } + out + }; + let enc = encrypt(b"hello"); + for hex in [false, true] { + let data = if hex { enc.iter().map(|b| format!("{b:02x}")).collect::().into_bytes() } else { enc.clone() }; + let mut s = Sources::default(); + let up = s.add(Source::bytes(data)); + let e = s.add(Source::eexec(up)); + assert_eq!(s.peek(e), Some(b'h'), "look-ahead inside the section"); + let got: Vec = (0..5).filter_map(|_| s.read(e)).collect(); + assert_eq!(got, b"hello", "hex {hex}"); + } + } + + #[test] + fn broken_filter_data_ends_the_filter_not_the_program() { + for (name, data) in [ + (&b"ASCIIHexDecode"[..], &b"zz>"[..]), + (b"ASCII85Decode", b"\x7f~>"), + (b"FlateDecode", b"\x78\x9c\xff\xff"), + (b"RunLengthDecode", b"\x05a"), + (b"LZWDecode", b"\xff\xff\xff"), + ] { + let mut s = Sources::default(); + let id = s.add(Source::bytes(data.to_vec())); + let f = add_filter(&mut s, id, name, &FilterParams::default()); + let _ = all(&mut s, f); + } + let mut s = Sources::default(); + let id = s.add(Source::bytes(b"\xff\xd8\xff".to_vec())); + let f = add_filter(&mut s, id, b"DCTDecode", &FilterParams::default()); + assert!(s.dct(f).is_some()); + } +} diff --git a/crates/ps/src/read/tests.rs b/crates/ps/src/read/tests.rs new file mode 100644 index 0000000000..1520416597 --- /dev/null +++ b/crates/ps/src/read/tests.rs @@ -0,0 +1,755 @@ +//! End-to-end: EPS programs in, PDF content out. + +use super::*; + +/// The page content stream of a converted EPS, inflated. +fn content(pdf: &[u8]) -> String { + // The content stream is object 4, written right after the page. + let at = pdf.windows(7).position(|w| w == b"4 0 obj").expect("content object"); + let rest = &pdf[at..]; + let s = rest.windows(6).position(|w| w == b"stream").unwrap() + 6; + let s = s + if rest[s] == b'\r' { 2 } else { 1 }; + let e = rest.windows(9).position(|w| w == b"endstream").unwrap(); + let raw = miniz_oxide::inflate::decompress_to_vec_zlib(&rest[s..e]) + .unwrap_or_else(|_| miniz_oxide::inflate::decompress_to_vec_zlib(&rest[s..e - 1]).unwrap()); + String::from_utf8_lossy(&raw).into_owned() +} + +fn eps(body: &str) -> Vec { + format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 110 70\n%%EndComments\n{body}\n%%EOF\n").into_bytes() +} + +fn run(body: &str) -> (String, Converted) { + let c = eps_to_pdf(&eps(body), Limits::default()).unwrap(); + (content(&c.pdf), c) +} + +#[test] +fn eps_sections_and_deferred_bounding_boxes_use_craft_eps() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%HiResBoundingBox: (atend)\n%%BoundingBox: (atend)\n%%EndComments\n%%Trailer\n%%BoundingBox: 0 0 100 50\n%%HiResBoundingBox: 0.5 1.5 90.5 40.5\n"; + let wrapped = craft_eps::wrap(ps, Some(b"tiff"), None).unwrap(); + assert!(is_eps(&wrapped)); + assert_eq!(postscript_section(&wrapped), ps); + assert_eq!(bounding_box(ps), Some([0.5, 1.5, 90.5, 40.5])); +} + +#[test] +fn bounding_box_keeps_the_historical_256k_header_scan() { + let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); + ps.resize(ps.len() + (70 << 10), b' '); + ps.extend_from_slice(b"\n%%BoundingBox: 0 0 20 10\n%%EndComments\n"); + assert_eq!(craft_eps::Comments::read(&ps).page_box(), None); + assert_eq!(bounding_box(&ps), Some([0.0, 0.0, 20.0, 10.0])); +} + +#[test] +fn damaged_dos_preview_does_not_hide_the_executable_postscript() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n%%EndComments\n0 0 10 10 rectfill\n"; + let mut wrapped = craft_eps::wrap(ps, Some(b"tiff"), None).unwrap(); + wrapped[20..24].copy_from_slice(&u32::MAX.to_le_bytes()); + wrapped[24..28].copy_from_slice(&1u32.to_le_bytes()); + assert_eq!(postscript_section(&wrapped), ps); + assert!(craft_eps::sections(&wrapped).is_err()); + assert!(eps_to_pdf(&wrapped, Limits::default()).is_ok()); +} + +#[test] +fn paths_fill_and_stroke_in_their_colours() { + let (c, conv) = run("0 0 1 0 setcmykcolor 10 20 50 30 rectfill 1 0 0 setrgbcolor 2 setlinewidth newpath 10 20 moveto 100 60 lineto stroke"); + assert_eq!(conv.bbox, [10.0, 20.0, 110.0, 70.0]); + // The bounding box's corner moves to the page origin. + assert!(c.starts_with("1 0 0 1 -10 -20 cm"), "{c}"); + assert!(c.contains("0 0 1 0 k"), "CMYK stays CMYK: {c}"); + assert!(c.contains("10 20 m") && c.contains("f"), "{c}"); + assert!(c.contains("1 0 0 RG") && c.contains("2 w") && c.contains("S"), "{c}"); +} + +#[test] +fn procedures_loops_and_dictionaries_run() { + let (c, _) = run("/sq { newpath moveto 10 0 rlineto 0 10 rlineto -10 0 rlineto closepath fill } bind def + 0 1 2 { 15 mul 10 add 30 sq } for + /d 3 dict def d /n 7 put d /n get 7 eq { 0.5 setgray 60 20 5 5 rectfill } if + { 1 0 div } stopped { 0.25 setgray 70 20 5 5 rectfill } if + [ 1 2 3 ] { pop } forall 3 { } repeat 0 { 1 add dup 4 ge { exit } if } loop pop"); + assert_eq!(c.lines().filter(|l| *l == "f").count(), 5, "{c}"); + assert!(c.contains("0.5 g") && c.contains("0.25 g"), "{c}"); +} + +#[test] +fn integer_division_overflow_returns_zero() { + let (c, _) = run("-9223372036854775808 -1 idiv 0 eq { 10 20 5 5 rectfill } if + -9223372036854775808 -1 mod 0 eq { 20 20 5 5 rectfill } if"); + assert_eq!(c.lines().filter(|line| *line == "f").count(), 2, "{c}"); +} + +#[test] +fn copy_past_operand_limit_is_a_noop() { + let body = format!("10 20 5 5 rectfill {} 60000 copy 20 20 5 5 rectfill", "0 ".repeat(60_000)); + let compatible = eps_to_pdf(&eps(&body), Limits { stack_overflow_noop: true, ..Limits::default() }).unwrap(); + let compatible_content = content(&compatible.pdf); + assert_eq!(compatible_content.lines().filter(|line| *line == "f").count(), 2, "{compatible_content}"); + + let strict = eps_to_pdf(&eps(&body), Limits { keep_unpainted: true, ..Limits::default() }).unwrap(); + assert!(strict.warnings.iter().any(|warning| warning.contains("stackoverflow")), "{:?}", strict.warnings); + assert_eq!(content(&strict.pdf).lines().filter(|line| *line == "f").count(), 1); +} + +#[test] +fn transforms_curves_and_clips() { + let (c, _) = run("gsave 60 45 translate 2 2 scale newpath 0 0 10 0 360 arc clip newpath -20 -20 40 40 rectfill grestore 10 20 5 5 rectfill"); + assert!(c.contains(" c"), "arcs become curves: {c}"); + assert!(c.contains("W") && c.contains("q") && c.contains("Q"), "clip in its own q: {c}"); + // The circle is centred at (60, 45) with radius 20 in device space. + assert!(c.contains("80 45 m"), "{c}"); +} + +#[test] +fn huge_arc_checks_temporary_and_retained_memory_before_building_curves() { + let limits = Limits { memory: 4096, keep_unpainted: true, ..Limits::default() }; + let converted = eps_to_pdf(&eps("10 20 5 5 rectfill newpath 0 0 1e16 0 360 arc"), limits).unwrap(); + assert!(converted.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", converted.warnings); + assert_eq!(content(&converted.pdf).lines().filter(|line| *line == "f").count(), 1); +} + +#[test] +fn separation_colours_use_their_tint_transform() { + let (c, _) = run("[/Separation (Spot) /DeviceCMYK { dup 0 exch 0 } ] setcolorspace 0.5 setcolor 10 20 10 10 rectfill"); + assert!(c.contains("0.5 0 0.5 0 k") || c.contains(".5 0 .5 0 k"), "{c}"); +} + +#[test] +fn images_and_masks_become_xobjects() { + let (c, conv) = run("gsave 10 20 translate 20 10 scale 2 1 8 [2 0 0 -1 0 1] <00ff> image grestore + gsave 40 20 translate 10 10 scale 0 0 1 setrgbcolor 8 1 true [8 0 0 -1 0 1] imagemask grestore + gsave 60 20 translate 10 10 scale 1 1 8 [1 0 0 -1 0 1] currentfile /ASCIIHexDecode filter false 3 colorimage +ff8000> +grestore"); + assert_eq!(c.matches("Do").count(), 3, "{c}"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/ImageMask true") && pdf.contains("/DeviceRGB") && pdf.contains("/DeviceGray"), "{pdf}"); +} + +#[test] +fn type3_fonts_draw_their_glyphs() { + let (c, _) = run("/T3 8 dict dup begin /FontType 3 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 1000] def + /Encoding 256 array def 0 1 255 { Encoding exch /.notdef put } for Encoding 65 /A put + /BuildChar { pop pop 600 0 0 0 500 500 setcachedevice 0 0 500 500 rectfill } def end def + /T3 T3 definefont pop /T3 findfont 20 scalefont setfont 10 20 moveto (AA) show"); + // Two glyphs, the second 12 points (600 units at 20 pt) to the right. + assert_eq!(c.lines().filter(|l| *l == "f").count(), 2, "{c}"); + assert!(c.contains("22 20 m"), "{c}"); +} + +#[test] +fn type3_glyph_paints_after_prior_outline_glyphs() { + let ttf = tiny_ttf(); + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::())).collect(); + let (c, _) = run(&format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [0.001 0 0 0.001 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end /T42 exch definefont pop + /T3 8 dict dup begin /FontType 3 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 700] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /BuildChar {{ pop pop 1000 0 0 0 1000 700 setcachedevice 1 setgray 0 0 1000 700 rectfill }} def end /T3 exch definefont pop + /T0 6 dict dup begin /FontType 0 def /FMapType 2 def /FontMatrix [1 0 0 1 0 0] def + /FDepVector [ /T42 findfont /T3 findfont ] def end /T0 exch definefont pop + /T0 findfont 20 scalefont setfont 10 10 moveto <00410141> show" + )); + let lines: Vec<&str> = c.lines().collect(); + let first_fill = lines.iter().position(|line| *line == "f").unwrap_or_else(|| panic!("outline fill missing: {c}")); + let white_paint = lines.iter().position(|line| *line == "1 g").unwrap_or_else(|| panic!("Type 3 white paint missing: {c}")); + let second_fill = lines + .iter() + .enumerate() + .skip(white_paint + 1) + .find(|(_, line)| **line == "f") + .map(|(index, _)| index) + .unwrap_or_else(|| panic!("Type 3 fill missing: {c}")); + assert!(first_fill < white_paint && white_paint < second_fill, "glyph paints are out of order: {c}"); +} + +#[test] +fn type3_measurement_suppresses_nested_outline_painting() { + let ttf = tiny_ttf(); + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::())).collect(); + let (c, _) = run(&format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [0.001 0 0 0.001 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end /T42 exch definefont pop + /T3 8 dict dup begin /FontType 3 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 700] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /BuildChar {{ pop pop 1000 0 0 0 1000 700 setcachedevice /T42 findfont 20 scalefont setfont 10 10 moveto (A) show }} def end /T3 exch definefont pop + /T3 findfont 20 scalefont setfont (A) stringwidth pop pop 0 0 10 10 rectfill" + )); + assert_eq!(c.lines().filter(|line| *line == "f").count(), 1, "measurement painted nested outline text: {c}"); +} + +#[test] +fn a_string_made_a_file_runs_as_a_program() { + // Adobe's idiom: `(code) 0 () /SubFileDecode filter cvx exec`. + let (c, _) = run("(0.5 setgray 10 20 5 5 rectfill) 0 () /SubFileDecode filter cvx exec"); + assert!(c.contains("0.5 g"), "{c}"); +} + +#[test] +fn subfiledecode_exec_reads_the_following_program_lazily() { + let (c, converted) = run("currentfile 0 () /SubFileDecode filter exec\n0 0 10 10 rectfill"); + assert!(converted.warnings.is_empty(), "{:?}", converted.warnings); + assert_eq!(c.lines().filter(|line| *line == "f").count(), 1, "{c}"); +} + +#[test] +fn discarded_subfiledecode_skips_payload_without_materializing_it() { + let payload = "x".repeat(8192); + let bytes = eps(&format!("0 0 10 10 rectfill currentfile 0 (END) /SubFileDecode filter pop\n{payload}END")); + let limits = Limits { memory: 4096, ..Limits::default() }; + let converted = eps_to_pdf(&bytes, limits).unwrap(); + assert!(!converted.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", converted.warnings); + assert!(converted.memory <= limits.memory, "{} bytes", converted.memory); + let c = content(&converted.pdf); + assert!(c.contains("0 0 m") && c.contains("10 10 l"), "{c}"); +} + +#[test] +fn pop_does_not_drain_a_subfiledecode_stream_with_another_reference() { + let (c, converted) = run("currentfile 0 () /SubFileDecode filter 1 copy pop exec\n1 0 0 setrgbcolor 0 0 10 10 rectfill"); + assert!(converted.warnings.is_empty(), "{:?}", converted.warnings); + assert!(c.contains("1 0 0 rg") && c.contains("0 0 m") && c.contains("10 10 l"), "{c}"); +} + +#[test] +fn predictor_and_reusable_stream_buffers_are_charged_before_retention() { + let limits = Limits { memory: 4096, keep_unpainted: true, ..Limits::default() }; + let predictor = eps_to_pdf( + &eps("10 20 1 1 rectfill () << /Predictor 12 /Colors 32 /BitsPerComponent 16 /Columns 1048576 >> /FlateDecode filter pop"), + limits, + ) + .unwrap(); + assert!(predictor.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", predictor.warnings); + assert!(predictor.memory <= limits.memory, "{} bytes", predictor.memory); + + let payload = "x".repeat(2500); + let reusable = eps_to_pdf(&eps(&format!("10 20 1 1 rectfill ({payload}) /ReusableStreamDecode filter pop")), limits).unwrap(); + assert!(reusable.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", reusable.warnings); +} + +#[test] +fn empty_filter_source_records_are_charged_to_the_memory_limit() { + let limits = Limits { memory: 4096, keep_unpainted: true, ..Limits::default() }; + let converted = eps_to_pdf(&eps("10 20 1 1 rectfill 100000 { () 0 () /SubFileDecode filter pop } repeat"), limits).unwrap(); + assert!(converted.warnings.iter().any(|warning| warning == "out of memory"), "{:?}", converted.warnings); + assert!(converted.memory > limits.memory, "{} bytes", converted.memory); + assert!(converted.steps < limits.steps, "the test hit the work limit first: {} steps", converted.steps); +} + +#[test] +fn eexec_sections_run() { + // `(1 0 0 setrgbcolor 10 20 5 5 rectfill) ` encrypted with the eexec key, as hex. + let plain = b"1 0 0 setrgbcolor 10 20 5 5 rectfill currentfile closefile\n"; + let mut r: u16 = 55665; + let mut hex = String::new(); + for &p in [1u8, 2, 3, 4].iter().chain(plain.iter()) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + hex.push_str(&format!("{c:02x}")); + } + let (c, _) = run(&format!("currentfile eexec\n{hex}\n0 1 0 setrgbcolor 20 20 5 5 rectfill")); + assert!(c.contains("1 0 0 rg") && c.contains("0 1 0 rg"), "the program carries on after the section: {c}"); +} + +#[test] +fn completed_embedded_type1_fonts_get_a_fid_when_registered() { + let plain = b"pop currentfile closefile\n"; + let mut r: u16 = 55665; + let mut hex = String::new(); + for &p in [1u8, 2, 3, 4].iter().chain(plain.iter()) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + hex.push_str(&format!("{c:02x}")); + } + let body = format!( + "/T 6 dict dup begin /FontName /T def /FontType 1 def /FontMatrix [0.001 0 0 0.001 0 0] def /Private 1 dict def end def + T begin currentfile eexec\n{hex}\nT end + T /FID known {{ 1 0 0 setrgbcolor 10 20 5 5 rectfill }} if" + ); + let (content, _) = run(&body); + assert!(content.contains("1 0 0 rg"), "the recovered font has a FID: {content}"); +} + +#[test] +fn repeated_eexec_font_searches_charge_the_operand_stack_work() { + let plain = b"pop end currentfile closefile\n"; + let mut r: u16 = 55665; + let mut hex = String::new(); + for &p in [1u8, 2, 3, 4].iter().chain(plain.iter()) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + hex.push_str(&format!("{c:02x}")); + } + let mut body = format!( + "/T 6 dict dup begin /FontName /T def /FontType 1 def /FontMatrix [0.001 0 0 0.001 0 0] def /Private 1 dict def end def\nT begin {} ", + "0 ".repeat(4096) + ); + for _ in 0..16 { + body.push_str(&format!("currentfile eexec\n{hex}\n")); + } + let limits = Limits { steps: 20_000, keep_unpainted: true, ..Limits::default() }; + let converted = eps_to_pdf(&eps(&body), limits).expect("bounded recovery keeps completed output"); + assert!(converted.warnings.iter().any(|warning| warning == "the program runs too long"), "{:?}", converted.warnings); + assert!(converted.steps >= limits.steps, "stack search work was not charged: {}", converted.steps); +} + +#[test] +fn hostile_programs_end_with_an_error_not_a_hang_or_panic() { + let limits = Limits { + steps: 200_000, + memory: 64 << 20, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + }; + for body in [ + "{ } loop", + "/f { f } def f", + "/f { 1 f } def f", + "{ 1 } loop", + "1000000000 array", + "0 1 1e9 { pop } for", + "[ 1 2", + "/x 10 dict def x begin x begin", + "100000 { gsave } repeat", + "{ { { { { { stop } exec } exec } exec } exec } exec } loop", + "(unterminated", + "1 0 idiv", + "mark { 0 0 moveto } 1000000 { dup exec } repeat", + "currentfile 100000000 string readstring", + "/A85 currentfile /ASCII85Decode filter def ~>", + "0 0 moveto 1 1 1e300 1e300 0 0 curveto stroke", + "[1e300 0 0 1e300 0 0] concat 0 0 1 1 rectfill", + ] { + let _ = eps_to_pdf(&eps(body), limits); + } + // Nothing painted and an error: no PDF, so the caller keeps the preview. + assert!(eps_to_pdf(&eps("1 0 div"), limits).is_err()); + assert!(eps_to_pdf(b"%!PS-Adobe-3.0 EPSF-3.0\n0 0 1 1 rectfill\n", limits).is_err(), "no bounding box"); + assert!(eps_to_pdf(b"not postscript", limits).is_err()); +} + +#[test] +fn mutually_bound_executable_names_stop_at_a_bounded_depth() { + let err = eps_to_pdf(&eps("/n /m cvx def /m /n cvx def n"), Limits::default()).unwrap_err(); + assert_eq!(err, "executable name resolution limit"); +} + +#[test] +fn a_file_in_a_name_is_data_until_executed() { + // cairo keeps its image filter in a name and calls `status` and `flushfile` on it. + let (c, _) = run("/f (0.5 setgray 10 20 5 5 rectfill) 0 () /SubFileDecode filter def f status pop f cvx exec"); + assert!(c.contains("0.5 g"), "{c}"); +} + +#[test] +fn smooth_shadings_become_pdf_shadings() { + let (c, conv) = run("<< /ShadingType 2 /ColorSpace /DeviceCMYK /Coords [10 20 110 20] /Extend [true true] + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0 0] /C1 [0 0 1 0] /N 1 >> >> shfill + << /ShadingType 3 /ColorSpace [/Separation (Gold) /DeviceCMYK { dup 0.2 mul exch 0 exch 0 } ] + /Coords [60 45 0 60 45 20] /Function { } >> shfill"); + assert_eq!(c.matches(" sh").count(), 2, "{c}"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/ShadingType 2") && pdf.contains("/ShadingType 3"), "{pdf}"); + // CMYK and a spot made of CMYK stay CMYK. + assert_eq!(pdf.matches("/ColorSpace /DeviceCMYK").count(), 2, "{pdf}"); +} + +#[test] +fn shading_patterns_fill_their_path() { + let (c, _) = run("<< /PatternType 2 /Shading << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 0 100 0] + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> >> matrix makepattern + setpattern 10 20 50 30 rectfill"); + assert!(c.contains("W") && c.contains(" sh"), "clipped to the rectangle, then shaded: {c}"); +} + +#[test] +fn mesh_shadings_keep_their_vertices() { + // Two free-form triangles from an array, the second sharing an edge (flag 1). + let (_, conv) = run("<< /ShadingType 4 /ColorSpace /DeviceRGB + /DataSource [0 10 20 1 0 0 0 110 20 0 1 0 0 60 70 0 0 1 1 110 70 1 1 0] >> shfill + << /ShadingType 6 /ColorSpace /DeviceGray /DataSource [0 10 20 10 30 10 40 10 50 20 50 30 50 40 50 50 50 50 40 50 30 50 20 40 20 30 20 20 20 0 0.3 0.6 1] >> shfill"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/ShadingType 4") && pdf.contains("/ShadingType 6"), "{pdf}"); + // Malformed meshes draw what they hold, or nothing. + for bad in [ + "<< /ShadingType 4 /ColorSpace /DeviceRGB /DataSource [0 1] >> shfill", + "<< /ShadingType 7 /ColorSpace /DeviceGray /DataSource (abc) /BitsPerCoordinate 32 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 1 0 1 0 1] >> shfill 0 0 1 1 rectfill", + ] { + let _ = eps_to_pdf(&eps(bad), Limits::default()); + } +} + +/// A two-glyph TrueType font: .notdef (empty) and a 500 × 700 box at x 50, 600 wide, in +/// 1000 units to the em. +fn tiny_ttf() -> Vec { + let be16 = |v: i32| (v as i16 as u16).to_be_bytes(); + // The box: one contour of four on-curve points, coordinates as 16-bit deltas. + let mut glyph = Vec::new(); + for v in [1, 50, 0, 550, 700, 3] { + glyph.extend(be16(v)); + } + glyph.extend([0, 0]); // no instructions + glyph.extend([1, 1, 1, 1]); // on-curve, long coordinates + for dx in [50, 500, 0, -500] { + glyph.extend(be16(dx)); + } + for dy in [0, 0, 700, 0] { + glyph.extend(be16(dy)); + } + let mut head = Vec::new(); + head.extend(0x0001_0000u32.to_be_bytes()); + head.extend(0x0001_0000u32.to_be_bytes()); + head.extend(0u32.to_be_bytes()); + head.extend(0x5F0F_3CF5u32.to_be_bytes()); + head.extend(be16(0)); + head.extend(be16(1000)); + head.extend([0; 16]); + for v in [0, 0, 600, 700, 0, 8, 2, 0, 0] { + head.extend(be16(v)); + } + let mut hhea = 0x0001_0000u32.to_be_bytes().to_vec(); + for v in [800, -200, 0, 600, 0, 0, 550, 1, 0, 0, 0, 0, 0, 0, 0, 2] { + hhea.extend(be16(v)); + } + let mut maxp = 0x0000_5000u32.to_be_bytes().to_vec(); + maxp.extend(be16(2)); + let mut hmtx = Vec::new(); + for v in [500, 0, 600, 50] { + hmtx.extend(be16(v)); + } + let mut loca = Vec::new(); + for v in [0, 0, glyph.len() as i32 / 2] { + loca.extend(be16(v)); + } + let tables: [(&[u8; 4], Vec); 6] = [(b"glyf", glyph), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)]; + let mut out = 0x0001_0000u32.to_be_bytes().to_vec(); + out.extend(be16(tables.len() as i32)); + out.extend([0; 6]); + let mut at = 12 + 16 * tables.len(); + let mut body = Vec::new(); + for (tag, data) in &tables { + out.extend(*tag); + out.extend(0u32.to_be_bytes()); + out.extend((at as u32).to_be_bytes()); + out.extend((data.len() as u32).to_be_bytes()); + let mut d = data.clone(); + d.resize(data.len().div_ceil(4) * 4, 0); + at += d.len(); + body.extend(d); + } + out.extend(body); + out +} + +fn fallback_tiny_ttf(_: &[u8]) -> Option<&'static [u8]> { + static FONT: std::sync::OnceLock> = std::sync::OnceLock::new(); + Some(FONT.get_or_init(tiny_ttf).as_slice()) +} + +#[test] +fn fallback_font_bytes_are_charged_before_copying() { + let limits = Limits { memory: 256, fallback_font: Some(fallback_tiny_ttf), ..Limits::default() }; + let error = eps_to_pdf(&eps("/Missing findfont pop"), limits).unwrap_err(); + assert_eq!(error, "out of memory"); +} + +#[test] +fn actual_text_uses_the_selected_encoding_and_omits_unknown_names() { + let (content, _) = run("/F /Helvetica findfont def F /Encoding get 65 /B put F 10 scalefont setfont 10 20 moveto (A) show"); + assert!(content.contains("/ActualText (B)"), "{content}"); + + let (content, _) = run("/F /Helvetica findfont def F /Encoding get 65 /customGlyph put F 10 scalefont setfont 10 20 moveto (A) show"); + assert!(!content.contains("/ActualText"), "{content}"); +} + +#[test] +fn text_paint_keeps_completed_glyphs_when_a_later_glyph_hits_the_work_limit() { + let ttf = tiny_ttf(); + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::())).collect(); + let body = format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end definefont + 20 scalefont setfont 10 20 moveto (AA) show" + ); + let bytes = eps(&body); + let complete = eps_to_pdf(&bytes, Limits::default()).unwrap(); + let mut found_prefix = false; + for steps in (complete.steps.saturating_sub(100))..complete.steps { + let limits = Limits { steps, keep_unpainted: true, ..Limits::default() }; + let Ok(converted) = eps_to_pdf(&bytes, limits) else { continue }; + if converted.warnings.iter().any(|warning| warning == "the program runs too long") { + let content = content(&converted.pdf); + if content.lines().filter(|line| *line == "f").count() == 1 { + found_prefix = true; + break; + } + } + } + assert!(found_prefix, "no partial PDF retained the first completed glyph"); +} + +#[test] +fn type42_fonts_draw_their_truetype_glyphs() { + let ttf = tiny_ttf(); + // sfnts strings split at an even length below the string limit. + let sfnts: String = ttf.chunks(64).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::())).collect(); + let (c, _) = run(&format!( + "/T42 11 dict dup begin /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /PaintType 0 def /FontBBox [0 0 1 1] def + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 65 /A put + /CharStrings 2 dict dup /.notdef 0 put dup /A 1 put def /sfnts [ {sfnts} ] def end definefont + 20 scalefont setfont 10 20 moveto (AA) show" + )); + // Each glyph is filled independently; 1 point (50 units at 20 pt) in, the second 12 points on. + assert_eq!(c.lines().filter(|l| *l == "f").count(), 2, "{c}"); + assert_eq!(c.lines().filter(|l| *l == "EMC").count(), 1, "{c}"); + assert!(c.contains("11 20 m") && c.contains("23 20 m"), "{c}"); +} + +/// A CFF INDEX of `items` (4-byte offsets). +fn cff_index(items: &[Vec]) -> Vec { + let mut out = (items.len() as u16).to_be_bytes().to_vec(); + if items.is_empty() { + return out; + } + out.push(4); + let mut off = 1u32; + out.extend(off.to_be_bytes()); + for it in items { + off += it.len() as u32; + out.extend(off.to_be_bytes()); + } + for it in items { + out.extend(it); + } + out +} + +/// A DICT integer operand in its five-byte form (so offsets don't change the length). +fn cff_int(v: i32) -> Vec { + [vec![29], v.to_be_bytes().to_vec()].concat() +} + +/// A one-glyph CFF font set: glyph 1 is a 500 × 700 box, 600 wide. CID-keyed fonts give it CID 5. +fn tiny_cff(cid: bool) -> Vec { + let n = |v: i32| vec![(v + 139) as u8]; + let box_glyph = + [n(-100), n(50), n(0), vec![21], vec![247, 136], n(0), vec![5], n(0), vec![248, 80], vec![5], vec![251, 136], n(0), vec![5], vec![14]] + .concat(); + // 600 = width as the first (odd) operand: nominalWidthX 700 → −100. + let charstrings = cff_index(&[vec![14], box_glyph]); + let charset = if cid { vec![0, 0, 5] } else { vec![0, 0, 34] }; + let private = [cff_int(700), vec![21]].concat(); + let strings = cff_index(&[b"Adobe".to_vec(), b"Identity".to_vec()]); + let head = vec![1, 0, 4, 4]; + let names = cff_index(&[b"T".to_vec()]); + // Lay out: header, names, top dict, strings, gsubrs, charset, charstrings, private, [fdarray, fdselect]. + let top_len = |extra: usize| 1 + 2 + 4 + 4 + (5 + 1) * 2 + (5 + 5 + 1) + extra; + let extra = if cid { 5 + 5 + 5 + 2 + 5 + 2 + 5 + 2 + 5 + 2 } else { 0 }; + let top_index_len = 2 + 1 + 8 + (top_len(extra) - 11); + let mut at = head.len() + names.len() + top_index_len + strings.len() + 2; + let charset_at = at; + at += charset.len(); + let cs_at = at; + at += charstrings.len(); + let priv_at = at; + at += private.len(); + let fd_private = private.clone(); + let fd_dict = [cff_int(fd_private.len() as i32), cff_int(priv_at as i32), vec![18]].concat(); + let fdarray = cff_index(&[fd_dict]); + let fdarray_at = at; + at += fdarray.len(); + let fdselect_at = at; + let fdselect = vec![0, 0, 0]; + let mut top = + [cff_int(charset_at as i32), vec![15], cff_int(cs_at as i32), vec![17], cff_int(private.len() as i32), cff_int(priv_at as i32), vec![18]] + .concat(); + if cid { + top = [ + cff_int(391), + cff_int(392), + cff_int(0), + vec![12, 30], + cff_int(6), + vec![12, 34], + cff_int(fdarray_at as i32), + vec![12, 36], + cff_int(fdselect_at as i32), + vec![12, 37], + top, + ] + .concat(); + } + let tops = cff_index(&[top]); + let mut out = [head, names, tops, strings, vec![0, 0]].concat(); + assert_eq!(out.len(), charset_at, "layout"); + out.extend(charset); + out.extend(charstrings); + out.extend(private); + if cid { + out.extend(fdarray); + out.extend(fdselect); + } + out +} + +fn startdata_eps(cff: &[u8], body: &str) -> Vec { + let mut v = + format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 110 70\n/FontSetInit /ProcSet findresource begin\n/T {} StartData ", cff.len()) + .into_bytes(); + v.extend_from_slice(cff); + v.extend_from_slice(format!("\n{body}\n%%EOF\n").as_bytes()); + v +} + +#[test] +fn cff_fonts_from_startdata_draw_their_glyphs() { + let c = content( + &eps_to_pdf(&startdata_eps(&tiny_cff(false), "/T findfont 10 scalefont setfont 10 20 moveto (AA) show"), Limits::default()).unwrap().pdf, + ); + assert_eq!(c.lines().filter(|l| *l == "f").count(), 2, "{c}"); + assert_eq!(c.lines().filter(|l| *l == "EMC").count(), 1, "{c}"); + // The box starts 0.5 points (50 units) in; the second glyph 6 points (600 units) on. + assert!(c.contains("10.5 20 m") && c.contains("16.5 20 m"), "{c}"); +} + +#[test] +fn cid_fonts_draw_through_cmaps() { + let body = "/T-Identity-H findfont 10 scalefont setfont 10 20 moveto <00050005> show + /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /One-H def + 1 begincodespacerange <00> endcodespacerange 1 begincidchar <41> 5 endcidchar + endcmap CMapName currentdict /CMap defineresource pop end end + /U /One-H [/T] composefont pop /U findfont 10 scalefont setfont 10 40 moveto (AA) show"; + let c = content(&eps_to_pdf(&startdata_eps(&tiny_cff(true), body), Limits::default()).unwrap().pdf); + assert_eq!(c.lines().filter(|l| *l == "f").count(), 4, "{c}"); + assert_eq!(c.lines().filter(|l| *l == "EMC").count(), 0, "{c}"); + assert!(c.contains("16.5 20 m") && c.contains("16.5 40 m"), "{c}"); + // Broken font data is a warning, not a failure. + let r = eps_to_pdf(&startdata_eps(b"\x01\x00\x04\x04\xff\xff\xff", "0 0 1 1 rectfill"), Limits::default()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("CFF")), "{:?}", r.warnings); +} + +#[test] +fn tiling_patterns_become_pdf_patterns() { + let (c, conv) = run("<< /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 + /PaintProc { pop 1 0 0 setrgbcolor 0 0 5 5 rectfill } >> matrix makepattern setpattern + 10 20 50 30 rectfill + << /PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 4 4] /XStep 4 /YStep 4 + /PaintProc { pop 1 0 0 setrgbcolor 0 0 2 4 rectfill } >> matrix makepattern /S exch def + [/Pattern /DeviceCMYK] setcolorspace 0 1 0 0 S setcolor 60 20 40 30 rectfill"); + assert!(c.contains("/Pattern cs") && c.contains("/P0 scn") && c.contains("/P1 scn"), "{c}"); + let pdf = String::from_utf8_lossy(&conv.pdf); + assert!(pdf.contains("/PatternType 1") && pdf.contains("/XStep 10"), "{pdf}"); + // A cell that fails or nests too deeply ends cleanly. + for bad in [ + "<< /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 0 /YStep 1 /PaintProc { pop } >> matrix makepattern setpattern 0 0 1 1 rectfill", + "/P << /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /PaintProc { pop P setpattern 0 0 1 1 rectfill } >> matrix makepattern def P setpattern 0 0 1 1 rectfill", + "<< /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /PaintProc { 1 0 div } >> matrix makepattern setpattern 0 0 1 1 rectfill", + ] { + let _ = eps_to_pdf(&eps(bad), Limits::default()); + } +} + +#[test] +fn strokepath_outlines_the_stroke() { + // A 4-point butt-capped line from (10,20) to (60,20): its outline is the band y 18–22. + let (c, _) = run("newpath 10 30 moveto 60 30 lineto 4 setlinewidth strokepath 0 setgray fill"); + assert!(c.lines().any(|l| l == "f"), "{c}"); + assert!(!c.contains(" S\n") && !c.lines().any(|l| l == "S"), "filled, not stroked: {c}"); + for y in ["28", "32"] { + assert!(c.contains(&format!(" {y} l")) || c.contains(&format!(" {y} m")), "edge at y={y}: {c}"); + } + // Dashes split it; a path through a degenerate matrix ends empty; a clip to a stroke works. + let (c, _) = run("newpath 10 30 moveto 110 30 lineto 2 setlinewidth [10 10] 0 setdash strokepath fill"); + assert!(c.matches(" m").count() >= 5, "five dashes: {c}"); + let _ = run("[0 0 0 0 0 0] concat newpath 0 0 moveto 1 1 lineto strokepath fill"); + let (c, _) = run("newpath 10 30 moveto 100 30 lineto 10 setlinewidth strokepath clip newpath 10 20 100 50 rectfill"); + assert!(c.contains("W"), "{c}"); +} + +#[test] +fn vertical_cid_text_runs_down_from_its_vertical_origin() { + let body = "/T-Identity-V findfont 10 scalefont setfont 10 40 moveto <00050005> show"; + let c = content(&eps_to_pdf(&startdata_eps(&tiny_cff(true), body), Limits::default()).unwrap().pdf); + // v = (300, 880) units: the glyph's origin is 3 left and 8.8 below the point; the second + // glyph is one em (10) lower. The box starts 0.5 in from its origin. + assert!(c.contains("7.5 31.2 m") && c.contains("7.5 21.2 m"), "{c}"); + // A CMap program can make a font vertical too. + let body = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /V1 def /WMode 1 def + 1 begincodespacerange <00> endcodespacerange 1 begincidchar <41> 5 endcidchar + endcmap CMapName currentdict /CMap defineresource pop end end + /U /V1 [/T] composefont pop /U findfont 10 scalefont setfont 10 40 moveto (AA) show"; + let c = content(&eps_to_pdf(&startdata_eps(&tiny_cff(true), body), Limits::default()).unwrap().pdf); + assert!(c.contains("7.5 31.2 m") && c.contains("7.5 21.2 m"), "{c}"); +} + +#[test] +fn a_tiny_dash_on_a_long_path_draws_solid() { + let body = "newpath 0 30 moveto 100000 30 lineto [0.0001] 0 setdash"; + let (c, _) = run(&format!("{body} stroke")); + assert!(!c.contains(" d\n") && !c.contains("] 0 d"), "{c}"); + let (c, _) = run(&format!("{body} strokepath fill")); + assert!(c.matches(" m").count() < 10, "{}", &c[..c.len().min(300)]); +} + +#[test] +fn metrics_without_two_numbers_dont_underflow() { + // `[/a /b]` has two elements but no numbers: the width index used to go below zero. + let (c, _) = run("/Helvetica findfont dup length 1 add dict copy dup /Metrics << /A [/a /b] /B [7] >> put + /H exch definefont 10 scalefont setfont 10 20 moveto (AB) show 10 20 1 1 rectfill"); + assert!(c.contains("re") || c.contains(" m"), "{c}"); +} + +#[test] +fn work_in_proportion_to_operands_counts_against_the_limits() { + let limits = Limits { + steps: 200_000, + memory: 8 << 20, + stack_overflow_noop: false, + skip_images: false, + keep_unpainted: false, + zero_division_zero: false, + fallback_font: None, + }; + let ends = |body: &str| { + let r = eps_to_pdf(&eps(&format!("10 20 1 1 rectfill {body}")), limits).expect("what was painted is kept"); + let w = r.warnings.join(" "); + assert!(w.contains("too long") || w.contains("memory") || w.contains("too much data"), "{body}: {w}"); + // It stops at the charge that crosses the limit: overshoot is one operand's worth at most. + assert!(r.steps <= limits.steps + 1_000_000 || r.memory > limits.memory, "{body}: {} steps", r.steps); + }; + // Each would take seconds to minutes in a few steps without its charge. + ends("/h 1000000 string def /n 500 string def { h n search pop pop } loop"); + ends("100000 { 0 } repeat { 100000 copy 100000 { pop } repeat } loop"); + ends("/a 4000000 string def /b 4000000 string def { a b eq pop } loop"); + ends("newpath 0 0 moveto 100000 { 1 0 rlineto } repeat { gsave grestore } loop"); + ends("{ 4000000 string pop } loop"); + ends("/d 100000 dict def 0 1 99999 { d exch 0 put } for { d { pop pop } forall } loop"); + ends("/Helvetica findfont 10 scalefont setfont /s 1000000 string def { 0 0 moveto s show } loop"); + ends("mark 100000 { 0 } repeat { counttomark pop } loop"); + // Reading counts: a stream decoded over and over. + let z = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 1 << 20], 9); + let hex: String = z.iter().map(|b| format!("{b:02x}")).collect(); + ends(&format!("/z <{hex}> def {{ z /FlateDecode filter dup 2000000 string readstring pop pop closefile }} loop")); + // Tiny programs that only loop still end at the step limit. + ends("{ } loop"); +} + +#[test] +fn the_web_gets_smaller_default_limits() { + let l = Limits::default(); + if cfg!(target_arch = "wasm32") { + assert!(l.memory <= 256 << 20 && l.steps <= 20_000_000); + } else { + assert!(l.memory <= 1 << 30 && l.steps <= 50_000_000); + } +} diff --git a/crates/ps/src/read/type1.rs b/crates/ps/src/read/type1.rs new file mode 100644 index 0000000000..7ea3476e22 --- /dev/null +++ b/crates/ps/src/read/type1.rs @@ -0,0 +1,357 @@ +//! Type 1 glyphs: charstrings decrypted and run into outlines (Adobe Type 1 Font Format). + +use crate::read::gstate::Seg; +use crate::read::obj::{Key, Obj, PDict, name}; + +/// A glyph outline in glyph space and its advance. +#[derive(Debug, Clone, Default)] +pub struct Glyph { + pub path: Vec, + pub width: (f64, f64), + /// The work making it took (charstring operators run, or outline points). + pub cost: usize, +} + +/// The most charstring operators run for one glyph (subroutines included). +const MAX_OPS: usize = 100_000; +const MAX_CALL_DEPTH: usize = 12; + +pub fn decrypt(data: &[u8], skip: usize) -> Vec { + let mut r: u16 = 4330; + let mut out = Vec::with_capacity(data.len()); + for &c in data { + out.push(c ^ (r >> 8) as u8); + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + } + out.into_iter().skip(skip).collect() +} + +fn string_bytes(o: &Obj) -> Option> { + match o { + Obj::Str(s, _) => Some(s.bytes()), + _ => None, + } +} + +struct Font { + charstrings: PDict, + subrs: Vec>, + len_iv: i64, +} + +impl Font { + fn of(font: &PDict) -> Option { + let Some(Obj::Dict(charstrings)) = font.get_name(b"CharStrings") else { return None }; + let private = match font.get_name(b"Private") { + Some(Obj::Dict(p)) => Some(p), + _ => None, + }; + let len_iv = private.as_ref().and_then(|p| p.get_name(b"lenIV")).and_then(|o| o.num()).unwrap_or(4.0) as i64; + let subrs = match private.as_ref().and_then(|p| p.get_name(b"Subrs")) { + Some(Obj::Array(a, _)) => a.items().iter().map(|o| string_bytes(o).unwrap_or_default()).collect(), + _ => Vec::new(), + }; + Some(Font { charstrings, subrs, len_iv }) + } + + fn plain(&self, data: &[u8]) -> Vec { + if self.len_iv < 0 { data.to_vec() } else { decrypt(data, usize::try_from(self.len_iv).unwrap_or(4)) } + } + + fn charstring(&self, glyph: &[u8]) -> Option> { + let o = self.charstrings.get(&Key::Name(name(glyph))).or_else(|| self.charstrings.get(&Key::Name(name(b".notdef"))))?; + string_bytes(&o).map(|d| self.plain(&d)) + } +} + +#[derive(Default)] +struct Run { + path: Vec, + x: f64, + y: f64, + open: bool, + width: (f64, f64), + sb: (f64, f64), + stack: Vec, + ps: Vec, + flex: Option>, + ops: usize, + done: bool, +} + +impl Run { + fn move_to(&mut self, x: f64, y: f64) { + self.x = x; + self.y = y; + if let Some(pts) = self.flex.as_mut() { + pts.push((x, y)); + return; + } + if self.open { + self.path.push(Seg::Close); + } + self.path.push(Seg::Move(x, y)); + self.open = true; + } + + fn line_to(&mut self, x: f64, y: f64) { + if !self.open { + self.path.push(Seg::Move(self.x, self.y)); + self.open = true; + } + self.x = x; + self.y = y; + self.path.push(Seg::Line(x, y)); + } + + fn curve_to(&mut self, a: (f64, f64), b: (f64, f64), c: (f64, f64)) { + if !self.open { + self.path.push(Seg::Move(self.x, self.y)); + self.open = true; + } + self.x = c.0; + self.y = c.1; + self.path.push(Seg::Curve(a.0, a.1, b.0, b.1, c.0, c.1)); + } + + fn close(&mut self) { + if self.open { + self.path.push(Seg::Close); + self.open = false; + } + } +} + +fn exec(font: &Font, code: &[u8], run: &mut Run, depth: usize, std_glyph: &dyn Fn(usize) -> Option>) -> Option<()> { + if depth > MAX_CALL_DEPTH { + return None; + } + let mut i = 0; + while i < code.len() && !run.done { + run.ops += 1; + if run.ops > MAX_OPS || run.stack.len() > 64 { + return None; + } + let v = *code.get(i)?; + i += 1; + if v >= 32 { + let n = match v { + 32..=246 => f64::from(v) - 139.0, + 247..=250 => { + let w = *code.get(i)?; + i += 1; + (f64::from(v) - 247.0) * 256.0 + f64::from(w) + 108.0 + } + 251..=254 => { + let w = *code.get(i)?; + i += 1; + -(f64::from(v) - 251.0) * 256.0 - f64::from(w) - 108.0 + } + _ => { + let b: [u8; 4] = code.get(i..i + 4)?.try_into().ok()?; + i += 4; + f64::from(i32::from_be_bytes(b)) + } + }; + run.stack.push(n); + continue; + } + let s = std::mem::take(&mut run.stack); + let a = |k: usize| s.get(k).copied().unwrap_or(0.0); + match v { + // hstem, vstem: hints only. + 1 | 3 => {} + 4 => run.move_to(run.x, run.y + a(0)), + 5 => run.line_to(run.x + a(0), run.y + a(1)), + 6 => run.line_to(run.x + a(0), run.y), + 7 => run.line_to(run.x, run.y + a(0)), + 8 => { + let p1 = (run.x + a(0), run.y + a(1)); + let p2 = (p1.0 + a(2), p1.1 + a(3)); + let p3 = (p2.0 + a(4), p2.1 + a(5)); + run.curve_to(p1, p2, p3); + } + 9 => run.close(), + 10 => { + let n = usize::try_from(a(s.len().saturating_sub(1)) as i64).ok()?; + // Arguments below the subroutine number stay for it. + run.stack = s.get(..s.len().saturating_sub(1)).map(<[f64]>::to_vec).unwrap_or_default(); + let sub = font.subrs.get(n)?; + let plain = font.plain(sub); + exec(font, &plain, run, depth + 1, std_glyph)?; + continue; + } + 11 => { + run.stack = s; + return Some(()); + } + 12 => { + let e = *code.get(i)?; + i += 1; + match e { + // dotsection, vstem3, hstem3: hints. + 0..=2 => {} + 6 => { + // seac: an accented character from two StandardEncoding glyphs. + let (asb, adx, ady, bchar, achar) = (a(0), a(1), a(2), a(3) as usize, a(4) as usize); + let base = font.charstring(&std_glyph(bchar)?)?; + let accent = font.charstring(&std_glyph(achar)?)?; + let mut b = Run::default(); + exec(font, &base, &mut b, depth + 1, std_glyph)?; + let mut acc = Run::default(); + exec(font, &accent, &mut acc, depth + 1, std_glyph)?; + let (dx, dy) = (adx - asb + run.sb.0, ady); + run.path.extend(b.path); + run.path.extend(acc.path.iter().map(|s| s.map(&crate::read::gstate::M([1.0, 0.0, 0.0, 1.0, dx, dy])))); + run.done = true; + } + 7 => { + run.sb = (a(0), a(1)); + run.width = (a(2), a(3)); + run.x = a(0); + run.y = a(1); + } + 12 => { + let n = s.len(); + let d = a(n.saturating_sub(1)); + let q = if d != 0.0 { a(n.saturating_sub(2)) / d } else { 0.0 }; + run.stack = s.get(..n.saturating_sub(2)).map(<[f64]>::to_vec).unwrap_or_default(); + run.stack.push(q); + continue; + } + 16 => { + // callothersubr: flex (0–2) and hint replacement (3) are done here. + let n = s.len(); + let other = a(n.saturating_sub(1)) as i64; + let argc = usize::try_from(a(n.saturating_sub(2)) as i64).unwrap_or(0).min(n.saturating_sub(2)); + let args: Vec = s.get(n.saturating_sub(2) - argc..n.saturating_sub(2)).map(<[f64]>::to_vec).unwrap_or_default(); + run.stack = s.get(..n.saturating_sub(2) - argc).map(<[f64]>::to_vec).unwrap_or_default(); + match other { + 1 => run.flex = Some(Vec::new()), + 2 => {} + 0 => { + let pts = run.flex.take().unwrap_or_default(); + if let (Some(&p1), Some(&p2), Some(&p3), Some(&p4), Some(&p5), Some(&p6)) = + (pts.get(1), pts.get(2), pts.get(3), pts.get(4), pts.get(5), pts.get(6)) + { + run.curve_to(p1, p2, p3); + run.curve_to(p4, p5, p6); + } + // The end point for `pop pop setcurrentpoint`. + run.ps = vec![run.y, run.x]; + } + _ => { + // Hint replacement and others: their arguments come back. + run.ps = args.into_iter().rev().collect(); + } + } + continue; + } + 17 => { + let v = run.ps.pop().unwrap_or(0.0); + run.stack = s; + run.stack.push(v); + continue; + } + 33 => { + run.x = a(0); + run.y = a(1); + } + _ => {} + } + } + 13 => { + run.sb = (a(0), 0.0); + run.width = (a(1), 0.0); + run.x = a(0); + run.y = 0.0; + } + 14 => { + run.close(); + run.done = true; + } + 21 => run.move_to(run.x + a(0), run.y + a(1)), + 22 => run.move_to(run.x + a(0), run.y), + 30 => { + let p1 = (run.x, run.y + a(0)); + let p2 = (p1.0 + a(1), p1.1 + a(2)); + let p3 = (p2.0 + a(3), p2.1); + run.curve_to(p1, p2, p3); + } + 31 => { + let p1 = (run.x + a(0), run.y); + let p2 = (p1.0 + a(1), p1.1 + a(2)); + let p3 = (p2.0, p2.1 + a(3)); + run.curve_to(p1, p2, p3); + } + _ => {} + } + } + Some(()) +} + +/// The outline and advance of `glyph` in a Type 1 font dictionary, None when it has none. +pub fn glyph(font: &PDict, glyph: &[u8], std_names: &[&str]) -> Option { + let f = Font::of(font)?; + let code = f.charstring(glyph)?; + let mut run = Run::default(); + let std_glyph = |i: usize| std_names.get(i).map(|n| n.as_bytes().to_vec()); + exec(&f, &code, &mut run, 0, &std_glyph)?; + run.close(); + Some(Glyph { cost: run.ops + run.path.len(), path: run.path, width: run.width }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::read::obj::{PArr, PStr}; + + fn encrypt(plain: &[u8]) -> Vec { + let mut r: u16 = 4330; + let mut out = Vec::new(); + for &p in [0u8; 4].iter().chain(plain) { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + out.push(c); + } + out + } + + fn num(v: i32) -> Vec { + match v { + -107..=107 => vec![(v + 139) as u8], + 108..=1131 => { + let v = v - 108; + vec![(v / 256 + 247) as u8, (v % 256) as u8] + } + -1131..=-108 => { + let v = -v - 108; + vec![(v / 256 + 251) as u8, (v % 256) as u8] + } + _ => [vec![255], v.to_be_bytes().to_vec()].concat(), + } + } + + #[test] + fn a_square_glyph_and_its_width() { + // 50 600 hsbw; 0 0 rmoveto... : a 500 × 700 box through a subroutine. + let sub = [num(500), vec![6], num(700), vec![7], vec![11]].concat(); + let cs = [num(50), num(600), vec![13], num(0), num(0), vec![21], num(0), vec![10], num(-500), vec![6], vec![9], vec![14]].concat(); + let font = PDict::new(4); + let chars = PDict::new(2); + chars.put_name(b"A", Obj::Str(PStr::new(encrypt(&cs)), false)); + font.put_name(b"CharStrings", Obj::Dict(chars)); + let private = PDict::new(2); + private.put_name(b"Subrs", Obj::Array(PArr::new(vec![Obj::Str(PStr::new(encrypt(&sub)), false)]), false)); + font.put_name(b"Private", Obj::Dict(private)); + let g = glyph(&font, b"A", &[]).unwrap(); + assert_eq!(g.width, (600.0, 0.0)); + assert_eq!(g.path.first(), Some(&Seg::Move(50.0, 0.0))); + assert!(g.path.contains(&Seg::Line(550.0, 700.0)), "{:?}", g.path); + // Garbage doesn't panic or loop. + let chars = PDict::new(1); + chars.put_name(b"B", Obj::Str(PStr::new(encrypt(&[10, 10, 10, 255, 255])), false)); + font.put_name(b"CharStrings", Obj::Dict(chars)); + let _ = glyph(&font, b"B", &[]); + } +} diff --git a/crates/ps/src/read/type42.rs b/crates/ps/src/read/type42.rs new file mode 100644 index 0000000000..0b2bf7fbfa --- /dev/null +++ b/crates/ps/src/read/type42.rs @@ -0,0 +1,81 @@ +//! Type 42 fonts: a TrueType font in the `sfnts` strings, glyphs found through CharStrings +//! (glyph name → glyph index), drawn in em units (Adobe Technical Note 5012). + +use skrifa::instance::{LocationRef, Size}; +use skrifa::outline::{DrawSettings, OutlinePen}; +use skrifa::raw::TableProvider; +use skrifa::{GlyphId, MetadataProvider}; + +use crate::read::gstate::Seg; +use crate::read::obj::{Key, Obj, PDict, name}; +use crate::read::type1::Glyph; + +/// The TrueType data of a Type 42 font: its `sfnts` strings joined (an odd string's last byte +/// is padding). +pub fn sfnts(font: &PDict) -> Option> { + let Some(Obj::Array(a, _)) = font.get_name(b"sfnts") else { return None }; + let mut out = Vec::new(); + for s in a.items() { + let Obj::Str(s, _) = s else { return None }; + let mut b = s.bytes(); + if b.len() % 2 == 1 { + b.pop(); + } + out.extend_from_slice(&b); + } + Some(out) +} + +struct Pen { + path: Vec, + scale: f64, + cur: (f64, f64), +} + +impl OutlinePen for Pen { + fn move_to(&mut self, x: f32, y: f32) { + let p = (f64::from(x) * self.scale, f64::from(y) * self.scale); + self.path.push(Seg::Move(p.0, p.1)); + self.cur = p; + } + fn line_to(&mut self, x: f32, y: f32) { + let p = (f64::from(x) * self.scale, f64::from(y) * self.scale); + self.path.push(Seg::Line(p.0, p.1)); + self.cur = p; + } + fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) { + // A quadratic as the cubic with the same shape. + let (c, p) = ((f64::from(cx) * self.scale, f64::from(cy) * self.scale), (f64::from(x) * self.scale, f64::from(y) * self.scale)); + let a = (self.cur.0 + 2.0 / 3.0 * (c.0 - self.cur.0), self.cur.1 + 2.0 / 3.0 * (c.1 - self.cur.1)); + let b = (p.0 + 2.0 / 3.0 * (c.0 - p.0), p.1 + 2.0 / 3.0 * (c.1 - p.1)); + self.path.push(Seg::Curve(a.0, a.1, b.0, b.1, p.0, p.1)); + self.cur = p; + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + let s = self.scale; + let p = (f64::from(x) * s, f64::from(y) * s); + self.path.push(Seg::Curve(f64::from(x1) * s, f64::from(y1) * s, f64::from(x2) * s, f64::from(y2) * s, p.0, p.1)); + self.cur = p; + } + fn close(&mut self) { + self.path.push(Seg::Close); + } +} + +/// The glyph index for a glyph name (CharStrings maps names to indices). +pub fn glyph_index(font: &PDict, glyph: &[u8]) -> u32 { + let Some(Obj::Dict(cs)) = font.get_name(b"CharStrings") else { return 0 }; + cs.get(&Key::Name(name(glyph))).and_then(|o| o.num()).and_then(|v| u32::try_from(v as i64).ok()).unwrap_or(0) +} + +/// Glyph `gid` of TrueType `data` in em units, with its advance. +pub fn glyph(data: &[u8], gid: u32) -> Option { + let f = skrifa::FontRef::new(data).ok()?; + let upem = f64::from(f.head().ok()?.units_per_em()).max(1.0); + let mut pen = Pen { path: Vec::new(), scale: 1.0 / upem, cur: (0.0, 0.0) }; + if let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) { + let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), LocationRef::default()), &mut pen); + } + let adv = f.glyph_metrics(Size::unscaled(), LocationRef::default()).advance_width(GlyphId::new(gid)).map_or(0.0, f64::from) / upem; + Some(Glyph { cost: pen.path.len() * 4 + 16, path: pen.path, width: (adv, 0.0) }) +} diff --git a/crates/psd/src/io.rs b/crates/psd/src/io.rs index d8aa4b51d3..8ca8353b93 100644 --- a/crates/psd/src/io.rs +++ b/crates/psd/src/io.rs @@ -440,6 +440,18 @@ pub(crate) fn write_unicode_units(out: &mut Vec, units: &[u16]) { #[cfg(test)] mod tests { + /// A section length that does not fit the file's 32-bit field is refused, not truncated: + /// this is what keeps every `as u32` on a length inside a serialized file from ever wrapping, + /// and it is why an over-large PSD fails the write instead of producing a short length. + #[test] + fn a_length_that_does_not_fit_32_bits_is_refused() { + let mut out = Vec::new(); + assert!(out.put_len(u64::from(u32::MAX), false).is_ok(), "the largest 32-bit length fits"); + assert!(matches!(out.put_len(u64::from(u32::MAX) + 1, false), Err(PsdError::LimitExceeded(_)))); + // A PSB length field is 64 bits, so the same value is written there. + assert!(out.put_len(u64::from(u32::MAX) + 1, true).is_ok(), "PSB has room for it"); + } + use super::*; #[test] diff --git a/crates/raw/docs/nikon-lens-corrections.md b/crates/raw/docs/nikon-lens-corrections.md index 2431cd6dbd..74e35cc77d 100644 --- a/crates/raw/docs/nikon-lens-corrections.md +++ b/crates/raw/docs/nikon-lens-corrections.md @@ -1,10 +1,10 @@ # Nikon embedded distortion corrections Nikon writes its own distortion correction into NEFs from its mirrorless bodies, in the raw SubIFD tag `0xc7d5` -(NikonNEFInfo). LightCraft reads it for the NIKON Z 6_2 (Z 6II), the NIKON Z 8 and the NIKON Z f and turns it into an +(NikonNEFInfo). LightCraft reads it for the NIKON Z 6, NIKON Z 7, NIKON Z 6_2 (Z 6II), NIKON Z 8 and NIKON Z f and turns it into an `OpcodeList3` `WarpRectilinear`, so it goes through the same profile correction control, optics path, orientation handling and DNG export as the other embedded corrections. Other bodies are left alone for now even if they have the -same tag, because I've only checked files from these three. +same tag. Body recognition is limited to files checked against their camera JPEGs. This is distortion only. The vignetting block (`0x0006`) and what looks like lateral CA (`0x0007`) aren't applied yet. Like the Sony, Fujifilm and Panasonic corrections it's on by default and can be turned off under Lens @@ -24,7 +24,7 @@ NikonNEFInfo starts with `"Nikon\0"` and a 4-byte version, followed by a small T | Entry | Bytes | What it holds | |---|---|---| | `0x0005` DistortionInfo | 0–3 | `"0100"` | -| | 4 | correction mode: 1 "On (Optional)", 3 "On (Required)", 0 none | +| | 4 | correction mode: 1 "On (Optional)", 3 "On (Required)"; 0 none, 2 "Off" and unknown modes are skipped | | | 8–15 | normalisation radius in mm, a signed rational. It's 21.6 (the FX half diagonal) in every file I looked at | | | 16–19 | number of terms, 4 | | | 20, 28, 36 | the three coefficients, called `k1`, `k2`, `k3` here after ExifTool's names | @@ -84,18 +84,38 @@ extra correction for Z lenses that isn't in the readable coefficients. NikonNEFI didn't try to decode it. Even so, the readable correction takes most of the distortion out. At 24 mm the error at 0.7 half diagonals goes from −82 px to +25 px, and at 70 mm from about −137 px to under 4 px. +## Z 6 and Z 7 validation + +Six CC0 raw.pixls.us files were checked: three Z 6 and three Z 7 exposures of two repeated scenes, all with one +NIKKOR Z 24-70mm f/4 S (Z 6 at 52 mm and f/6.7, Z 7 at 56 mm and f/5.6). They don't establish coverage at other focal +lengths or with other lenses. Log-green patches in a quarter-size sensor proxy were matched against the full-size +embedded JPEG (normalised correlation at least 0.90, and a peak at least 0.02 above competing matches outside its 7 by +7 neighbourhood). The stored coefficients, zoom and optical centre were used as stored, with no per-photo fit. Radial +errors are full-size pixels over reliable matches between 0.15 and 0.95 image half diagonals: + +| Body | Files | Uncorrected radial median | Corrected radial median | Corrected radial p95 | +|---|---:|---:|---:|---:| +| Z 6 | 3 | 82.84-84.00 px | 0.88-0.96 px | 4.69-4.99 px | +| Z 7 | 3 | 124.21-124.80 px | 1.37-1.46 px | 6.18-6.38 px | + +Reliable patches reach about 0.90 half diagonals on the Z 6 and 0.94 on the Z 7, so the extreme corners aren't +validated. The remaining smooth edge error matches the native Z lens residual described above. The method, file +hashes and a production render sweep are in +[LightCraft PR #3796](https://github.com/storytold/lightcraft/pull/3796). + ## What's left out -Only `NIKON Z 6_2`, `NIKON Z 8` and `NIKON Z f` are corrected, matched exactly. A matching tag on another body doesn't tell us its +Only `NIKON Z 6`, `NIKON Z 7`, `NIKON Z 6_2`, `NIKON Z 8` and `NIKON Z f` are corrected, matched exactly. A matching tag on another body doesn't tell us its pixel pitch or image area, so other bodies can be added once someone checks their files. Only the full-frame 3:2 image area is corrected, because the stored 21.6 mm radius is the FX half diagonal, so DX and other crops are skipped. -The decoder also skips data it doesn't recognise (another layout, radius or term count, or no correction mode), +The decoder also skips data it doesn't recognise (another layout, radius or term count, or a correction mode other than 1 or 3), values that are clearly wrong (coefficients past ±1, a zoom past ±0.5, a sensor shift over 5% of the frame) and any mapping that folds back on itself before the farthest corner. The tests in `nef_lens` cover the polynomial and zoom, the sensor-shift center and refusing other bodies, layouts and crops. `nikon_in_file_distortion_becomes_a_warp` runs a synthetic Z 6II NEF through the header and full decode -and a DNG export. `nikon_in_file_distortion_is_limited_to_validated_bodies` checks the corpus: the Z f sample gets the -warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. +and a DNG export. `nikon_distortion_modes_are_respected_by_probe_and_full_decode` checks that only modes 1 and 3 +give a warp, in the header probe and the full decode alike. `nikon_in_file_distortion_is_limited_to_validated_bodies` +checks the corpus: the Z f sample gets the warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. None of my photos, crops or reference images are committed, only the numbers above. diff --git a/crates/raw/src/nef.rs b/crates/raw/src/nef.rs index bd880ebb88..8f4ffdcdd6 100644 --- a/crates/raw/src/nef.rs +++ b/crates/raw/src/nef.rs @@ -725,36 +725,38 @@ mod tests { TiffWriter::new(order, false).write(&[ifd0]).unwrap() } + /// A small uncompressed NEF with a real NikonNEFInfo TIFF block, without binary fixtures. + fn nikon_distortion_file(model: &str, mode: u8) -> Vec { + use crate::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; + let (w, h) = (48u32, 32u32); + let words: Vec = (0..w * h).flat_map(|i| (600 + (i % 97) as u16 * 50).to_be_bytes()).collect(); + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + let info = nef_info_blob(&[ + (0x0005, distortion_block(mode, 21.6, 4, [0.039895, 0.019211, -0.127218], -0.025043)), + (0x0008, offset_block(1.5, -0.75)), + ]); + raw.set(0xc7d5, Value::Undefined(info)); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![words] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); + ifd0.set(t::MODEL, Value::Ascii(model.into())); + ifd0.add_sub_ifd(raw); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() + } + /// A Z 6II NEF carrying NikonNEFInfo gets Nikon's distortion correction as one warp, in the header probe and /// the full decode alike, and keeps it through DNG export; another body with the same data gets none. #[test] fn nikon_in_file_distortion_becomes_a_warp() { - use crate::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; - let (w, h) = (48u32, 32u32); - let file = |model: &str| { - let words: Vec = (0..w * h).flat_map(|i| (600 + (i % 97) as u16 * 50).to_be_bytes()).collect(); - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); - raw.set(t::COMPRESSION, Value::Short(vec![1])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - let info = nef_info_blob(&[ - (0x0005, distortion_block(3, 21.6, 4, [0.039895, 0.019211, -0.127218], -0.025043)), - (0x0008, offset_block(1.5, -0.75)), - ]); - raw.set(0xc7d5, Value::Undefined(info)); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![words] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); - ifd0.set(t::MODEL, Value::Ascii(model.into())); - ifd0.add_sub_ifd(raw); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() - }; - let bytes = file("NIKON Z 6_2"); + let bytes = nikon_distortion_file("NIKON Z 6_2", 3); let header = decode(&bytes, Mode::Header, &Limits::default()).unwrap(); let full = decode(&bytes, Mode::Full, &Limits::default()).unwrap(); assert_eq!(header.info(), full.info()); @@ -767,7 +769,19 @@ mod tests { let dng = crate::write_dng(&full, &Default::default()).unwrap(); assert_eq!(crate::decode(&dng).unwrap().opcodes.list3, full.opcodes.list3); } - assert!(decode(&file("NIKON D850"), Mode::Full, &Limits::default()).unwrap().opcodes.list3.is_empty()); + assert!(decode(&nikon_distortion_file("NIKON D850", 3), Mode::Full, &Limits::default()).unwrap().opcodes.list3.is_empty()); + } + + /// Off, no-lens and unrecognized modes must not create a source correction through either public path. + #[test] + fn nikon_distortion_modes_are_respected_by_probe_and_full_decode() { + for mode in [0, 1, 2, 3, 4, 128, 255] { + let bytes = nikon_distortion_file("NIKON Z 6_2", mode); + let header = crate::probe_info(&bytes).unwrap(); + let full = crate::decode(&bytes).unwrap(); + assert_eq!(header, full.info(), "mode {mode}: header/full agreement"); + assert_eq!(!header.opcodes.list3.is_empty(), matches!(mode, 1 | 3), "mode {mode}"); + } } #[test] diff --git a/crates/raw/src/nef_lens.rs b/crates/raw/src/nef_lens.rs index 9f8dafb0e7..a6c6673240 100644 --- a/crates/raw/src/nef_lens.rs +++ b/crates/raw/src/nef_lens.rs @@ -15,7 +15,7 @@ const DISTORTION_INFO: u16 = 0x0005; const CENTRE_OFFSET: u16 = 0x0008; /// Bodies whose files were checked against the camera's JPEG (docs/nikon-lens-corrections.md). Matching tags on /// another body do not establish its pixel pitch or image area; add a body only after checking its files. -const VALIDATED: &[&str] = &["NIKON Z 6_2", "NIKON Z 8", "NIKON Z f"]; +const VALIDATED: &[&str] = &["NIKON Z 6", "NIKON Z 7", "NIKON Z 6_2", "NIKON Z 8", "NIKON Z f"]; /// The normalisation radius every checked file stores: the FX half-diagonal in millimetres. const FX_HALF_DIAGONAL_MM: f64 = 21.6; const SAMPLES: usize = 256; @@ -45,10 +45,10 @@ fn nef_info(raw: &Ifd) -> Option<(Ifd, ByteOrder)> { Some((ifd, order)) } -/// DistortionInfo: `"0100"`, the correction mode (0 none), the normalisation radius (mm) at 8, the term count (4) -/// at 16, the coefficients at 20 / 28 / 36 and the zoom at 64, each a signed rational. +/// DistortionInfo: `"0100"`, mode (1 optional on, 3 required on; 0 no lens, 2 off), radius (mm) at 8, +/// term count (4) at 16, coefficients at 20 / 28 / 36 and zoom at 64, each a signed rational. fn distortion_info(b: &[u8], order: ByteOrder) -> Option { - if b.get(0..4)? != b"0100" || *b.get(4)? == 0 { + if b.get(0..4)? != b"0100" || !matches!(*b.get(4)?, 1 | 3) { return None; } let norm = rational(b, 8, order)?; @@ -222,15 +222,20 @@ pub(crate) mod tests { #[test] fn refuses_unvalidated_bodies_and_unknown_layouts() { let good = distortion_block(3, 21.6, 4, WIDE.0, WIDE.1); - assert!(warp("NIKON Z 6_2", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); + for model in ["NIKON Z 6", "NIKON Z 7", "NIKON Z 6_2"] { + assert!(warp(model, &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some(), "{model}"); + } assert!(warp("NIKON Z f", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); assert!(warp("NIKON Z 8", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); - for model in ["", "NIKON Z 6", "NIKON Z 6_3", "NIKON Z 9", "NIKON D850", "NIKON Z 6_2 x"] { + for model in ["", "NIKON Z 7_2", "NIKON Z 6_3", "NIKON Z 9", "NIKON D850", "NIKON Z 6_2 x"] { assert!(warp(model, &raw_with(&[(DISTORTION_INFO, good.clone())])).is_none(), "{model}"); } // correction off, a DX radius, another term count, a wild coefficient or zoom, no NEFInfo at all for bad in [ distortion_block(0, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(2, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(4, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(255, 21.6, 4, WIDE.0, WIDE.1), distortion_block(3, 14.2, 4, WIDE.0, WIDE.1), distortion_block(3, 21.6, 3, WIDE.0, WIDE.1), distortion_block(3, 21.6, 4, [0.0, 0.0, 1.5], 0.0), diff --git a/crates/rtf/src/text.rs b/crates/rtf/src/text.rs index b1411842ec..7cca12d8e0 100644 --- a/crates/rtf/src/text.rs +++ b/crates/rtf/src/text.rs @@ -12,8 +12,9 @@ fn multibyte(code_page: u16) -> Option<&'static encoding_rs::Encoding> { /// else the default font's, else the document's) and how many fallback characters follow a /// `\uN` (`\ucN`, 1 when not set). /// -/// - `\uN` is one UTF-16 code unit. A high surrogate pairs only with a low surrogate in the -/// very next `\u`; every surrogate that does not pair reads as U+FFFD, as in Word. +/// - `\uN` is one UTF-16 code unit in the signed/unsigned 16-bit range. A high surrogate pairs +/// only with a low surrogate in the very next `\u`; unmatched surrogates and out-of-range +/// values are dropped, matching the historical DesignCraft reader. /// - After a `\uN`, the next `\ucN` characters are its fallback and are skipped: a text byte, /// a `\'hh`, a control word and a control symbol each count as one ([`TextDecoder::skip`]). /// The skipping ends with the group ([`TextDecoder::group`]). @@ -36,27 +37,34 @@ impl TextDecoder { } /// A held high surrogate that nothing paired with. - fn flush_high(&mut self, out: &mut String) { - if self.high.take().is_some() { - out.push('\u{FFFD}'); - } + fn flush_high(&mut self) { + self.high = None; } /// `\uN` with `uc` fallback characters to skip after it. pub fn unicode(&mut self, param: i32, uc: usize, out: &mut String) { self.finish_multibyte(out); + if !(-32_768..=65_535).contains(¶m) { + self.skip = uc; + return; + } let u = i64::from(param).rem_euclid(65_536) as u16; if (0xD800..0xDC00).contains(&u) { - self.flush_high(out); + self.flush_high(); self.high = Some(u); } else { match self.high.take() { - Some(h) if (0xDC00..0xE000).contains(&u) => out.push(char::decode_utf16([h, u]).next().and_then(Result::ok).unwrap_or('\u{FFFD}')), - Some(_) => { - out.push('\u{FFFD}'); - out.push(char::from_u32(u32::from(u)).unwrap_or('\u{FFFD}')); + Some(h) if (0xDC00..0xE000).contains(&u) => { + if let Some(c) = char::decode_utf16([h, u]).next().and_then(Result::ok) { + out.push(c); + } + } + Some(_) | None if (0xDC00..0xE000).contains(&u) => {} + Some(_) | None => { + if let Some(c) = char::from_u32(u32::from(u)) { + out.push(c); + } } - None => out.push(char::from_u32(u32::from(u)).unwrap_or('\u{FFFD}')), } } self.skip = uc; @@ -73,7 +81,7 @@ impl TextDecoder { /// A character a control word or symbol stands for (`\emdash`, `\~`). pub fn char(&mut self, c: char, out: &mut String) { self.finish_multibyte(out); - self.flush_high(out); + self.flush_high(); out.push(c); } @@ -95,7 +103,7 @@ impl TextDecoder { } fn decode(&mut self, chunk: &[u8], cp: u16, out: &mut String) { - self.flush_high(out); + self.flush_high(); if self.mb.is_none() && chunk.is_ascii() { // ASCII is itself in every code page here; with no lead byte pending, as it is. out.push_str(std::str::from_utf8(chunk).unwrap_or_default()); @@ -143,7 +151,7 @@ impl TextDecoder { /// for a partner any longer. pub fn finish(&mut self, out: &mut String) { self.finish_multibyte(out); - self.flush_high(out); + self.flush_high(); } } @@ -165,12 +173,13 @@ mod tests { assert_eq!(units(&[-10179, -8704], 0), "\u{1F600}"); assert_eq!(units(&[0xD83D, 0xDE00], 0), "\u{1F600}", "written unsigned"); assert_eq!(units(&[8364], 0), "€"); - assert_eq!(units(&[-10179], 0), "\u{FFFD}", "a lone high surrogate at the end"); - assert_eq!(units(&[-8704], 0), "\u{FFFD}", "a lone low surrogate"); - assert_eq!(units(&[-8704, -10179], 0), "\u{FFFD}\u{FFFD}", "low then high"); - assert_eq!(units(&[-10179, -10179, -8704], 0), "\u{FFFD}\u{1F600}", "a high surrogate before a pair"); - assert_eq!(units(&[-10179, 65, -8704], 0), "\u{FFFD}A\u{FFFD}"); - assert_eq!(units(&[65536 + 65, -65536 + 66], 0), "AB", "taken modulo 65536"); + assert_eq!(units(&[-10179], 0), "", "a lone high surrogate is dropped"); + assert_eq!(units(&[-8704], 0), "", "a lone low surrogate is dropped"); + assert_eq!(units(&[-8704, -10179], 0), "", "low then high are dropped"); + assert_eq!(units(&[-10179, -10179, -8704], 0), "\u{1F600}", "an unpaired high is dropped before a pair"); + assert_eq!(units(&[-10179, 65, -8704], 0), "A"); + assert_eq!(units(&[65_536 + 65, -65_536 + 66], 0), "", "out-of-range units are dropped"); + assert_eq!(units(&[i32::MAX, 65, i32::MIN], 0), "A", "extreme units are dropped"); } #[test] @@ -187,7 +196,7 @@ mod tests { d.group(&mut out); d.unicode(-8704, 1, &mut out); d.finish(&mut out); - assert_eq!(out, "\u{FFFD}x\u{FFFD}\u{FFFD}\u{2014}\u{1F600}"); + assert_eq!(out, "x\u{2014}\u{1F600}"); } #[test] diff --git a/crates/rtf/tests/read_write.rs b/crates/rtf/tests/read_write.rs index 9ef8fbfb70..32209b9926 100644 --- a/crates/rtf/tests/read_write.rs +++ b/crates/rtf/tests/read_write.rs @@ -103,8 +103,8 @@ fn pictures_and_objects_are_counted_not_read() { } #[test] -fn out_of_range_unicode_wraps_and_hyphens_are_text() { - assert_eq!(text(br"{\rtf1 a\u4294967361?b}"), "a\u{FFFF}b", "clamped to i32, then modulo 65536"); +fn invalid_unicode_and_hyphens_are_compatible() { + assert_eq!(text(br"{\rtf1 a\u4294967361?b}"), "ab", "out-of-range signed parameters are dropped"); assert_eq!(text(br"{\rtf1\ansi Rock\emdash-roll, x\tab-y, a\li-720 b}"), "Rock\u{2014}-roll, x\t-y, ab"); assert_eq!(text(br"{\rtf1 {\b A\'4}B}"), "AB"); assert_eq!(text(br"{\rtf1 a\'+fb}"), "a+fb"); @@ -132,9 +132,15 @@ fn nul_is_not_text() { #[test] fn surrogate_pairs() { assert_eq!(text(br"{\rtf1\ansi\uc1 A\u-10179?\u-8704?B \u-10174?\u-8265?\u30000?}"), "A\u{1F600}B \u{20BB7}\u{7530}"); - assert_eq!(text(br"{\rtf1 A\u-10179?B\u-8704?C}"), "A\u{FFFD}B\u{FFFD}C", "half a pair is U+FFFD, as in Word"); - assert_eq!(text(br"{\rtf1 A\u-10179?\par\u-8704?C}"), "A\u{FFFD}\n\u{FFFD}C", "a pair does not span a paragraph end"); - assert_eq!(text(br"{\rtf1 A\u-10179?}"), "A\u{FFFD}"); + assert_eq!(text(br"{\rtf1 A\u-10179?B\u-8704?C}"), "ABC", "unpaired surrogates are dropped, as in the previous DesignCraft reader"); + assert_eq!(text(br"{\rtf1 A\u-10179?\par\u-8704?C}"), "A\nC", "a pair does not span a paragraph end"); + assert_eq!(text(br"{\rtf1 A\u-10179?}"), "A"); +} + +#[test] +fn out_of_range_unicode_escapes_are_dropped() { + assert_eq!(text(br"{\rtf1 a\u4294967361?b}"), "ab"); + assert_eq!(text(br"{\rtf1 a\u-4294967231?b}"), "ab"); } #[test] diff --git a/crates/stream-codecs/src/ccitt.rs b/crates/stream-codecs/src/ccitt.rs index 2733cf98b4..c5a213ceaa 100644 --- a/crates/stream-codecs/src/ccitt.rs +++ b/crates/stream-codecs/src/ccitt.rs @@ -152,6 +152,76 @@ fn starts_with_end_of_line(data: &[u8]) -> bool { /// Rows of 1-bit samples filled from a decoder's pixels: `columns` a row, each row on a new byte, at /// most `rows` rows. Pixels past a row's end and rows past the last are dropped. +/// Reason a raw CCITT fax decode stopped or failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CcittErrorKind { + UnexpectedEof, + Overflow, + InvalidData, +} + +impl std::fmt::Display for CcittErrorKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnexpectedEof => f.write_str("unexpected end of CCITT stream"), + Self::Overflow => f.write_str("CCITT stream overflow"), + Self::InvalidData => f.write_str("invalid CCITT data"), + } + } +} + +/// Result of [`decode_ccitt_raw`], including any partial rows decoded before an error. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CcittRawOutput { + pub data: Vec, + pub rows_decoded: u32, + pub bytes_consumed: usize, + pub error: Option, +} + +/// Decodes CCITT Group 3 or Group 4 fax `data` with caller-specified `params` and `max_rows`, +/// returning packed MSB-first rows, rows decoded, input bytes consumed, and any decode error. +pub fn decode_ccitt_raw(data: &[u8], p: &CcittParams, max_rows: u32) -> Result { + if p.columns <= 0 || p.columns > i64::from(MAX_CCITT_COLUMNS) { + return Err(CodecError::Corrupt { filter: "CCITTFaxDecode", detail: format!("CCITT columns {} outside 1..={MAX_CCITT_COLUMNS}", p.columns) }); + } + let columns = u32::try_from(p.columns).map_err(|_| CodecError::Corrupt { filter: "CCITTFaxDecode", detail: "invalid CCITT columns".into() })?; + let rows = if p.rows > 0 { u32::try_from(p.rows).unwrap_or(max_rows).min(max_rows) } else { max_rows }; + let settings = hayro_ccitt::DecodeSettings { + columns, + rows, + end_of_block: p.end_of_block, + end_of_line: p.end_of_line, + rows_are_byte_aligned: p.encoded_byte_align && (p.k < 0 || !starts_with_end_of_line(data)), + encoding: match p.k { + ..0 => hayro_ccitt::EncodingMode::Group4, + 0 => hayro_ccitt::EncodingMode::Group3_1D, + k => hayro_ccitt::EncodingMode::Group3_2D { k: u32::try_from(k).unwrap_or(u32::MAX) }, + }, + invert_black: false, + }; + let mut out = Rows::new(columns as usize, rows as usize, p.black_is_1); + let (bytes_consumed, error) = match hayro_ccitt::decode(data, &mut out, &mut hayro_ccitt::DecoderContext::new(settings)) { + Ok(used) => (used, None), + Err(e) => { + let kind = match e { + hayro_ccitt::DecodeError::UnexpectedEof => CcittErrorKind::UnexpectedEof, + hayro_ccitt::DecodeError::Overflow => CcittErrorKind::Overflow, + _ => CcittErrorKind::InvalidData, + }; + let used = if out.done > 0 { + let mut drop_rows = Rows::new(columns as usize, out.done, p.black_is_1); + let retry = hayro_ccitt::DecodeSettings { rows: u32::try_from(out.done).unwrap_or(u32::MAX), ..settings }; + hayro_ccitt::decode(data, &mut drop_rows, &mut hayro_ccitt::DecoderContext::new(retry)).unwrap_or(data.len()) + } else { + 0 + }; + (used, Some(kind)) + } + }; + Ok(CcittRawOutput { data: out.out, rows_decoded: u32::try_from(out.done).unwrap_or(u32::MAX), bytes_consumed, error }) +} + pub(crate) struct Rows { pub(crate) out: Vec, row: Vec, diff --git a/crates/stream-codecs/src/lib.rs b/crates/stream-codecs/src/lib.rs index d129cacaa2..ee275b2ce6 100644 --- a/crates/stream-codecs/src/lib.rs +++ b/crates/stream-codecs/src/lib.rs @@ -42,7 +42,7 @@ mod mq; pub mod predictor; pub mod runlength; -pub use ccitt::{CcittParams, MAX_CCITT_COLUMNS, MAX_G4_COLUMNS, decode_ccitt_within, encode_g4}; +pub use ccitt::{CcittErrorKind, CcittParams, CcittRawOutput, MAX_CCITT_COLUMNS, MAX_G4_COLUMNS, decode_ccitt_raw, decode_ccitt_within, encode_g4}; pub use jbig2::{MAX_JBIG2_COLUMNS, MAX_JBIG2_PIXELS, SharedJbig2, decode_jbig2_within, encode_jbig2, encode_jbig2_generic, encode_jbig2_shared}; /// Parameters of the predictors and of LZW, as a PDF `/DecodeParms` dictionary gives them diff --git a/crates/svg/src/tree/draw.rs b/crates/svg/src/tree/draw.rs index a7bdfd80f8..f83653284d 100644 --- a/crates/svg/src/tree/draw.rs +++ b/crates/svg/src/tree/draw.rs @@ -24,6 +24,8 @@ use std::collections::HashMap; use usvg::Transform; +#[cfg(feature = "tree-render")] +pub use resvg; #[cfg(feature = "tree-render")] pub use resvg::tiny_skia; diff --git a/crates/svg/src/tree/tests.rs b/crates/svg/src/tree/tests.rs index 751e7726b5..59b42dacc0 100644 --- a/crates/svg/src/tree/tests.rs +++ b/crates/svg/src/tree/tests.rs @@ -81,7 +81,8 @@ fn every_limit_refuses_the_file_past_it() { let chain: String = (0..20).map(|i| format!("", i + 1)).collect(); let uses = svg(&format!("{chain}")); assert!(!guard::deeper_than(&uses, 24)); - assert_eq!(try_parse(&uses, &shallow()).err(), Some(Error::TooDeep(24))); + let referenced_depth = Limits { tree_depth: 24, ..shallow() }; + assert_eq!(try_parse(&uses, &referenced_depth).err(), Some(Error::TooDeep(24))); // Attributes on one element. let wide = svg(&format!("", (0..40).map(|i| format!(" a{i}='1'")).collect::())); assert!(try_parse(&wide, &Limits { attributes: 40, ..shallow() }).is_ok()); diff --git a/crates/texture/Cargo.toml b/crates/texture/Cargo.toml new file mode 100644 index 0000000000..78868dd879 --- /dev/null +++ b/crates/texture/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-texture" +description = "Bounded linear float image planes and texture sampling" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[features] +default = [] +parallel = ["dep:rayon"] + +[lints] +workspace = true + +[dependencies] +rayon = { workspace = true, optional = true } +thiserror = { workspace = true } diff --git a/crates/texture/README.md b/crates/texture/README.md new file mode 100644 index 0000000000..a41b42666f --- /dev/null +++ b/crates/texture/README.md @@ -0,0 +1,77 @@ +# craft-texture + +Linear float image planes and texture sampling. An `Image` is a gray (1 channel) or RGBA plane of +`f32`, row-major with the top row first, shared copy-on-write through an `Arc`. Values are stored +as given, so HDR values above 1 and negative values are kept. The crate has no UI, does no file or +network I/O and has no `unsafe` code. + +- **Construction.** `try_filled`, `try_generate`, `try_generate_uv` and `from_data` check the size + against `Limits` (longest side, pixel count, bytes) before allocating and return an + `ImageError`. `from_data` also checks that the buffer holds width × height × channels floats. + `filled`, `generate`, `generate_uv` and `gray` clamp each side to `1..=MAX_SIDE` (8192). + A plane is never larger than `isize::MAX` bytes (2 GiB minus one byte on `wasm32`), even with + raised limits: the `try_` forms return `ImageError::TooLarge` for a larger one, and `map`, + `to_color` and `to_kind` clamp each side to `1..=MAX_SIDE` and map the top-left part instead. + `try_map`, `try_to_kind`, `try_resize` and `try_to_rgba8_display` reserve their pixel buffer + first and return `ImageError::OutOfMemory` when that reservation fails. They still make small + allocations that are not fallible: the `Arc` around a new image's buffer, and the boxed + resampler of `try_resize`. The forms without `try_` allocate like `Vec`. A failed infallible + allocation ends the process. +- **Sampling.** `sample` (bilinear) and `sample_nearest` take normalized `(u, v)` with `(0, 0)` at + the upper-left corner and `v` increasing downward, as glTF 2.0 section 3.8.3 defines them + (). `tile` picks repeat (glTF + `REPEAT`) or clamp to edge (`CLAMP_TO_EDGE`) for both axes. The texel coordinate, the wrapping + and the bilinear weights follow the Vulkan specification, sections 20.4.1, 20.6.1 and 20.6.3 + (). + Repeat keeps its period at any finite coordinate. A NaN or infinite coordinate gives + `[0, 0, 0, 1]`. Bilinear sums are taken in `f64` and clamped to the `f32` range, so finite + texels give a finite sample. +- **Other operations.** `get` reads one texel, `map`, `to_gray`, `to_color` and `to_kind` convert, + `resize` box-averages whole-factor shrinks and samples bilinearly otherwise, and + `to_rgba8_display` encodes 8-bit sRGB RGBA. `linear_to_srgb`, `srgb_to_linear` and `luminance` + (Rec. 709) are scalar helpers. `resource_key` and `split_resource_key` tag a bitmap name with + its color space. + +Mirrored repeat, mip chains, height to normal, channel packing, decoding and texture-set +recognition are not in the crate yet. + +## Cargo features + +No default features. + +| Feature | Provides | Pulls in | +|---|---|---| +| `parallel` | generated images and display conversion fill rows on several threads; the results are the same | `rayon` | + +Without `parallel` the crate builds for `wasm32-unknown-unknown`. + +## Limits + +| Field | Default | Checked by | +|---|---|---| +| `max_side` | 8192 | every `try_` constructor and `from_data` | +| `max_pixels` | 2^26 (8192 × 8192) | the same | +| `max_bytes` | 1 GiB (an 8192 × 8192 RGBA plane) | the same | + +## Origin + +| Part | Source | +|---|---| +| `Image`, `Kind`, sampling, resizing, conversions, sRGB helpers, resource keys and the six tests `sample_survives_huge_coordinates`, `resource_keys_round_trip`, `sample_wraps_and_clamps`, `resize_box_and_bilinear`, `hostile_sizes_are_clamped`, `conversions` | MaterialCraft `crates/image/src/lib.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | +| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature | written here | + +## Migration + +| App | Status | +|---|---| +| MaterialCraft | `materialcraft-image` is the source. The app switches to this crate in its own pull request. | +| EffectCraft | Its texture sampling moves into this crate later, with mirrored repeat. | + +For MaterialCraft: + +| `materialcraft-image` | craft-texture | +| --- | --- | +| `image.w`, `image.h`, `image.kind`, `image.data` | `width()`, `height()`, `kind()`, `data()` and `shared_data()` | +| `Image { w, h, kind, data }` built by hand | `Image::from_data(w, h, kind, data, &Limits::default())` | +| `rayon` always on | the `parallel` feature | +| `linear_to_srgb(NaN)` returned −0.055 | it returns NaN | diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs new file mode 100644 index 0000000000..2aaef3e8bc --- /dev/null +++ b/crates/texture/src/lib.rs @@ -0,0 +1,895 @@ +//! # craft-texture +//! +//! Linear float image planes and texture sampling. An [`Image`] is a grayscale (1 channel) or +//! color (RGBA) plane of `f32`, row-major with the top row first, shared copy-on-write through an +//! `Arc` so a copy costs a reference count. Values are stored as given: HDR values above 1, +//! negative values and non-finite values are kept. +//! +//! Sampling takes normalized `(u, v)` with `(0, 0)` at the upper-left corner and `v` increasing +//! downward, as glTF 2.0 section 3.8.3 defines texture coordinates +//! (). The `tile` argument picks the +//! wrap mode of both axes: repeat (glTF `REPEAT`, 10497) or clamp to edge (`CLAMP_TO_EDGE`, 33071). +//! [`Image::sample_nearest`] and [`Image::sample`] (bilinear) use the texel coordinates, wrapping +//! and weights of the Vulkan specification, sections 20.4.1, 20.6.1 and 20.6.3 +//! (). +//! +//! Sizes are bounded. [`Limits`] caps the side, the pixel count and the bytes, and the `try_` +//! constructors return an [`ImageError`] before allocating anything over them. A plane is also +//! never larger than `isize::MAX` bytes, the most a `Vec` can hold on the target: `isize::MAX` is +//! 2 GiB minus one byte on 32-bit targets such as `wasm32`. The `try_` forms return +//! [`ImageError::TooLarge`] for a plane over that bound, also when the caller raised the limits +//! past it. The constructors without `try_` clamp each side to `1..=MAX_SIDE`, and [`Image::map`] +//! clamps the same way when its result would be over the bound. Every operation that allocates a +//! pixel buffer has a `try_` form that reserves that buffer first and returns +//! [`ImageError::OutOfMemory`] when the reservation fails. The `try_` forms still make small +//! allocations that are not fallible: the `Arc` that holds a new image's buffer, and the boxed +//! resampler of [`Image::try_resize`]. The forms without `try_` allocate like `Vec`. A failed +//! infallible allocation ends the process. Rows are generated on several threads only with the +//! `parallel` feature. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::sync::Arc; + +#[cfg(feature = "parallel")] +use rayon::prelude::*; + +/// Largest side the clamping constructors make, and the default [`Limits::max_side`]. +pub const MAX_SIDE: u32 = 8192; + +/// Whether an image holds one channel or four. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Gray, + Color, +} + +impl Kind { + pub fn channels(self) -> usize { + match self { + Kind::Gray => 1, + Kind::Color => 4, + } + } +} + +/// Why an image could not be made. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum ImageError { + /// A side is zero or longer than [`Limits::max_side`]. + #[error("image size {0}x{1} has a zero side or a side over the limit")] + BadSize(u32, u32), + /// The pixel count or the byte count is over [`Limits`], or the byte count is over + /// `isize::MAX`, the largest allocation the target allows. + #[error("image size {0}x{1} needs more pixels or bytes than the limits or the target allow")] + TooLarge(u32, u32), + /// The float buffer does not hold width × height × channels values. + #[error("image data holds {found} floats where {expected} are needed")] + BadDataLength { expected: usize, found: usize }, + /// Memory for the pixels could not be reserved. + #[error("not enough memory for a {0}x{1} image")] + OutOfMemory(u32, u32), +} + +/// Caps on the size of an image, checked before anything is allocated. +/// `#[non_exhaustive]`: start from [`Limits::default`] and set the fields you change. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub struct Limits { + /// Longest side in pixels. Default [`MAX_SIDE`]. + pub max_side: u32, + /// Most pixels (width × height). Default 2^26, which is 8192 × 8192. + pub max_pixels: u64, + /// Most bytes of float data (pixels × channels × 4). Default 1 GiB, an 8192 × 8192 color plane. + pub max_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_side: MAX_SIDE, max_pixels: 1 << 26, max_bytes: 1 << 30 } + } +} + +/// The largest allocation in bytes that a `Vec` can make on the target. +const MAX_ALLOC_BYTES: u64 = isize::MAX as u64; + +/// Bytes of float data in a `w × h` image of `kind`, or `None` when the count overflows `u64`. +fn checked_byte_len(w: u32, h: u32, kind: Kind) -> Option { + u64::from(w).checked_mul(u64::from(h))?.checked_mul(kind.channels() as u64)?.checked_mul(size_of::() as u64) +} + +impl Limits { + /// The number of floats a `w × h` image of `kind` holds, or the error the limits give for that + /// size. A size whose bytes are over `isize::MAX` is [`ImageError::TooLarge`] whatever the + /// limits are. Nothing is allocated. + pub fn check(&self, w: u32, h: u32, kind: Kind) -> Result { + self.check_within(w, h, kind, MAX_ALLOC_BYTES) + } + + /// [`Limits::check`] with `max_alloc_bytes` as the largest allocation the target allows. + fn check_within(&self, w: u32, h: u32, kind: Kind, max_alloc_bytes: u64) -> Result { + if w == 0 || h == 0 || w > self.max_side || h > self.max_side { + return Err(ImageError::BadSize(w, h)); + } + let too_large = ImageError::TooLarge(w, h); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(|| too_large.clone())?; + let floats = pixels.checked_mul(kind.channels() as u64).ok_or_else(|| too_large.clone())?; + let bytes = floats.checked_mul(size_of::() as u64).ok_or_else(|| too_large.clone())?; + if pixels > self.max_pixels || bytes > self.max_bytes || bytes > max_alloc_bytes { + return Err(too_large); + } + usize::try_from(floats).map_err(|_| too_large) + } +} + +/// A gray or RGBA plane of linear `f32`. Width and height are at least 1, and the data holds +/// exactly width × height × channels floats. +#[derive(Clone, Debug)] +pub struct Image { + w: u32, + h: u32, + kind: Kind, + /// Row-major, `kind.channels()` floats per pixel. + data: Arc>, +} + +/// Images are equal when their size, kind and floats are equal. Floats compare as `f32` does, so +/// an image holding NaN is unequal to every image, its clones included. +impl PartialEq for Image { + fn eq(&self, o: &Image) -> bool { + self.w == o.w && self.h == o.h && self.kind == o.kind && self.data == o.data + } +} + +/// Clamp a requested size into `1..=MAX_SIDE` on each side. +pub fn clamp_size(w: u32, h: u32) -> (u32, u32) { + (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE)) +} + +/// The size and float count of an image of `kind` requested at `w × h` without a limit check: +/// `w × h` when its bytes fit in `max_alloc_bytes`, otherwise each side clamped to +/// `1..=MAX_SIDE`, and 1 × 1 when even the clamped size does not fit. Nothing is allocated. +fn bounded_size(w: u32, h: u32, kind: Kind, max_alloc_bytes: u64) -> (u32, u32, usize) { + let floats = |w: u32, h: u32| { + let bytes = checked_byte_len(w, h, kind).filter(|&bytes| bytes <= max_alloc_bytes)?; + usize::try_from(bytes / size_of::() as u64).ok() + }; + if let Some(len) = floats(w, h) { + return (w, h, len); + } + let (w, h) = clamp_size(w, h); + match floats(w, h) { + Some(len) => (w, h, len), + None => (1, 1, kind.channels()), + } +} + +/// Integer texel index `i` on an axis of `n >= 1` texels: `i mod n` when repeating, otherwise +/// clamped to `0..=n - 1`. +#[inline] +fn wrap(i: i64, n: u32, tile: bool) -> usize { + let n = i64::from(n.max(1)); + if tile { i.rem_euclid(n) as usize } else { i.clamp(0, n - 1) as usize } +} + +/// The largest `f32` below 1. +const BELOW_ONE: f32 = 1.0 - f32::EPSILON / 2.0; + +/// A normalized coordinate brought into a range whose texel indices fit in `i64`: its fractional +/// part, below 1, when repeating, since the repeat period is 1, and `-1..=2` when clamping, where +/// every value outside `0..=1` already selects an edge texel. `None` for NaN and infinity. +#[inline] +fn reduce(t: f32, tile: bool) -> Option { + if !t.is_finite() { + return None; + } + Some(if tile { t.rem_euclid(1.0).min(BELOW_ONE) } else { t.clamp(-1.0, 2.0) }) +} + +/// Fill `data` row by row with `f(x, y)`, keeping the first `c` channels of each result. +fn fill [f32; 4] + Sync>(data: &mut [f32], w: u32, c: usize, f: &F) { + let row_len = (w as usize).max(1) * c; + let fill_row = |(y, row): (usize, &mut [f32])| { + for (x, px) in row.chunks_exact_mut(c).enumerate() { + let p = f(x as u32, y as u32); + px.copy_from_slice(&p[..c]); + } + }; + #[cfg(feature = "parallel")] + data.par_chunks_mut(row_len).enumerate().for_each(fill_row); + #[cfg(not(feature = "parallel"))] + data.chunks_mut(row_len).enumerate().for_each(fill_row); +} + +impl Image { + /// An image of `w × h`, or of the clamped size [`bounded_size`] gives when its bytes would be + /// over `isize::MAX`. `f` is called only for pixels inside the size that was made. + fn build [f32; 4] + Sync>(w: u32, h: u32, kind: Kind, f: F) -> Image { + let (w, h, len) = bounded_size(w, h, kind, MAX_ALLOC_BYTES); + let mut data = vec![0.0f32; len]; + fill(&mut data, w, kind.channels(), &f); + Image { w, h, kind, data: Arc::new(data) } + } + + /// An image checked against `limits`, with its memory reserved before any pixel is generated. + fn try_build [f32; 4] + Sync>(w: u32, h: u32, kind: Kind, limits: &Limits, f: F) -> Result { + let len = limits.check(w, h, kind)?; + let mut data = Vec::new(); + data.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(w, h))?; + data.resize(len, 0.0); + fill(&mut data, w, kind.channels(), &f); + Ok(Image { w, h, kind, data: Arc::new(data) }) + } + + /// A constant image, each side clamped to `1..=MAX_SIDE`. + pub fn filled(w: u32, h: u32, kind: Kind, v: [f32; 4]) -> Image { + let (w, h) = clamp_size(w, h); + Image::build(w, h, kind, |_, _| v) + } + + /// A constant image, or an error when the size is outside `limits` or memory runs out. + pub fn try_filled(w: u32, h: u32, kind: Kind, v: [f32; 4], limits: &Limits) -> Result { + Image::try_build(w, h, kind, limits, |_, _| v) + } + + /// Generate every pixel with `f(x, y)` (pixel indices), each side clamped to `1..=MAX_SIDE`. + pub fn generate(w: u32, h: u32, kind: Kind, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { + let (w, h) = clamp_size(w, h); + Image::build(w, h, kind, f) + } + + /// Generate every pixel with `f(x, y)`, or return an error when the size is outside `limits` + /// or memory runs out. + pub fn try_generate(w: u32, h: u32, kind: Kind, limits: &Limits, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Result { + Image::try_build(w, h, kind, limits, f) + } + + /// Generate from normalized coordinates at the pixel centers, `(x + 0.5) / w` and + /// `(y + 0.5) / h`, each side clamped to `1..=MAX_SIDE` first. + pub fn generate_uv(w: u32, h: u32, kind: Kind, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { + let (w, h) = clamp_size(w, h); + let (iw, ih) = (1.0 / w as f32, 1.0 / h as f32); + Image::build(w, h, kind, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) + } + + /// [`Image::generate_uv`] for a size checked against `limits`. + pub fn try_generate_uv(w: u32, h: u32, kind: Kind, limits: &Limits, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Result { + let (iw, ih) = (1.0 / w.max(1) as f32, 1.0 / h.max(1) as f32); + Image::try_build(w, h, kind, limits, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) + } + + /// A gray image generated with `f(x, y)`, each side clamped to `1..=MAX_SIDE`. + pub fn gray(w: u32, h: u32, f: impl Fn(u32, u32) -> f32 + Sync) -> Image { + Image::generate(w, h, Kind::Gray, |x, y| [f(x, y), 0.0, 0.0, 0.0]) + } + + /// An image over existing row-major data, checked against `limits` and against the length + /// width × height × channels. The data is not copied. + pub fn from_data(w: u32, h: u32, kind: Kind, data: impl Into>>, limits: &Limits) -> Result { + let expected = limits.check(w, h, kind)?; + let data = data.into(); + if data.len() != expected { + return Err(ImageError::BadDataLength { expected, found: data.len() }); + } + Ok(Image { w, h, kind, data }) + } + + pub fn width(&self) -> u32 { + self.w + } + + pub fn height(&self) -> u32 { + self.h + } + + pub fn kind(&self) -> Kind { + self.kind + } + + /// The row-major floats, `channels()` per pixel. + pub fn data(&self) -> &[f32] { + self.data.as_slice() + } + + /// The shared buffer behind [`Image::data`]. + pub fn shared_data(&self) -> &Arc> { + &self.data + } + + pub fn channels(&self) -> usize { + self.kind.channels() + } + + pub fn is_gray(&self) -> bool { + self.kind == Kind::Gray + } + + /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). + #[inline] + pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { + let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); + let i = y * self.w as usize + x; + match self.kind { + Kind::Gray => { + let v = self.data.get(i).copied().unwrap_or(0.0); + [v, v, v, 1.0] + } + Kind::Color => { + let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + [s[0], s[1], s[2], s[3]] + } + } + } + + /// The gray value, or the Rec. 709 luminance of a color image. + #[inline] + pub fn get_gray(&self, x: i64, y: i64, tile: bool) -> f32 { + let p = self.get(x, y, tile); + match self.kind { + Kind::Gray => p[0], + Kind::Color => luminance(p), + } + } + + /// Bilinear sample at normalized `(u, v)`; pixel centers sit at `(i + 0.5) / w`. The texel + /// coordinate is `u × w − 0.5`; its floor and the next index are wrapped or clamped, and the + /// four texels are weighted `(1 − α)(1 − β)`, `α(1 − β)`, `(1 − α)β` and `αβ` by the fractional + /// parts `α` and `β`. A texel with weight 0 does not enter the sum, so an infinite neighbor + /// leaves a sample at a texel center unchanged. NaN or infinite coordinates give `[0, 0, 0, 1]`. + #[inline] + pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + return [0.0, 0.0, 0.0, 1.0]; + }; + let fx = u * self.w as f32 - 0.5; + let fy = v * self.h as f32 - 0.5; + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x0, y0) = (x0 as i64, y0 as i64); + let taps = [((1.0 - tx) * (1.0 - ty), x0, y0), (tx * (1.0 - ty), x0 + 1, y0), ((1.0 - tx) * ty, x0, y0 + 1), (tx * ty, x0 + 1, y0 + 1)]; + // Summed in f64: the rounded weights can add up to slightly more than 1, which would + // overflow a finite HDR value near `f32::MAX` in f32. A finite sum is clamped to the f32 + // range; an infinite texel still gives an infinite or NaN sample. + let mut o = [0.0f64; 4]; + for (weight, x, y) in taps { + if weight == 0.0 { + continue; + } + let p = self.get(x, y, tile); + for (o, p) in o.iter_mut().zip(p) { + *o += f64::from(weight) * f64::from(p); + } + } + o.map(|v| if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 }) + } + + #[inline] + pub fn sample_gray(&self, u: f32, v: f32, tile: bool) -> f32 { + let p = self.sample(u, v, tile); + match self.kind { + Kind::Gray => p[0], + Kind::Color => luminance(p), + } + } + + /// Nearest sample at normalized `(u, v)`: the texel `floor(u × w)`, wrapped or clamped. NaN or + /// infinite coordinates give `[0, 0, 0, 1]`. + #[inline] + pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + return [0.0, 0.0, 0.0, 1.0]; + }; + let (x, y) = ((u * self.w as f32).floor() as i64, (v * self.h as f32).floor() as i64); + // A repeated coordinate is below 1, so its texel is below the size even where `u × w` + // rounds up to it. + let (x, y) = if tile { (x.min(i64::from(self.w) - 1), y.min(i64::from(self.h) - 1)) } else { (x, y) }; + self.get(x, y, tile) + } + + /// Map every pixel (as RGBA) to a new image of `kind`, same size. When a result of that size + /// would be over `isize::MAX` bytes, which only an image allowed by raised [`Limits`] can + /// reach, each side is clamped to `1..=MAX_SIDE` and the result maps the top-left part of this + /// image. [`Image::try_map`] returns [`ImageError::TooLarge`] instead. + pub fn map(&self, kind: Kind, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Image { + Image::build(self.w, self.h, kind, |x, y| f(self.get(i64::from(x), i64::from(y), false))) + } + + /// [`Image::map`] with the new image checked against `limits` and its memory reserved first. + pub fn try_map(&self, kind: Kind, limits: &Limits, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Result { + Image::try_build(self.w, self.h, kind, limits, |x, y| f(self.get(i64::from(x), i64::from(y), false))) + } + + /// [`Image::to_kind`] with the result checked against `limits`, also when the kind is + /// unchanged, and the memory of a new image reserved first. + pub fn try_to_kind(&self, kind: Kind, limits: &Limits) -> Result { + limits.check(self.w, self.h, kind)?; + match (self.kind, kind) { + (Kind::Gray, Kind::Gray) | (Kind::Color, Kind::Color) => Ok(self.clone()), + (Kind::Color, Kind::Gray) => self.try_map(Kind::Gray, limits, |p| [luminance(p), 0.0, 0.0, 0.0]), + (Kind::Gray, Kind::Color) => self.try_map(Kind::Color, limits, |p| p), + } + } + + /// This image as grayscale (luminance of a color image), same size. + pub fn to_gray(&self) -> Image { + match self.kind { + Kind::Gray => self.clone(), + Kind::Color => self.map(Kind::Gray, |p| [luminance(p), 0.0, 0.0, 0.0]), + } + } + + /// This image as RGBA (gray copied to RGB, alpha 1). A gray image goes through + /// [`Image::map`], so a result over `isize::MAX` bytes is clamped as `map` describes. + pub fn to_color(&self) -> Image { + match self.kind { + Kind::Color => self.clone(), + Kind::Gray => self.map(Kind::Color, |p| p), + } + } + + /// [`Image::to_gray`] or [`Image::to_color`]. + pub fn to_kind(&self, kind: Kind) -> Image { + match kind { + Kind::Gray => self.to_gray(), + Kind::Color => self.to_color(), + } + } + + /// Resample to `w × h`, each side clamped to `1..=MAX_SIDE`: a box average when both sides + /// shrink by whole factors, otherwise bilinear samples at the new pixel centers. + pub fn resize(&self, w: u32, h: u32, tile: bool) -> Image { + let (w, h) = clamp_size(w, h); + if w == self.w && h == self.h { + return self.clone(); + } + Image::build(w, h, self.kind, self.resampler(w, h, tile)) + } + + /// [`Image::resize`] without the clamp: the new size is checked against `limits`, also when it + /// equals the current size, and its memory reserved first. + pub fn try_resize(&self, w: u32, h: u32, tile: bool, limits: &Limits) -> Result { + limits.check(w, h, self.kind)?; + if w == self.w && h == self.h { + return Ok(self.clone()); + } + Image::try_build(w, h, self.kind, limits, self.resampler(w, h, tile)) + } + + /// The pixel function of a resample to `w × h`, both at least 1. + fn resampler(&self, w: u32, h: u32, tile: bool) -> Box [f32; 4] + Sync + '_> { + let (w, h) = (w.max(1), h.max(1)); + if w <= self.w && h <= self.h && self.w.is_multiple_of(w) && self.h.is_multiple_of(h) { + let (fx, fy) = (i64::from(self.w / w), i64::from(self.h / h)); + let inv = 1.0 / (fx * fy) as f64; + return Box::new(move |x, y| { + // Summed in f64, so finite HDR values near `f32::MAX` average without overflow. + let mut s = [0.0f64; 4]; + for j in 0..fy { + for i in 0..fx { + let p = self.get(i64::from(x) * fx + i, i64::from(y) * fy + j, tile); + for (s, p) in s.iter_mut().zip(p) { + *s += f64::from(p); + } + } + } + s.map(|v| (v * inv) as f32) + }); + } + let (iw, ih) = (1.0 / w as f32, 1.0 / h as f32); + Box::new(move |x, y| self.sample((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih, tile)) + } + + /// Raw float access for gray images (`None` for color). + pub fn gray_data(&self) -> Option<&[f32]> { + (self.kind == Kind::Gray).then_some(self.data.as_slice()) + } + + /// 8-bit sRGB-encoded RGBA for display (gray shown as is; color through the sRGB curve). + /// Values are clamped to `0..=1` first; NaN becomes 0. The result has 4 bytes per pixel, never + /// more than the float data's own bytes. + pub fn to_rgba8_display(&self) -> Vec { + let mut out = vec![0u8; self.display_len()]; + self.fill_display(&mut out); + out + } + + /// [`Image::to_rgba8_display`] with its memory reserved first. + pub fn try_to_rgba8_display(&self) -> Result, ImageError> { + let len = self.display_len(); + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(self.w, self.h))?; + out.resize(len, 0); + self.fill_display(&mut out); + Ok(out) + } + + /// Bytes of the display copy: 4 per pixel, never more than the float data's own bytes. + fn display_len(&self) -> usize { + self.data.len() / self.channels() * 4 + } + + fn fill_display(&self, out: &mut [u8]) { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let pixel = |(i, px): (usize, &mut [u8])| match self.kind { + Kind::Gray => { + let v = q(self.data.get(i).copied().unwrap_or(0.0)); + px.copy_from_slice(&[v, v, v, 255]); + } + Kind::Color => { + let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + px.copy_from_slice(&[q(linear_to_srgb(s[0])), q(linear_to_srgb(s[1])), q(linear_to_srgb(s[2])), q(s[3])]); + } + }; + #[cfg(feature = "parallel")] + out.par_chunks_mut(4).enumerate().for_each(pixel); + #[cfg(not(feature = "parallel"))] + out.chunks_mut(4).enumerate().for_each(pixel); + } + + /// Mean of each channel (as RGBA), e.g. for tests and auto levels. A NaN or infinite pixel + /// makes its channel's mean non-finite. + pub fn mean(&self) -> [f32; 4] { + let c = self.channels(); + let n = f64::from(self.w) * f64::from(self.h); + let mut s = [0f64; 4]; + for px in self.data.chunks(c) { + for (k, v) in px.iter().enumerate() { + s[k] += f64::from(*v); + } + } + if c == 1 { + let m = (s[0] / n) as f32; + return [m, m, m, 1.0]; + } + s.map(|v| (v / n) as f32) + } + + /// Minimum and maximum over all channels (alpha excluded). NaN values are skipped; `(0, 0)` + /// when every value is NaN. + pub fn range(&self) -> (f32, f32) { + let c = self.channels(); + let mut lo = f32::INFINITY; + let mut hi = f32::NEG_INFINITY; + for px in self.data.chunks(c) { + for v in px.iter().take(c.min(3)) { + lo = lo.min(*v); + hi = hi.max(*v); + } + } + if lo > hi { (0.0, 0.0) } else { (lo, hi) } + } +} + +/// Rec. 709 luminance of a linear RGB(A) pixel. +#[inline] +pub fn luminance(p: [f32; 4]) -> f32 { + 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2] +} + +/// The sRGB encoding of a linear value. NaN stays NaN. +#[inline] +pub fn linear_to_srgb(v: f32) -> f32 { + if v.is_nan() || v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// The linear value of an sRGB-encoded value. NaN stays NaN. +#[inline] +pub fn srgb_to_linear(v: f32) -> f32 { + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +/// Encode the bitmap name and its requested color space without ambiguity. +/// Plain sRGB names remain readable by simple resource callbacks. +pub fn resource_key(name: &str, linear: bool) -> String { + if linear { + format!("\u{1}L{name}") + } else if name.starts_with('\u{1}') { + format!("\u{1}S{name}") + } else { + name.to_string() + } +} + +/// Split a key made by [`resource_key`] into its name and data-map flag. +pub fn split_resource_key(key: &str) -> (&str, bool) { + if let Some(name) = key.strip_prefix("\u{1}L") { + (name, true) + } else if let Some(name) = key.strip_prefix("\u{1}S") { + (name, false) + } else { + (key, false) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sample_survives_huge_coordinates() { + let img = Image::gray(8, 8, |x, _| x as f32); + for u in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN] { + for tile in [true, false] { + let p = img.sample(u, u, tile); + assert!(p.iter().all(|c| c.is_finite())); + } + } + } + + #[test] + fn resource_keys_round_trip() { + for name in ["n", "", "\u{1}Lnormal", "\u{1}Sn", "n\u{1}linear"] { + for linear in [false, true] { + assert_eq!(split_resource_key(&resource_key(name, linear)), (name, linear)); + } + } + } + + #[test] + fn sample_wraps_and_clamps() { + let img = Image::gray(4, 1, |x, _| x as f32); + assert_eq!(img.get(-1, 0, true)[0], 3.0); + assert_eq!(img.get(-1, 0, false)[0], 0.0); + // Halfway between the last and the (wrapped) first pixel. + assert!((img.sample(1.0, 0.5, true)[0] - 1.5).abs() < 1e-5); + } + + #[test] + fn resize_box_and_bilinear() { + let img = Image::gray(4, 4, |x, _| if x < 2 { 0.0 } else { 1.0 }); + let small = img.resize(2, 2, true); + assert_eq!(small.data.as_slice(), &[0.0, 1.0, 0.0, 1.0]); + let big = small.resize(8, 8, false); + assert_eq!(big.w, 8); + assert!(big.data[0] < big.data[7]); + } + + #[test] + fn hostile_sizes_are_clamped() { + let img = Image::filled(0, u32::MAX, Kind::Gray, [0.5; 4]); + assert_eq!((img.w, img.h), (1, MAX_SIDE)); + assert_eq!(img.sample(f32::NAN, 0.0, true), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn conversions() { + let c = Image::filled(2, 2, Kind::Color, [1.0, 1.0, 1.0, 1.0]); + assert!((c.to_gray().data[0] - 1.0).abs() < 1e-5); + assert_eq!(c.to_rgba8_display()[0], 255); + } + + /// Texel values 0, 5 and 1: the blend of the last and first texels (0.5) differs from the + /// middle texel (5), so a wrong repeat period shows. + fn stripe() -> Image { + Image::gray(3, 1, |x, _| [0.0, 5.0, 1.0][x as usize]) + } + + #[test] + fn repeat_keeps_its_period_at_large_coordinates() { + let img = stripe(); + // Every whole number repeats u = 0, which falls halfway between the last and first texels. + let at_zero = img.sample(0.0, 0.5, true)[0]; + assert!((at_zero - 0.5).abs() < 1e-6); + for u in [1.0e9_f32, -1.0e9, 4.0e9, 3.0e12] { + assert_eq!(img.sample(u, 0.5, true)[0], at_zero, "bilinear u = {u}"); + assert_eq!(img.sample_nearest(u, 0.5, true)[0], 0.0, "nearest u = {u}"); + } + assert_eq!(img.sample_nearest(1.0e19, 0.5, true)[0], 0.0); + assert_eq!(img.sample_nearest(-1.0e19, 0.5, true)[0], 0.0); + } + + #[test] + fn clamp_selects_the_edges_at_large_coordinates() { + let img = stripe(); + for u in [2.0_f32, 1.0e9, 1.0e19, f32::MAX] { + assert_eq!(img.sample(u, 0.5, false)[0], 1.0); + assert_eq!(img.sample_nearest(u, 0.5, false)[0], 1.0); + } + for u in [-1.0_f32, -1.0e9, -1.0e19, f32::MIN] { + assert_eq!(img.sample(u, 0.5, false)[0], 0.0); + assert_eq!(img.sample_nearest(u, 0.5, false)[0], 0.0); + } + } + + #[test] + fn nearest_follows_the_texel_floor() { + let img = Image::gray(4, 1, |x, _| x as f32); + // floor(u × 4): u = 1.0 repeats to texel 0 and clamps to texel 3. + assert_eq!(img.sample_nearest(0.24, 0.5, true)[0], 0.0); + assert_eq!(img.sample_nearest(0.25, 0.5, true)[0], 1.0); + assert_eq!(img.sample_nearest(1.0, 0.5, true)[0], 0.0); + assert_eq!(img.sample_nearest(1.0, 0.5, false)[0], 3.0); + assert_eq!(img.sample_nearest(-0.01, 0.5, true)[0], 3.0); + } + + #[test] + fn bilinear_weights_follow_the_fractional_texel_coordinate() { + // u × 4 − 0.5 = 1.25: texel 1 weighted 0.75 and texel 2 weighted 0.25. + let img = Image::gray(4, 1, |x, _| [0.0, 2.0, 6.0, 0.0][x as usize]); + assert!((img.sample(1.75 / 4.0, 0.5, false)[0] - 3.0).abs() < 1e-6); + // Two axes: the four texels of a 2 × 2 image at the image center weigh a quarter each. + let sq = Image::gray(2, 2, |x, y| [1.0, 3.0, 5.0, 11.0][(y * 2 + x) as usize]); + assert!((sq.sample(0.5, 0.5, false)[0] - 5.0).abs() < 1e-6); + } + + #[test] + fn small_negative_coordinates_repeat_to_the_last_texel() { + let img = Image::gray(4, 1, |x, _| x as f32); + for u in [-1.0e-8_f32, -1.0e-30, -f32::MIN_POSITIVE] { + assert_eq!(img.sample_nearest(u, 0.5, true)[0], 3.0, "u = {u}"); + assert!((img.sample(u, 0.5, true)[0] - 1.5).abs() < 1e-5, "u = {u}"); + } + let wide = Image::gray(MAX_SIDE, 1, |x, _| x as f32); + assert_eq!(wide.sample_nearest(-1.0e-8, 0.5, true)[0], (MAX_SIDE - 1) as f32); + } + + #[test] + fn bilinear_ignores_zero_weight_texels_and_does_not_overflow() { + let l = Limits::default(); + let Ok(img) = Image::from_data(2, 1, Kind::Gray, vec![1.0, f32::INFINITY], &l) else { panic!("valid 2 x 1 image") }; + // The center of texel 0 gives texel 0, though its neighbor is infinite. + assert_eq!(img.sample(0.25, 0.5, false)[0], 1.0); + let Ok(hdr) = Image::from_data(2, 1, Kind::Gray, vec![f32::MAX, -f32::MAX], &l) else { panic!("valid 2 x 1 image") }; + assert_eq!(hdr.sample(0.5, 0.5, false)[0], 0.0); + // Rounded weights can sum past 1; a constant image of the largest float stays finite. + let max = Image::filled(2, 2, Kind::Gray, [f32::MAX; 4]); + let t = 0.5 + 2.0_f32.powi(-24); + for tile in [false, true] { + assert!(max.sample(0.250_012_5, t, tile)[0].is_finite(), "tile = {tile}"); + assert_eq!(max.sample(t, t, tile)[0], f32::MAX, "tile = {tile}"); + } + } + + #[test] + fn equality_does_not_depend_on_buffer_sharing() { + let img = Image::filled(2, 1, Kind::Gray, [f32::NAN; 4]); + let rebuilt = Image::filled(2, 1, Kind::Gray, [f32::NAN; 4]); + // NaN pixels compare unequal as floats do, whether or not the buffer is shared. + assert_ne!(img, rebuilt); + assert_ne!(img, img.clone()); + let finite = Image::filled(2, 1, Kind::Gray, [0.5; 4]); + assert_eq!(finite, finite.clone()); + assert_eq!(finite, Image::filled(2, 1, Kind::Gray, [0.5; 4])); + } + + #[test] + fn box_shrink_averages_large_hdr_values() { + let img = Image::filled(2, 2, Kind::Color, [f32::MAX, -f32::MAX, 1.0, 1.0]); + assert_eq!(img.resize(1, 1, false).data(), &[f32::MAX, -f32::MAX, 1.0, 1.0]); + } + + #[test] + fn fallible_operations_check_the_limits() { + let img = Image::gray(4, 4, |x, y| (x + 4 * y) as f32); + let l = Limits::default(); + assert_eq!(img.try_resize(2, 2, true, &l), Ok(img.resize(2, 2, true))); + assert_eq!(img.try_resize(7, 3, false, &l), Ok(img.resize(7, 3, false))); + assert_eq!(img.try_resize(0, 2, false, &l), Err(ImageError::BadSize(0, 2))); + let small = Limits { max_bytes: 100, ..Limits::default() }; + assert_eq!(img.try_resize(8, 8, false, &small), Err(ImageError::TooLarge(8, 8))); + assert_eq!(img.try_to_kind(Kind::Color, &small), Err(ImageError::TooLarge(4, 4))); + assert_eq!(img.try_to_kind(Kind::Color, &l), Ok(img.to_color())); + assert_eq!(img.try_to_kind(Kind::Gray, &small), Ok(img.clone())); + assert_eq!(img.try_map(Kind::Gray, &l, |p| [p[0] * 2.0; 4]), Ok(img.map(Kind::Gray, |p| [p[0] * 2.0; 4]))); + assert_eq!(img.try_to_rgba8_display(), Ok(img.to_rgba8_display())); + } + + #[test] + fn unchanged_results_are_checked_against_the_limits() { + let img = Image::gray(4, 4, |x, y| (x + 4 * y) as f32); + let tiny = Limits { max_pixels: 8, ..Limits::default() }; + assert_eq!(img.try_resize(4, 4, false, &tiny), Err(ImageError::TooLarge(4, 4))); + assert_eq!(img.try_to_kind(Kind::Gray, &tiny), Err(ImageError::TooLarge(4, 4))); + let narrow = Limits { max_side: 3, ..Limits::default() }; + assert_eq!(img.try_resize(4, 4, false, &narrow), Err(ImageError::BadSize(4, 4))); + } + + #[test] + fn generate_uv_spans_the_clamped_size() { + let img = Image::generate_uv(MAX_SIDE + 100, 1, Kind::Gray, |u, _| [u, 0.0, 0.0, 0.0]); + assert_eq!(img.w, MAX_SIDE); + let last = img.data[MAX_SIDE as usize - 1]; + assert!((last - (MAX_SIDE as f32 - 0.5) / MAX_SIDE as f32).abs() < 1e-6, "{last}"); + } + + #[test] + fn checked_sizes_reject_zero_and_long_sides() { + let l = Limits::default(); + assert_eq!(Image::try_filled(0, 4, Kind::Gray, [0.0; 4], &l), Err(ImageError::BadSize(0, 4))); + assert_eq!(Image::try_filled(4, 0, Kind::Color, [0.0; 4], &l), Err(ImageError::BadSize(4, 0))); + assert_eq!(Image::from_data(0, 1, Kind::Gray, Vec::new(), &l), Err(ImageError::BadSize(0, 1))); + assert_eq!(Image::try_generate(MAX_SIDE + 1, 1, Kind::Gray, &l, |_, _| [0.0; 4]), Err(ImageError::BadSize(MAX_SIDE + 1, 1))); + assert!(Image::try_filled(3, 2, Kind::Color, [0.25; 4], &l).is_ok_and(|i| i.data().len() == 24 && i.width() == 3)); + } + + #[test] + fn checked_sizes_respect_the_pixel_and_byte_limits() { + let l = Limits { max_bytes: 1000, ..Limits::default() }; + assert_eq!(l.check(15, 16, Kind::Gray), Ok(240)); + assert_eq!(l.check(16, 16, Kind::Gray), Err(ImageError::TooLarge(16, 16))); + assert_eq!(Image::try_filled(8, 8, Kind::Color, [0.0; 4], &l), Err(ImageError::TooLarge(8, 8))); + let l = Limits { max_pixels: 100, ..Limits::default() }; + assert_eq!(l.check(10, 10, Kind::Color), Ok(400)); + assert_eq!(l.check(10, 11, Kind::Gray), Err(ImageError::TooLarge(10, 11))); + // The default limits accept a full 8192 × 8192 color plane and nothing longer. + assert_eq!(Limits::default().check(MAX_SIDE, MAX_SIDE, Kind::Color), Ok(1 << 28)); + } + + #[test] + fn checked_sizes_do_not_overflow() { + let open = Limits { max_side: u32::MAX, max_pixels: u64::MAX, max_bytes: u64::MAX }; + assert_eq!(open.check(u32::MAX, u32::MAX, Kind::Color), Err(ImageError::TooLarge(u32::MAX, u32::MAX))); + assert_eq!(open.check(u32::MAX, u32::MAX, Kind::Gray), Err(ImageError::TooLarge(u32::MAX, u32::MAX))); + } + + /// `isize::MAX` on a 32-bit target such as `wasm32`. + const BOUND_32: u64 = i32::MAX as u64; + + #[test] + fn checked_sizes_respect_target_isize_bound() { + let open = Limits { max_side: u32::MAX, max_pixels: u64::MAX, max_bytes: u64::MAX }; + // 16,385 × 8,192 gray is 512 MiB and 16 KiB; its color form is over 2 GiB. + assert_eq!(open.check_within(16_385, 8_192, Kind::Gray, BOUND_32), Ok(16_385 * 8_192)); + assert_eq!(open.check_within(16_385, 8_192, Kind::Color, BOUND_32), Err(ImageError::TooLarge(16_385, 8_192))); + assert_eq!(open.check_within(MAX_SIDE, MAX_SIDE, Kind::Color, BOUND_32), Ok(1 << 28)); + } + + #[test] + fn infallible_expansion_clamps_at_target_bound() { + assert_eq!(bounded_size(16_385, 8_192, Kind::Gray, BOUND_32), (16_385, 8_192, 16_385 * 8_192)); + assert_eq!(bounded_size(16_385, 8_192, Kind::Color, BOUND_32), (MAX_SIDE, MAX_SIDE, 1 << 28)); + assert_eq!(bounded_size(MAX_SIDE, MAX_SIDE, Kind::Color, BOUND_32), (MAX_SIDE, MAX_SIDE, 1 << 28)); + assert_eq!(bounded_size(3, 2, Kind::Color, BOUND_32), (3, 2, 24)); + // A bound below even the clamped size gives one pixel. + assert_eq!(bounded_size(16_385, 8_192, Kind::Color, 64), (1, 1, 4)); + assert_eq!(bounded_size(u32::MAX, u32::MAX, Kind::Gray, MAX_ALLOC_BYTES), (MAX_SIDE, MAX_SIDE, 1 << 26)); + } + + #[test] + fn checked_byte_len_rejects_arithmetic_overflow() { + assert_eq!(checked_byte_len(u32::MAX, u32::MAX, Kind::Color), None); + assert_eq!(checked_byte_len(u32::MAX, u32::MAX, Kind::Gray), None); + assert_eq!(checked_byte_len(MAX_SIDE, MAX_SIDE, Kind::Color), Some(1 << 30)); + } + + #[test] + fn from_data_checks_the_length() { + let l = Limits::default(); + assert_eq!(Image::from_data(2, 2, Kind::Color, vec![0.0], &l), Err(ImageError::BadDataLength { expected: 16, found: 1 })); + assert_eq!(Image::from_data(2, 2, Kind::Color, vec![0.0; 17], &l), Err(ImageError::BadDataLength { expected: 16, found: 17 })); + let img = Image::from_data(2, 1, Kind::Gray, vec![-2.0, 3.5], &l); + assert!(img.is_ok_and(|i| i.get(0, 0, false)[0] == -2.0 && i.get(1, 0, false)[0] == 3.5)); + } + + #[test] + fn non_finite_pixels_have_defined_results() { + let l = Limits::default(); + let img = Image::from_data(1, 1, Kind::Color, vec![f32::NAN, f32::INFINITY, -1.0, 2.0], &l); + let Ok(img) = img else { panic!("valid 1 x 1 image") }; + assert_eq!(img.to_rgba8_display(), vec![0, 255, 0, 255]); + let g = Image::from_data(3, 1, Kind::Gray, vec![f32::NAN, -4.0, 8.0], &l); + let Ok(g) = g else { panic!("valid 3 x 1 image") }; + assert_eq!(g.range(), (-4.0, 8.0)); + assert!(g.mean()[0].is_nan()); + } + + #[test] + fn srgb_encoding_keeps_nan() { + assert!(linear_to_srgb(f32::NAN).is_nan()); + assert!(srgb_to_linear(f32::NAN).is_nan()); + assert_eq!(linear_to_srgb(0.0), 0.0); + assert!((linear_to_srgb(1.0) - 1.0).abs() < 1e-6); + assert!((srgb_to_linear(linear_to_srgb(0.5)) - 0.5).abs() < 1e-6); + } + + #[test] + fn whole_factor_shrink_stays_exact_with_custom_limits() { + let l = Limits { max_side: 16, ..Limits::default() }; + let img = Image::try_generate(4, 2, Kind::Color, &l, |x, y| [x as f32, y as f32, 0.0, 1.0]); + let Ok(img) = img else { panic!("valid 4 x 2 image") }; + let half = img.resize(2, 1, false); + assert_eq!(half.data(), &[0.5, 0.5, 0.0, 1.0, 2.5, 0.5, 0.0, 1.0]); + assert_eq!(img.to_gray().width(), 4); + } +} diff --git a/crates/video/src/av1/encode/mod.rs b/crates/video/src/av1/encode/mod.rs index 0d8e2b04fd..10e88d0ada 100644 --- a/crates/video/src/av1/encode/mod.rs +++ b/crates/video/src/av1/encode/mod.rs @@ -600,8 +600,13 @@ impl Encoder { /// Encodes one frame. pub fn encode(&mut self, frame: &Frame) -> Result { + self.encode_with_key(frame, false) + } + + /// Encodes one frame, optionally forcing a keyframe regardless of `keyint`. + pub fn encode_with_key(&mut self, frame: &Frame, force_key: bool) -> Result { self.check_frame(frame)?; - let key = self.frame_num.is_multiple_of(self.cfg.keyint.max(1) as u64); + let key = force_key || self.frame_num.is_multiple_of(self.cfg.keyint.max(1) as u64); let src = self.load_source(frame); let (frame_obu, rf) = match self.cfg.rate { RateControl::ConstantQ(q) => self.encode_frame(&src, key, q.max(1)), diff --git a/crates/wordmodel/src/numbering.rs b/crates/wordmodel/src/numbering.rs index 5ab94ea877..91eb221b8d 100644 --- a/crates/wordmodel/src/numbering.rs +++ b/crates/wordmodel/src/numbering.rs @@ -70,12 +70,18 @@ impl Default for Level { } } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[derive(Clone, Debug, Serialize, Deserialize, Default)] #[serde(default)] pub struct AbstractNum { pub id: u32, pub name: Option, pub levels: Vec, + /// Which levels were defined in the source file. `None` is used by model-created definitions, + /// where the populated `levels` vector is authoritative. DOCX readers set this when they fill + /// unspecified Word levels with their effective defaults. This reader-only provenance is not + /// serialized as part of the document model. + #[serde(skip)] + pub explicit_levels: Option<[bool; 9]>, /// Word's list identity (`w:nsid`, 8 hex digits), which it uses to match lists across /// documents (paste, compare); kept from the file. #[serde(skip_serializing_if = "Option::is_none")] @@ -89,6 +95,20 @@ pub struct AbstractNum { pub multi_level_type: Option, } +// Explicit source-level presence is reader provenance used to distinguish an omitted Word level +// from an effective default. It is intentionally not part of the document model's structural +// equality, just as it is not serialized. +impl PartialEq for AbstractNum { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + && self.name == other.name + && self.levels == other.levels + && self.nsid == other.nsid + && self.tmpl == other.tmpl + && self.multi_level_type == other.multi_level_type + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] #[serde(default, rename_all = "camelCase")] pub struct Num { @@ -236,6 +256,20 @@ impl Numbering { } self.abstract_of(num)?.levels.get(level as usize) } + /// Whether the source definition supplied this level, or a per-numbering override defines it. + /// + /// [`Self::level`] also exposes Word's effective default for omitted levels. This method lets + /// importers preserve formats whose historical behavior distinguishes an explicit level from + /// that effective fallback. Older serialized and model-created definitions have no source + /// presence metadata, so their populated levels count as defined. + pub fn level_is_defined(&self, num: u32, level: u8) -> bool { + let Some(n) = self.num(num) else { return false }; + if n.level_overrides.iter().any(|(i, _)| *i == level) { + return true; + } + let Some(a) = self.abstract_of(num) else { return false }; + a.explicit_levels.map_or_else(|| a.levels.get(level as usize).is_some(), |levels| levels.get(level as usize).copied().unwrap_or(false)) + } /// Create a new list of `kind`; returns the `num` id. List ids run out only past `u32::MAX` /// lists, more than memory holds; then nothing is added and the id is 0, "no list". pub fn add_list(&mut self, kind: ListKind) -> u32 { @@ -485,6 +519,42 @@ const MAX_LABEL_BYTES: usize = 256; mod tests { use super::*; + #[test] + fn explicit_level_metadata_preserves_effective_defaults_and_old_models() { + let mut numbering = Numbering::default(); + let id = numbering.add_list(ListKind::Numbered); + assert!(numbering.level_is_defined(id, 0)); + assert!(numbering.level_is_defined(id, 8)); + + let abstract_id = numbering.num(id).unwrap().abstract_id; + let mut explicit = [false; 9]; + explicit[0] = true; + numbering.abstracts.iter_mut().find(|a| a.id == abstract_id).unwrap().explicit_levels = Some(explicit); + + // Effective Word defaults remain available to existing model callers, while importers can + // tell that this source file supplied only level zero. + assert!(numbering.level(id, 1).is_some()); + assert!(!numbering.level_is_defined(id, 1)); + assert!(numbering.level_is_defined(id, 0)); + + // Old serialized definitions have no presence marker; populated levels remain valid. + numbering.abstracts.iter_mut().find(|a| a.id == abstract_id).unwrap().explicit_levels = None; + assert!(numbering.level_is_defined(id, 8)); + + // A per-numbering level definition takes precedence over the abstract's missing level. + numbering.abstracts.iter_mut().find(|a| a.id == abstract_id).unwrap().explicit_levels = Some(explicit); + numbering.nums.iter_mut().find(|n| n.id == id).unwrap().level_overrides.push((1, Level::default())); + assert!(numbering.level_is_defined(id, 1)); + } + + #[test] + fn explicit_level_metadata_does_not_change_model_equality() { + let mut with_metadata = AbstractNum::default(); + let without_metadata = with_metadata.clone(); + with_metadata.explicit_levels = Some([true; 9]); + assert_eq!(with_metadata, without_metadata); + } + /// Read-only counter APIs retain the renderer's bounds and never advance a list. #[test] fn reference_labels_are_bounded_and_do_not_advance_counters() { diff --git a/crates/wordmodel/src/para.rs b/crates/wordmodel/src/para.rs index 0ed90870b1..bbfeb9cbcf 100644 --- a/crates/wordmodel/src/para.rs +++ b/crates/wordmodel/src/para.rs @@ -24,7 +24,7 @@ pub use inline_object::{CanvasStyle, GroupChild, InlineObject, MAX_GROUP_CHILDRE pub use run::{COLUMN_BREAK, LINE_BREAK, NB_HYPHEN, NBSP, OBJ, PAGE_BREAK, Run, SOFT_HYPHEN, next_rev}; /// A paragraph. -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Serialize, Deserialize)] pub struct Paragraph { pub text: String, pub runs: Vec, @@ -54,6 +54,19 @@ impl PartialEq for Paragraph { } } +impl std::fmt::Debug for Paragraph { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Paragraph") + .field("text", &self.text) + .field("runs", &self.runs) + .field("props", &self.props) + .field("mark", &self.mark) + .field("objects", &self.objects) + .field("section", &self.section) + .finish_non_exhaustive() + } +} + impl Default for Paragraph { fn default() -> Self { Paragraph::new() diff --git a/crates/wordmodel/src/props.rs b/crates/wordmodel/src/props.rs index 38feba083c..65a59592c2 100644 --- a/crates/wordmodel/src/props.rs +++ b/crates/wordmodel/src/props.rs @@ -93,6 +93,16 @@ mod tests { } } + #[test] + fn explicit_off_values_disable_underline() { + for value in ["off", "false", "0"] { + assert_eq!(Underline::from_ooxml(value), Underline::None, "{value}"); + } + assert_eq!(Underline::from_ooxml("none"), Underline::None); + assert_eq!(Underline::from_ooxml("single"), Underline::Single); + assert_eq!(Underline::from_ooxml("unknown"), Underline::Single); + } + /// The 16 `w14:ligatures` values of [MS-DOCX], each to its flags and back. #[test] fn ligature_names() { diff --git a/crates/wordmodel/src/props/char_props.rs b/crates/wordmodel/src/props/char_props.rs index 3cde0b132f..db08ce2fe6 100644 --- a/crates/wordmodel/src/props/char_props.rs +++ b/crates/wordmodel/src/props/char_props.rs @@ -51,6 +51,10 @@ impl Underline { } pub fn from_ooxml(s: &str) -> Underline { Underline::ALL.iter().copied().find(|u| u.ooxml() == s).unwrap_or(match s { + // Some Word producers serialize the generic on/off values here, although the + // underline simple type normally uses `none`. Honor an explicit disable rather + // than treating an unrecognized value as the default single underline. + "off" | "false" | "0" => Underline::None, "thickDash" | "dashLong" | "dashedHeavy" | "dashLongHeavy" => Underline::Dash, "dottedHeavy" => Underline::Dotted, "wavyHeavy" => Underline::Wave, diff --git a/crates/wordmodel/src/resolve.rs b/crates/wordmodel/src/resolve.rs index 40449e82cb..7ef12ccdc0 100644 --- a/crates/wordmodel/src/resolve.rs +++ b/crates/wordmodel/src/resolve.rs @@ -66,6 +66,11 @@ pub struct ResolvedChar { pub rtl: bool, /// The whole run uses the complex-script properties (`w:cs`). pub cs: bool, + /// The run says it is not complex script (`w:cs w:val="0"`): its Thai, Indic, Arabic or + /// Hebrew characters take its other font, size, bold and italic, as Word draws them in a run + /// that isn't complex script or right to left. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub cs_off: bool, /// Complex-script font, size, bold and italic (Arabic, Persian, Hebrew… text). pub font_cs: String, /// East Asian font (Chinese, Japanese and Korean text), when one is set. @@ -115,6 +120,7 @@ impl ResolvedChar { lang: c.lang.clone(), rtl: c.rtl.unwrap_or(false), cs: c.cs.unwrap_or(false), + cs_off: c.cs == Some(false), font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()), font_ea: c.font_ea.clone(), size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0), @@ -133,9 +139,11 @@ impl ResolvedChar { pub fn kerned(&self) -> bool { self.kern > 0.0 && self.size >= self.kern } - /// Does a character of this run use the complex-script properties? + /// Does a character of this run use the complex-script properties? Every character of a + /// right-to-left or complex-script run does; otherwise a complex-script character does, + /// unless the run says it is not complex script. pub fn uses_complex(&self, c: char) -> bool { - self.rtl || self.cs || crate::bidi::is_complex_script(c) + self.rtl || self.cs || (!self.cs_off && crate::bidi::is_complex_script(c)) } /// The size glyphs are drawn and measured at. Word sets superscript and subscript text at /// 0.65 of the run's size rounded to the half point, a font size the format can store diff --git a/crates/wordmodel/src/styles.rs b/crates/wordmodel/src/styles.rs index 090df9a05b..1d725efa2a 100644 --- a/crates/wordmodel/src/styles.rs +++ b/crates/wordmodel/src/styles.rs @@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use crate::props::{ - Align, Border, BorderStyle, Borders, CharProps, LineSpacing, ParaProps, Rgb, TabAlign, TabLeader, TabStop, TableLook, TextColor, Underline, - VAlign, + Align, Border, BorderStyle, Borders, CharProps, LineSpacing, ParaProps, PropChange, Rgb, TabAlign, TabLeader, TabStop, TableLook, TextColor, + Underline, VAlign, }; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] @@ -52,6 +52,12 @@ pub struct Style { pub default: bool, /// Table style: conditional formatting for header row, banding etc. pub table: Option, + /// Tracked change to the style's paragraph properties (`w:pPrChange`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub para_change: Option>>, + /// Tracked change to the style's run properties (`w:rPrChange`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub chr_change: Option>>, } /// Table style conditional formats (shading + character formatting per region). @@ -822,6 +828,94 @@ impl StyleSheet { out.chr.style = None; Some(out) } + /// Word draws a run's text with the complex-script font, size, bold and italic only when the run + /// is complex script or right to left (`w:cs`, `w:rtl`) by its own properties, its paragraph + /// style, its table style or the run defaults; a character style saying so, or saying not, + /// doesn't count (nor does its `w:rtl` change the order of the text). Anywhere else the text takes the run's other font and `w:sz`, Thai included, + /// whatever its language or `w:hint` (measured in Word for Windows: Thai text at `w:sz` 22 pt, + /// `w:szCs` 11 pt is drawn at 22 pt), and the same in a `.doc`. WordCraft draws Thai, Lao and Indic characters with the + /// complex-script formatting unless the run says it is not complex script, and counts a character + /// style's `w:cs`; so a run it would draw otherwise says on itself whether it is complex script + /// (`w:cs`, which Word reads the same way). A reader calls this on each paragraph it has read. `table` is the run formatting the table style gives + /// the paragraph's cell. Runs with right-to-left text are left as they are: they are written + /// right to left. + pub fn mark_runs_as_word_draws_them(&self, para: &mut crate::para::Paragraph, table: Option<&CharProps>) { + use crate::bidi::{is_complex_script, is_rtl_script}; + use crate::para::{InlineObject, OBJ}; + // What each run draws: its text, a field kept as one object standing for its result + // (drawn in the run's formatting, and measured in Word to follow the same rule). + let mut drawn = Vec::with_capacity(para.runs.len()); + let (mut at, mut objects) = (0, para.objects.iter()); + for run in ¶.runs { + let mut text = String::new(); + for c in para.text.get(at..at + run.len).unwrap_or("").chars() { + if c != OBJ { + text.push(c); + } else if let Some(InlineObject::Field { result, code: false, .. }) = objects.next() { + text.push_str(result); + } + } + at += run.len; + drawn.push(text); + } + let style = para.props.style.as_deref(); + for (run, text) in para.runs.iter_mut().zip(&drawn) { + if text.is_empty() || text.chars().any(is_rtl_script) { + continue; + } + let word = self.resolve_char_in(style, table, &CharProps { style: None, ..run.props.clone() }); + let mut ours = self.resolve_char_in(style, table, &run.props); + // Right to left only by its character style: Word draws and orders the run as it does + // one that says nothing (measured, Latin and Thai text). + if ours.rtl && !word.rtl { + run.props.rtl = Some(false); + ours = self.resolve_char_in(style, table, &run.props); + } + if word.cs || word.rtl { + if !ours.cs && !ours.rtl { + run.props.cs = Some(true); + } + } else if !ours.rtl && (ours.cs || (!ours.cs_off && text.chars().any(is_complex_script))) { + run.props.cs = Some(false); + } + } + } + /// The run formatting `t`'s table style gives the text of each of its cells, by row and then + /// cell: each of a cell's parts' over the last, lowest precedence first (ECMA-376 §17.7.6), as + /// layout applies it between document defaults and the paragraph's style. `None` when the + /// table has no style. The style and the table's size are worked out once for the whole table, + /// and each set of parts is put together once. + pub fn table_cells_chr(&self, t: &crate::table::Table) -> Option>> { + let st = self.table_style(t.props.style.as_deref()?)?; + let sizes = (st.parts.band_size.unwrap_or(0), st.parts.col_band_size.unwrap_or(0)); + let ncols = t.cols().clamp(1, crate::table::MAX_COLS); + let nrows = t.rows.len(); + let mut made: Vec<(PartSet, CharProps)> = Vec::new(); + let mut out = Vec::with_capacity(nrows); + for (r, row) in t.rows.iter().enumerate() { + let mut g = row.first_grid(); + let mut cells = Vec::with_capacity(row.cells.len()); + for cell in &row.cells { + let span = cell.span(); + let parts = PartSet::of_cell(&t.props.look, sizes, (r, nrows), (g, span, ncols)); + g = g.saturating_add(span); + let chr = match made.iter().find(|(p, _)| *p == parts) { + Some((_, chr)) => chr.clone(), + None => { + let mut chr = CharProps::default(); + for part in parts.iter() { + chr.overlay(&st.part(part).chr); + } + made.push((parts, chr.clone())); + chr + } + }; + cells.push(chr); + } + out.push(cells); + } + Some(out) + } /// Add or replace a style. pub fn upsert(&mut self, st: Style) { match self.styles.iter_mut().find(|s| s.id == st.id) { diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index 6fd34d0bed..83fdad40be 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -5,8 +5,9 @@ //! write: the end-of-central-directory record (and its ZIP64 form), central directory entries //! with ZIP64 sizes, local headers, data descriptors, "stored" and "deflate" entries (inflated //! by `miniz_oxide`), UTF-8 names (flag bit 11 or the Info-ZIP Unicode path field) and CP437 -//! names. Encryption, other compression methods and split archives are refused with a clear -//! error. +//! names. Self-extracting archives with ZIP data after a program stub are supported whether +//! their offsets count from the ZIP data or from the start of the file. Encryption, other +//! compression methods and split archives are refused with a clear error. //! //! The archive is treated as hostile. Every offset and size is checked against the bytes it //! comes from; entries may not overlap each other or the central directory; a name that would @@ -237,11 +238,22 @@ fn method_name(method: u16) -> &'static str { } /// The end of the central directory: (entry count, its size, its offset, where it must end). +/// +/// For a self-extracting archive, the record's offsets may be relative to the ZIP data rather +/// than the start of the executable. The returned directory offset stays as written; its real +/// location is resolved against `dir_limit` when opening the archive. fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { // The end record is in the last 22 + 65535 bytes (it may carry a comment). let lo = data.len().saturating_sub(22 + 65_535); let mut eocd = None; + // A shifted empty SFX archive has no central-directory signature with which to distinguish + // it from an empty EOCD-shaped record inside the preceding archive's comment. Keep it as a + // last resort while searching for an older, structurally stronger candidate. + let mut empty_sfx = None; let mut fallback = None; + // Fake EOCD records in a comment can all describe the same large directory. Cache binary + // directory jumps so checking each candidate does not rescan every entry. + let mut directory_jumps = HashMap::new(); for candidate in (lo..data.len().saturating_sub(21)).rev() { if u32_at(data, candidate) != Some(END) || !u16_at(data, candidate + 20) @@ -253,33 +265,41 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { // consistent candidate is found. This preserves useful damaged-ZIP diagnostics. fallback = Some(candidate); + let count = u16_at(data, candidate + 10).unwrap_or(u16::MAX); let size = u32_at(data, candidate + 12).unwrap_or(u32::MAX); let offset = u32_at(data, candidate + 16).unwrap_or(u32::MAX); - if size == u32::MAX || offset == u32::MAX { - // ZIP64's directory must end exactly where the ZIP64 end record starts. + if count == u16::MAX || size == u32::MAX || offset == u32::MAX { let locator = candidate.checked_sub(20).filter(|&at| u32_at(data, at) == Some(LOCATOR64)); - let valid = locator - .and_then(|at| u64_at(data, at + 8)) - .and_then(|at| usize::try_from(at).ok()) - .filter(|&at| u32_at(data, at) == Some(END64)) - .is_some_and(|at| { - let dir_size = u64_at(data, at + 40).and_then(|n| usize::try_from(n).ok()); - let dir_offset = u64_at(data, at + 48).and_then(|n| usize::try_from(n).ok()); - dir_size.zip(dir_offset).is_some_and(|(size, offset)| offset.checked_add(size) == Some(at)) - }); - if !valid { + let valid = locator.and_then(|locator| find_zip64_end(data, locator)).and_then(|at| { + let count = u64_at(data, at + 32)?; + let dir_size = u64_at(data, at + 40)?; + let dir_offset = u64_at(data, at + 48)?; + locate_directory(data, count, dir_size, dir_offset, at) + .filter(|&(dir, _)| directory_is_exact(data, dir, dir_size, count, &mut directory_jumps)) + .map(|(_, shift)| (at, count == 0 && shift > 0)) + }); + let Some((_, shifted_empty)) = valid else { + continue; + }; + if shifted_empty { + empty_sfx = Some(candidate); continue; } } else { - let end = usize::try_from(offset).ok().and_then(|offset| usize::try_from(size).ok().and_then(|size| offset.checked_add(size))); - if end != Some(candidate) { + let Some((_, shift)) = locate_directory(data, count.into(), size.into(), offset.into(), candidate) + .filter(|&(dir, _)| directory_is_exact(data, dir, size.into(), count.into(), &mut directory_jumps)) + else { + continue; + }; + if count == 0 && shift > 0 { + empty_sfx = Some(candidate); continue; } } eocd = Some(candidate); break; } - let eocd = eocd.or(fallback).ok_or(ZipError::NotZip)?; + let eocd = eocd.or(empty_sfx).or(fallback).ok_or(ZipError::NotZip)?; let field16 = |o: usize| u16_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); let field32 = |o: usize| u32_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); let (disk, dir_disk, on_disk, count) = (field16(4)?, field16(6)?, field16(8)?, field16(10)?); @@ -293,10 +313,7 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { // ZIP64: a locator just before the end record points at the ZIP64 end record. let locator = eocd.checked_sub(20).filter(|&l| u32_at(data, l) == Some(LOCATOR64)).ok_or(ZipError::Damaged("the ZIP64 end record is missing"))?; let missing = ZipError::Damaged("the ZIP64 end record is missing"); - let at = u64_at(data, locator + 8).and_then(|a| usize::try_from(a).ok()).filter(|&a| a < locator).ok_or(missing.clone())?; - if u32_at(data, at) != Some(END64) { - return Err(missing); - } + let at = find_zip64_end(data, locator).ok_or(missing)?; let cut = ZipError::Damaged("the ZIP64 end record is cut short"); let (disk, dir_disk) = (u32_at(data, at + 16).ok_or(cut.clone())?, u32_at(data, at + 20).ok_or(cut.clone())?); let (on_disk, count) = (u64_at(data, at + 24).ok_or(cut.clone())?, u64_at(data, at + 32).ok_or(cut.clone())?); @@ -306,11 +323,114 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { Ok((count, u64_at(data, at + 40).ok_or(cut.clone())?, u64_at(data, at + 48).ok_or(cut)?, at)) } +/// Finds the ZIP64 end record named by `locator`. For an SFX archive with unadjusted offsets, +/// the locator points to where that record was before the stub was prepended, so the record +/// itself immediately before the locator is authoritative. The shifted fallback supports the +/// no-extensible-data layout; ordinary ZIP64 records continue to use the locator's exact offset. +fn find_zip64_end(data: &[u8], locator: usize) -> Option { + let stated = usize::try_from(u64_at(data, locator.checked_add(8)?)?).ok()?; + let valid = |at: usize, shifted: bool| { + if u32_at(data, at) != Some(END64) { + return false; + } + let Some(record_size_at) = at.checked_add(4) else { return false }; + let Some(record_size) = u64_at(data, record_size_at).and_then(|n| usize::try_from(n).ok()) else { return false }; + if at.checked_add(12).and_then(|start| start.checked_add(record_size)) != Some(locator) || (shifted && record_size != 44) { + return false; + } + let Some(size_at) = at.checked_add(40) else { return false }; + let Some(offset_at) = at.checked_add(48) else { return false }; + let Some(size) = u64_at(data, size_at).and_then(|n| usize::try_from(n).ok()) else { return false }; + let Some(offset) = u64_at(data, offset_at).and_then(|n| usize::try_from(n).ok()) else { return false }; + if !shifted { + offset.checked_add(size) == Some(at) + } else { + let empty_directory = size == 0 && u64_at(data, at + 24) == Some(0) && u64_at(data, at + 32) == Some(0); + at > stated + && offset.checked_add(size) == Some(stated) + && at.checked_sub(size).is_some_and(|dir| dir > offset && (empty_directory || u32_at(data, dir) == Some(CENTRAL))) + } + }; + if valid(stated, false) { + return Some(stated); + } + let at = locator.checked_sub(56).filter(|&at| at > stated)?; + valid(at, true).then_some(at) +} + +/// Resolves a directory offset. If the stated offset already points to a central-directory +/// header and the directory ends at `limit`, it is used as is. Otherwise the only correction +/// accepted is a prefix shift that moves the directory to immediately before `limit`. +fn locate_directory(data: &[u8], count: u64, size: u64, stated: u64, limit: usize) -> Option<(usize, usize)> { + let stated = usize::try_from(stated).ok()?; + let size = usize::try_from(size).ok()?; + if stated.checked_add(size) == Some(limit) && (count == 0 || u32_at(data, stated) == Some(CENTRAL)) { + return Some((stated, 0)); + } + let actual = limit.checked_sub(size)?; + if actual > stated && (count == 0 || u32_at(data, actual) == Some(CENTRAL)) { + return Some((actual, actual - stated)); + } + None +} + +fn central_entry_end(data: &[u8], cursor: usize) -> Option { + if u32_at(data, cursor) != Some(CENTRAL) { + return None; + } + let header_end = cursor.checked_add(46).filter(|&at| at <= data.len())?; + let name_len = usize::from(u16_at(data, header_end - 18)?); + let extra_len = usize::from(u16_at(data, header_end - 16)?); + let comment_len = usize::from(u16_at(data, header_end - 14)?); + header_end.checked_add(name_len)?.checked_add(extra_len)?.checked_add(comment_len).filter(|&end| end <= data.len()) +} + +/// Return the offset after `2^power` contiguous central-directory records, memoizing offsets +/// shared by competing EOCD candidates in untrusted comments. +fn central_directory_jump(data: &[u8], start: usize, power: u8, jumps: &mut HashMap<(usize, u8), Option>) -> Option { + if let Some(&cached) = jumps.get(&(start, power)) { + return cached; + } + let end = if power == 0 { + central_entry_end(data, start) + } else { + central_directory_jump(data, start, power - 1, jumps).and_then(|middle| central_directory_jump(data, middle, power - 1, jumps)) + }; + jumps.insert((start, power), end); + end +} + +/// Checks that the declared central-directory entries consume the entire directory. This is +/// used while choosing among EOCD-shaped signatures, where comments may contain many fake records. +fn directory_is_exact(data: &[u8], start: usize, size: u64, count: u64, jumps: &mut HashMap<(usize, u8), Option>) -> bool { + let Ok(size) = usize::try_from(size) else { return false }; + let Some(end) = start.checked_add(size).filter(|&end| end <= data.len()) else { return false }; + // Preserve the existing TooMany diagnostic in `Archive::open` without walking attacker-sized + // entry counts here. + if count > MAX_ENTRIES as u64 { + return true; + } + let mut cursor = start; + let mut remaining = count; + let mut power = 0; + while remaining != 0 { + if remaining & 1 != 0 { + let Some(next) = central_directory_jump(data, cursor, power, jumps) else { + return false; + }; + cursor = next; + } + remaining >>= 1; + power += 1; + } + cursor == end +} + impl<'a> Archive<'a> { pub fn open(data: &'a [u8]) -> Result, ZipError> { let (count, dir_size, dir_at, dir_limit) = find_end(data)?; let past = ZipError::Damaged("the central directory is outside the archive"); - let dir_at = usize::try_from(dir_at).map_err(|_| past.clone())?; + let (dir_at, shift) = locate_directory(data, count, dir_size, dir_at, dir_limit).ok_or(past.clone())?; let dir_end = usize::try_from(dir_size).ok().and_then(|s| dir_at.checked_add(s)).filter(|&e| e <= dir_limit).ok_or(past.clone())?; let dir = data.get(dir_at..dir_end).ok_or(past)?; if count > MAX_ENTRIES as u64 { @@ -357,7 +477,7 @@ impl<'a> Archive<'a> { } } let outside = || ZipError::DamagedEntry(shown(), "is outside the archive"); - let offset = usize::try_from(offset).map_err(|_| outside())?; + let offset = usize::try_from(offset).ok().and_then(|offset| offset.checked_add(shift)).ok_or_else(outside)?; let comp = usize::try_from(comp).map_err(|_| outside())?; // An entry's size is checked when it is read: one too large to read may sit unused. let size = usize::try_from(size).unwrap_or(usize::MAX); diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 9f9d5a13ed..ee4b2cf337 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -1,7 +1,7 @@ //! The zip reader against the layouts writers produce and the archives an attacker would //! (ADR 0054). Archives are made by the independent writer in `tests/support/fla.rs`. -use super::pack::{self, Raw, write}; +use super::pack::{self, Raw, write, write_at}; use super::*; fn zip(files: &[(&str, &[u8], bool)]) -> Vec { @@ -261,6 +261,47 @@ fn central_directory_must_be_consumed_exactly() { assert_eq!(Archive::open(&z).err(), Some(ZipError::Damaged("the central directory has trailing data"))); } +#[test] +fn nonempty_comment_eocd_candidate_does_not_mask_valid_archive() { + let mut bytes = zip(&[("a.xml", b"x", false)]); + let end = bytes.len() - 22; + // The fake EOCD sits in the real EOCD's comment and claims the real directory plus the + // real EOCD as a shifted directory. Candidate selection must reject its trailing bytes. + bytes[end + 20..end + 22].copy_from_slice(&22u16.to_le_bytes()); + bytes.extend_from_slice(&END.to_le_bytes()); + bytes.extend_from_slice(&[0; 4]); + bytes.extend_from_slice(&1u16.to_le_bytes()); + bytes.extend_from_slice(&1u16.to_le_bytes()); + bytes.extend_from_slice(&73u32.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); +} + +#[test] +fn repeated_eocd_directory_candidates_reuse_entry_validation() { + let entries = (0..1024).map(|index| Raw::new(&format!("entry-{index:04}.xml"), b"", false)).collect::>(); + let mut bytes = write(&entries, false); + let eocd = bytes.len() - 22; + bytes[eocd + 20..eocd + 22].copy_from_slice(&1000u16.to_le_bytes()); + bytes.extend_from_slice(&vec![0; 1000]); + let directory_start = u32_at(&bytes, eocd + 16).unwrap() as usize; + let directory_size = u64::from(u32_at(&bytes, eocd + 12).unwrap()); + let count = u64::from(u16_at(&bytes, eocd + 10).unwrap()); + let mut jumps = std::collections::HashMap::new(); + + assert!(directory_is_exact(&bytes, directory_start, directory_size, count, &mut jumps)); + let indexed_records = jumps.len(); + // Each size models a fake shifted EOCD in the archive comment that starts at the same + // central-directory record but claims additional bytes through the real EOCD. + for extra in 1..=1000 { + assert!(!directory_is_exact(&bytes, directory_start, directory_size + extra, count, &mut jumps)); + } + assert_eq!(jumps.len(), indexed_records, "repeated candidates must reuse the indexed entry jumps"); +} + #[test] fn deeply_nested_folders_are_refused() { let ok = format!("{}a.xml", "f/".repeat(MAX_DEPTH)); @@ -319,6 +360,62 @@ fn zip64_archives_open_and_their_damage_is_named() { assert_eq!(Archive::open(&t).err(), Some(ZipError::DamagedEntry("a.xml".into(), "has no ZIP64 sizes"))); } +#[test] +fn zip64_count_sentinel_keeps_a_comment_eocd_from_masking_the_archive() { + let mut bytes = write(&[Raw::new("a.xml", b"x", false)], true); + let end = bytes.len() - 22; + let locator = end - 20; + let zip64_end = locator - 56; + let directory_size = u64_at(&bytes, zip64_end + 40).unwrap() as u32; + let directory_offset = u64_at(&bytes, zip64_end + 48).unwrap() as u32; + // Count requires ZIP64, while directory size and offset still fit in the classic fields. + bytes[end + 12..end + 16].copy_from_slice(&directory_size.to_le_bytes()); + bytes[end + 16..end + 20].copy_from_slice(&directory_offset.to_le_bytes()); + bytes[end + 20..end + 22].copy_from_slice(&22u16.to_le_bytes()); + // This valid empty EOCD-shaped signature is inside the real end record's comment. + bytes.extend_from_slice(&END.to_le_bytes()); + bytes.extend_from_slice(&[0; 18]); + + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); +} + +#[test] +fn empty_relative_zip64_directory_opens_after_sfx_stub() { + let mut bytes = b"MZ self-extracting stub".to_vec(); + bytes.extend_from_slice(&write_at(&[], true, 0)); + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.names().count(), 0); +} + +#[test] +fn self_extracting_archives_support_relative_and_adjusted_offsets() { + let entries = [Raw::new("DOMDocument.xml", b"", true), Raw::new("LIBRARY/a.xml", b"", false)]; + let stub = b"MZ\x90\0 self-extracting program with no ZIP signatures ".repeat(31); + for zip64 in [false, true] { + for adjusted in [false, true] { + let base = if adjusted { stub.len() as u64 } else { 0 }; + let mut bytes = stub.clone(); + bytes.extend_from_slice(&write_at(&entries, zip64, base)); + let archive = Archive::open(&bytes).unwrap_or_else(|error| panic!("ZIP64 {zip64}, adjusted {adjusted}: {error}")); + assert_eq!(archive.read("DOMDocument.xml").unwrap().unwrap(), b""); + assert_eq!(archive.read("LIBRARY/a.xml").unwrap().unwrap(), b""); + if !zip64 && !adjusted { + let eocd = bytes.len() - 22; + let stated = u32::from_le_bytes(bytes[eocd + 16..eocd + 20].try_into().unwrap()) as usize; + assert_eq!(&bytes[stated + stub.len()..stated + stub.len() + 4], b"PK\x01\x02"); + } + } + } + + // A gap between the directory and end record cannot be guessed as a prefix shift. + let mut bytes = stub; + bytes.extend_from_slice(&write_at(&entries, false, 0)); + let eocd = bytes.len() - 22; + bytes.splice(eocd..eocd, *b"junk"); + assert!(Archive::open(&bytes).is_err()); +} + #[test] fn errors_read_as_sentences() { let all = [ diff --git a/crates/xfl/tests/support/fla.rs b/crates/xfl/tests/support/fla.rs index a3aee29521..fcf5e2d7f0 100644 --- a/crates/xfl/tests/support/fla.rs +++ b/crates/xfl/tests/support/fla.rs @@ -144,6 +144,12 @@ fn le64(out: &mut Vec, v: u64) { /// Writes `entries` as a zip archive, with a ZIP64 end record if `zip64_end`. pub fn write(entries: &[Raw], zip64_end: bool) -> Vec { + write_at(entries, zip64_end, 0) +} + +/// Writes an archive whose offsets count from `base` bytes before the ZIP data. +/// This models a self-extracting archive that has been adjusted to count from file start. +pub fn write_at(entries: &[Raw], zip64_end: bool, base: u64) -> Vec { let mut out = Vec::new(); let mut central = Vec::new(); let mut offsets = Vec::new(); @@ -161,7 +167,7 @@ pub fn write(entries: &[Raw], zip64_end: bool) -> Vec { let comp = data.len() as u64; let flags = e.flags | if e.descriptor { 8 } else { 0 } | if e.utf8 { 0x800 } else { 0 }; let version: u16 = if e.zip64 { 45 } else { 20 }; - let offset = out.len() as u64; + let offset = base + out.len() as u64; offsets.push(offset); // The local header. le32(&mut out, 0x0403_4b50); @@ -235,11 +241,11 @@ pub fn write(entries: &[Raw], zip64_end: bool) -> Vec { central.extend_from_slice(&e.name); central.extend_from_slice(&extra); } - let dir_at = out.len() as u64; + let dir_at = base + out.len() as u64; out.extend_from_slice(¢ral); let n = entries.len() as u64; if zip64_end { - let record = out.len() as u64; + let record = base + out.len() as u64; le32(&mut out, 0x0606_4b50); le64(&mut out, 44); le16(&mut out, 45); diff --git a/crates/xml/Cargo.toml b/crates/xml/Cargo.toml index f957fa6253..02d68985b2 100644 --- a/crates/xml/Cargo.toml +++ b/crates/xml/Cargo.toml @@ -13,3 +13,4 @@ workspace = true [dependencies] quick-xml = { version = "0.41", default-features = false } thiserror = { workspace = true } +serde = { workspace = true, features = ["derive"] } diff --git a/crates/xml/src/dtd.rs b/crates/xml/src/dtd.rs new file mode 100644 index 0000000000..9fa1dd4975 --- /dev/null +++ b/crates/xml/src/dtd.rs @@ -0,0 +1,1063 @@ +//! DTD content-model parsing and XML validation. + +//! Document Type Definitions: element declarations (content models) and required attributes, and +//! validation of an XML document against them (Structure ▸ Validate). + +use std::collections::{HashMap, HashSet}; + +/// How much text parameter entities may add during expansion (a pass count is not an output +/// bound: each pass replaces whole strings, so references can inflate multiplicatively). +const MAX_EXPANDED_BYTES: usize = 1024 * 1024; +const MAX_DTD_BYTES: usize = 1024 * 1024; +const MAX_VALIDATION_XML_BYTES: usize = 16 * 1024 * 1024; +const MAX_VALIDATION_NODES: usize = 100_000; +const MAX_VALIDATION_DEPTH: usize = 256; +const MAX_VALIDATION_ATTRIBUTES: usize = 1_000_000; +const MAX_MATCH_WORK: usize = 20_000_000; +const MAX_MATCH_POSITIONS: usize = 5_000_000; +const MAX_MATCH_STATES: usize = 100_000; + +/// A content particle: a name, a sequence, a choice, or one of those repeated (`?`, `*`, `+`). +#[derive(Clone, Debug, PartialEq)] +enum Cp { + Name(String), + Seq(Vec), + Choice(Vec), + Rep(Box, char), +} + +#[derive(Clone, Debug, PartialEq)] +enum Model { + Empty, + Any, + /// `(#PCDATA | a | b)*`: text and these elements in any order. + Mixed(Vec), + Children(Cp), +} + +/// A parsed DTD. +#[derive(Clone, Debug, Default)] +pub struct Dtd { + elements: Vec<(String, Model)>, + /// Element → its `#REQUIRED` attributes. + required: HashMap>, +} + +/// A problem found by validation: where (an element path such as `Root/story[2]`) and what. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct Problem { + pub path: String, + pub message: String, +} + +impl Dtd { + /// Declared element names, in order. + pub fn element_names(&self) -> impl Iterator { + self.elements.iter().map(|(n, _)| n.as_str()) + } + + fn model(&self, name: &str) -> Option<&Model> { + self.elements.iter().find(|(n, _)| n == name).map(|(_, m)| m) + } +} + +/// Markup declarations (``) with comments removed and quoted strings kept whole. +fn declarations(src: &str) -> Result, String> { + let mut out = Vec::new(); + let mut rest = src; + while let Some(i) = rest.find("") else { + return Err("unterminated DTD comment".into()); + }; + rest = &rest[j + 3..]; + continue; + } + let mut quote = None; + let mut end = None; + for (k, c) in rest.char_indices().skip(2) { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (None, '"' | '\'') => quote = Some(c), + (None, '>') => { + end = Some(k); + break; + } + _ => {} + } + } + let Some(end) = end else { + return Err("unterminated DTD declaration".into()); + }; + out.push(rest[2..end].to_string()); + rest = &rest[end + 1..]; + } + Ok(out) +} + +fn tokens(s: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + for c in s.chars() { + if c.is_whitespace() || "(),|?*+".contains(c) { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + if !c.is_whitespace() { + out.push(c.to_string()); + } + } else { + cur.push(c); + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +/// How deeply groups may nest in a content model; parsing, matching (`ends`) and printing (`show`) +/// recurse once per level. +const MAX_CONTENT_MODEL_DEPTH: usize = 64; + +/// Parse a content particle from `t[*i..]`, inside `depth` enclosing groups. +fn particle(t: &[String], i: &mut usize, depth: usize) -> Result { + let base = match t.get(*i).map(String::as_str) { + Some("(") => { + if depth >= MAX_CONTENT_MODEL_DEPTH { + return Err(format!("content model nested more than {MAX_CONTENT_MODEL_DEPTH} levels")); + } + *i += 1; + let mut items = vec![particle(t, i, depth + 1)?]; + let mut sep = None; + loop { + match t.get(*i).map(String::as_str) { + Some(")") => { + *i += 1; + break; + } + Some(s @ ("," | "|")) => { + if sep.is_some_and(|p| p != s) { + return Err("mixed `,` and `|` in one group".into()); + } + sep = Some(if s == "," { "," } else { "|" }); + *i += 1; + items.push(particle(t, i, depth + 1)?); + } + other => return Err(format!("unexpected `{}` in a content model", other.unwrap_or("end"))), + } + } + if sep == Some("|") { Cp::Choice(items) } else { Cp::Seq(items) } + } + Some(n) if !"),|?*+".contains(n) => { + *i += 1; + Cp::Name(n.to_string()) + } + other => return Err(format!("unexpected `{}` in a content model", other.unwrap_or("end"))), + }; + Ok(match t.get(*i).map(String::as_str) { + Some(r @ ("?" | "*" | "+")) => { + *i += 1; + Cp::Rep(Box::new(base), r.chars().next().unwrap_or('*')) + } + _ => base, + }) +} + +fn parse_model(s: &str) -> Result { + let s = s.trim(); + match s { + "EMPTY" => return Ok(Model::Empty), + "ANY" => return Ok(Model::Any), + _ => {} + } + if s.contains("#PCDATA") { + let t = tokens(s); + if t.first().map(String::as_str) != Some("(") || t.get(1).map(String::as_str) != Some("#PCDATA") { + return Err("malformed mixed content model".into()); + } + let mut i = 2; + let mut allowed = Vec::new(); + if t.get(i).map(String::as_str) == Some(")") { + i += 1; + if t.get(i).map(String::as_str) == Some("*") { + i += 1; + } + if i != t.len() { + return Err("unexpected token after mixed content model".into()); + } + return Ok(Model::Mixed(allowed)); + } + loop { + if t.get(i).map(String::as_str) != Some("|") { + return Err("expected `|` in mixed content model".into()); + } + i += 1; + let Some(name) = t.get(i).filter(|name| !"(),|?*+".contains(name.as_str())) else { + return Err("expected element name in mixed content model".into()); + }; + if allowed.contains(name) { + return Err(format!("duplicate `{name}` in mixed content model")); + } + allowed.push(name.clone()); + i += 1; + match t.get(i).map(String::as_str) { + Some("|") => continue, + Some(")") => { + i += 1; + break; + } + _ => return Err("expected `|` or `)` in mixed content model".into()), + } + } + if t.get(i).map(String::as_str) != Some("*") || i + 1 != t.len() { + return Err("mixed content with element names must end in `*`".into()); + } + return Ok(Model::Mixed(allowed)); + } + let t = tokens(s); + let mut i = 0; + let cp = particle(&t, &mut i, 0)?; + if i != t.len() { + return Err(format!("unexpected `{}` after the content model", t[i])); + } + Ok(Model::Children(cp)) +} + +/// How deeply parameter entities may nest: a reference in the DTD is level 1, a reference in its +/// value level 2, and so on. +const MAX_PARAMETER_ENTITY_DEPTH: usize = 64; + +/// Expand `%name;` references, one level per round, until a round changes nothing. +fn expand_parameter_entities(src: &str, ents: &[(String, String)]) -> Result { + let mut entities = HashMap::new(); + for (name, value) in ents { + entities.entry(name.as_str()).or_insert(value.as_str()); + } + let limit = src.len().saturating_add(MAX_EXPANDED_BYTES); + let append = |out: &mut String, value: &str| -> Result<(), String> { + if value.len() > limit.saturating_sub(out.len()) { + return Err(format!("parameter entities expand the DTD beyond {limit} bytes")); + } + out.push_str(value); + Ok(()) + }; + let too_deep = || format!("parameter entities refer to themselves or nest deeper than {MAX_PARAMETER_ENTITY_DEPTH} levels"); + let mut text = src.to_string(); + // The round after the deepest level changes nothing, hence one more round than levels. + for _ in 0..=MAX_PARAMETER_ENTITY_DEPTH { + let mut out = String::with_capacity(text.len()); + let mut rest = text.as_str(); + let mut changed = false; + loop { + let mut special = None; + for (i, c) in rest.char_indices() { + if c == '%' { + special = Some((i, false)); + break; + } + if c == '<' && rest[i..].starts_with("") else { + return Err("unterminated DTD comment".into()); + }; + append(&mut out, &comment_tail[..end + 3])?; + rest = &comment_tail[end + 3..]; + continue; + } + let (prefix, reference) = rest.split_at(i); + append(&mut out, prefix)?; + // `find` points to an ASCII `%`, so both split positions are UTF-8 boundaries. + rest = reference.split_at(1).1; + // A name has no whitespace and no `%` (`parse` ends a name at whitespace), whatever its + // length: the search for the closing `;` stops at the first of those, so the searches of + // a round never overlap and a round stays linear in the text. + let end = + rest.bytes().position(|b| matches!(b, b';' | b'%') || b.is_ascii_whitespace()).filter(|&k| rest.as_bytes().get(k) == Some(&b';')); + if let Some(end) = end + && let Some(value) = rest.get(..end).and_then(|name| entities.get(name)) + { + // A value that is its own reference (``) never gets anywhere. + if reference.get(..end + 2) == Some(*value) { + return Err(too_deep()); + } + append(&mut out, value)?; + changed = true; + rest = rest.split_at(end + 1).1; + continue; + } + append(&mut out, "%")?; + } + append(&mut out, rest)?; + text = out; + if !changed { + return Ok(text); + } + } + Err(too_deep()) +} + +/// Parse a DTD (its element and attribute-list declarations; parameter entities are expanded). +pub fn parse(src: &str) -> Result { + if src.len() > MAX_DTD_BYTES { + return Err(format!("DTD exceeds the {MAX_DTD_BYTES} byte parsing limit")); + } + // Parameter entities first, then expand references and read the declarations again. + let mut ents: Vec<(String, String)> = Vec::new(); + for d in declarations(src)? { + if let Some(rest) = d.strip_prefix("ENTITY") { + let rest = rest.trim_start(); + if let Some(rest) = rest.strip_prefix('%') { + let rest = rest.trim_start(); + let name: String = rest.chars().take_while(|c| !c.is_whitespace()).collect(); + let val = rest[name.len()..].trim(); + let q = val.chars().next().unwrap_or('"'); + if let Some(v) = val.strip_prefix(q).and_then(|v| v.find(q).map(|e| &v[..e])) { + ents.push((name, v.to_string())); + } + } + } + } + let text = expand_parameter_entities(src, &ents)?; + let mut dtd = Dtd::default(); + for d in declarations(&text)? { + if let Some(rest) = d.strip_prefix("ELEMENT") { + let rest = rest.trim_start(); + let name: String = rest.chars().take_while(|c| !c.is_whitespace()).collect(); + let model = parse_model(&rest[name.len()..]).map_err(|e| format!(": {e}"))?; + dtd.elements.push((name, model)); + } else if let Some(rest) = d.strip_prefix("ATTLIST") { + // name (attr type default)*; only `#REQUIRED` matters here. + let mut words = Vec::new(); + let mut cur = String::new(); + let mut quote = None; + let mut group = 0; + for c in rest.chars() { + match (quote, c) { + (Some(q), c) if c == q => { + quote = None; + cur.push(c); + } + (Some(_), c) => cur.push(c), + (None, '"' | '\'') => { + quote = Some(c); + cur.push(c); + } + (None, '(') => { + group += 1; + cur.push(c); + } + (None, ')') => { + group -= 1; + cur.push(c); + } + (None, c) if c.is_whitespace() && group == 0 => { + if !cur.is_empty() { + words.push(std::mem::take(&mut cur)); + } + } + (None, c) => cur.push(c), + } + } + if !cur.is_empty() { + words.push(cur); + } + let Some((el, attrs)) = words.split_first() else { continue }; + let mut k = 0; + while k < attrs.len() { + let name = &attrs[k]; + let Some(ty) = attrs.get(k + 1) else { + return Err(format!("incomplete ATTLIST for `{el}`")); + }; + k += 2; + // NOTATION is a two-token type: the keyword followed by its enumeration. + if ty == "NOTATION" { + if attrs.get(k).is_none_or(|group| !group.starts_with('(') || !group.ends_with(')')) { + return Err(format!("malformed NOTATION type for `{name}`")); + } + k += 1; + } + let Some(default) = attrs.get(k).map(String::as_str) else { + return Err(format!("missing default declaration for `{name}`")); + }; + k += 1; + if default == "#REQUIRED" { + dtd.required.entry(el.clone()).or_default().push(name.clone()); + } else if default == "#FIXED" { + if k >= attrs.len() { + return Err(format!("missing #FIXED value for `{name}`")); + } + k += 1; + } + } + } + } + if dtd.elements.is_empty() { + return Err("no element declarations".into()); + } + Ok(dtd) +} + +/// What `ends` has worked out for one sequence of children: the end positions of a group (by the +/// address of its node, which lives as long as the model) from a position. +type EndsMemo = HashMap<(usize, usize), Vec>; + +#[derive(Default)] +struct MatchBudget { + work: usize, + positions: usize, + states: usize, + exhausted: bool, + reported: bool, +} + +impl MatchBudget { + fn spend(&mut self, work: usize, positions: usize) -> Result<(), &'static str> { + if self.exhausted { + return Err("content model matching exceeded its resource budget"); + } + self.work = self.work.saturating_add(work); + self.positions = self.positions.saturating_add(positions); + if self.work > MAX_MATCH_WORK { + self.exhausted = true; + return Err("content model matching exceeded its work limit"); + } + if self.positions > MAX_MATCH_POSITIONS { + self.exhausted = true; + return Err("content model matching exceeded its memory limit"); + } + Ok(()) + } + + fn retain_state(&mut self) -> Result<(), &'static str> { + self.states = self.states.saturating_add(1); + if self.states > MAX_MATCH_STATES { + self.exhausted = true; + return Err("content model matching exceeded its state limit"); + } + Ok(()) + } +} + +/// End positions after `cp` matches a prefix of `seq[i..]`. +/// +/// The positions of each group are worked out once per start position (`memo`): nested repetitions +/// such as `((a*)*)*` ask the inner group for the same positions again and again, which is +/// exponential in their depth without it. +fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo, budget: &mut MatchBudget) -> Result, &'static str> { + budget.spend(1, 0)?; + if let Cp::Name(n) = cp { + if seq.get(i) == Some(&n.as_str()) { + budget.spend(0, 1)?; + return Ok(vec![i + 1]); + } + return Ok(vec![]); + } + let key = (std::ptr::from_ref(cp) as usize, i); + if let Some(done) = memo.get(&key) { + budget.spend(0, done.len())?; + return Ok(done.clone()); + } + let mut out: Vec = match cp { + Cp::Name(_) => vec![], + // Keep the positions after each item a set: as a list of every path, `(a?, a?, …)` doubles per item. + Cp::Seq(items) => { + let mut at = vec![i]; + for c in items { + let mut next = Vec::new(); + for p in at { + let found = ends(c, seq, p, memo, budget)?; + budget.spend(found.len(), found.len())?; + next.extend(found); + } + next.sort_unstable(); + next.dedup(); + at = next; + } + at + } + Cp::Choice(items) => { + let mut all = Vec::new(); + for c in items { + let found = ends(c, seq, i, memo, budget)?; + budget.spend(found.len(), found.len())?; + all.extend(found); + } + all + } + Cp::Rep(c, r) => { + let mut all = if *r == '+' { vec![] } else { vec![i] }; + let mut seen: HashSet = all.iter().copied().collect(); + let mut frontier = ends(c, seq, i, memo, budget)?; + budget.spend(frontier.len(), frontier.len())?; + if *r == '?' { + all.extend(frontier); + } else { + while !frontier.is_empty() { + let mut new = Vec::new(); + for p in frontier.iter().copied() { + budget.spend(1, 0)?; + if seen.insert(p) { + budget.spend(0, 1)?; + new.push(p); + } + } + budget.spend(new.len(), new.len())?; + all.extend(&new); + let mut next = Vec::new(); + let mut next_seen = HashSet::new(); + for p in new.into_iter().filter(|&p| p > i) { + for found in ends(c, seq, p, memo, budget)? { + budget.spend(1, 0)?; + if !seen.contains(&found) && next_seen.insert(found) { + budget.spend(0, 1)?; + next.push(found); + } + } + } + // Two paths to one position are one position: kept apart they multiply per round. + next.sort_unstable(); + next.dedup(); + frontier = next; + } + } + all + } + }; + out.sort_unstable(); + out.dedup(); + budget.spend(out.len(), out.len())?; + budget.retain_state()?; + memo.insert(key, out.clone()); + Ok(out) +} + +fn show(cp: &Cp) -> String { + match cp { + Cp::Name(n) => n.clone(), + Cp::Seq(v) => format!("({})", v.iter().map(show).collect::>().join(", ")), + Cp::Choice(v) => format!("({})", v.iter().map(show).collect::>().join(" | ")), + Cp::Rep(c, r) => format!("{}{r}", show(c)), + } +} + +/// An element of the document being validated. +struct Node { + name: String, + attrs: Vec, + children: Vec, + text: bool, + content: bool, +} + +fn bounded_node(e: &quick_xml::events::BytesStart<'_>, depth: usize, nodes: &mut usize, attributes: &mut usize) -> Result { + if depth >= MAX_VALIDATION_DEPTH { + return Err(format!("XML nesting exceeds the {MAX_VALIDATION_DEPTH} level validation limit")); + } + *nodes = nodes.saturating_add(1); + if *nodes > MAX_VALIDATION_NODES { + return Err(format!("XML exceeds the {MAX_VALIDATION_NODES} node validation limit")); + } + let mut attrs = Vec::new(); + for attr in e.attributes().with_checks(true) { + let attr = attr.map_err(|err| format!("invalid attribute: {err}"))?; + attrs.push(String::from_utf8_lossy(attr.key.as_ref()).to_string()); + } + *attributes = attributes.saturating_add(attrs.len()); + if *attributes > MAX_VALIDATION_ATTRIBUTES { + return Err(format!("XML exceeds the {MAX_VALIDATION_ATTRIBUTES} attribute validation limit")); + } + Ok(Node { name: String::from_utf8_lossy(e.name().as_ref()).to_string(), attrs, children: vec![], text: false, content: false }) +} + +fn read_tree(xml: &str) -> Result { + use quick_xml::events::Event; + if xml.len() > MAX_VALIDATION_XML_BYTES { + return Err(format!("XML exceeds the {} byte validation limit", MAX_VALIDATION_XML_BYTES)); + } + let mut r = quick_xml::Reader::from_str(xml); + let mut stack: Vec = Vec::new(); + let mut root = None; + let mut nodes = 0usize; + let mut attributes = 0usize; + loop { + match r.read_event().map_err(|e| e.to_string())? { + Event::Start(e) => { + if stack.is_empty() && root.is_some() { + return Err("multiple root elements".into()); + } + let n = bounded_node(&e, stack.len(), &mut nodes, &mut attributes)?; + if let Some(parent) = stack.last_mut() { + parent.content = true; + } + stack.push(n); + } + Event::Empty(e) => { + if stack.is_empty() && root.is_some() { + return Err("multiple root elements".into()); + } + let n = bounded_node(&e, stack.len(), &mut nodes, &mut attributes)?; + match stack.last_mut() { + Some(p) => { + p.content = true; + p.children.push(n); + } + None => root = Some(n), + } + } + Event::End(e) => { + let n = stack.pop().ok_or("unbalanced end tag")?; + if n.name.as_bytes() != e.name().as_ref() { + return Err("mismatched end tag".into()); + } + match stack.last_mut() { + Some(p) => p.children.push(n), + None => root = Some(n), + } + } + Event::Text(t) => { + if let Some(p) = stack.last_mut() { + p.content = true; + if !t.iter().all(u8::is_ascii_whitespace) { + p.text = true; + } + } else if !t.iter().all(u8::is_ascii_whitespace) { + return Err("text outside the root element".into()); + } + } + Event::CData(_) => { + if let Some(p) = stack.last_mut() { + p.text = true; + p.content = true; + } + } + Event::GeneralRef(reference) => { + let name = reference.decode().map_err(|e| e.to_string())?; + let accepted = if let Some(character) = reference.resolve_char_ref().map_err(|e| e.to_string())? { + crate::is_xml_char(character) + } else { + matches!(name.as_ref(), "amp" | "lt" | "gt" | "apos" | "quot") + }; + if !accepted { + return Err(format!("unsupported general entity reference `&{name};`")); + } + if let Some(p) = stack.last_mut() { + p.text = true; + p.content = true; + } else { + return Err("reference outside the root element".into()); + } + } + Event::Comment(_) | Event::PI(_) => { + if let Some(parent) = stack.last_mut() { + parent.content = true; + } + } + Event::Eof => { + if !stack.is_empty() { + return Err("unclosed element".into()); + } + return root.ok_or_else(|| "no root element".into()); + } + _ => {} + } + } +} + +fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec, budget: &mut MatchBudget) { + let mut problem = |m: String| out.push(Problem { path: path.to_string(), message: m }); + match dtd.model(&n.name) { + None => problem(format!("`{}` isn't declared in the DTD", n.name)), + Some(Model::Any) => {} + Some(Model::Empty) => { + if n.content { + problem(format!("`{}` should be empty", n.name)); + } + } + Some(Model::Mixed(allowed)) => { + for c in &n.children { + if !allowed.contains(&c.name) { + problem(format!("`{}` isn't allowed in `{}`", c.name, n.name)); + } + } + } + Some(Model::Children(cp)) => { + if n.text { + problem(format!("`{}` can't contain text", n.name)); + } + let seq: Vec<&str> = n.children.iter().map(|c| c.name.as_str()).collect(); + let matched = ends(cp, &seq, 0, &mut EndsMemo::new(), budget); + match matched { + Ok(positions) if positions.contains(&seq.len()) => {} + Ok(_) => { + let got = if seq.is_empty() { "nothing".to_string() } else { seq.join(", ") }; + problem(format!("`{}` contains {got}; the DTD asks for {}", n.name, show(cp))); + } + Err(error) => { + if !budget.reported { + problem(format!("`{}`: {error}", n.name)); + budget.reported = true; + } + } + } + } + } + for a in dtd.required.get(&n.name).into_iter().flatten() { + if !n.attrs.contains(a) { + problem(format!("`{}` is missing the required attribute `{a}`", n.name)); + } + } + let mut seen: HashMap<&str, usize> = HashMap::new(); + for c in &n.children { + let k = seen.entry(c.name.as_str()).or_default(); + *k += 1; + check(dtd, c, &format!("{path}/{}[{k}]", c.name), out, budget); + } +} + +/// Validate `xml` against `dtd`; an empty list when it's valid. +/// +/// Validation rejects input above the internal byte, depth, node, attribute and content-model +/// matching budgets. Only predefined entities and numeric character references are resolved; a +/// general entity reference is reported as unsupported rather than expanded or fetched. +pub fn validate(dtd: &Dtd, xml: &str) -> Vec { + match read_tree(xml) { + Ok(root) => { + let mut out = Vec::new(); + let path = root.name.clone(); + check(dtd, &root, &path, &mut out, &mut MatchBudget::default()); + out + } + Err(e) => vec![Problem { path: String::new(), message: format!("not well-formed XML: {e}") }], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const DTD: &str = r##" + + + + + + + + + + b" kind (photo|chart) "photo">"##; + + #[test] + fn content_models_and_required_attributes() { + let dtd = parse(DTD).unwrap(); + assert_eq!(dtd.element_names().count(), 8); + let ok = r#"T <em>x</em>ab
"#; + assert_eq!(validate(&dtd, ok), vec![]); + let bad = r#"no title
x