mirror of
https://github.com/storytold/deckcraft.git
synced 2026-11-25 21:20:10 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51b6808789 | ||
|
|
659c586765 | ||
|
|
37a82eac0a | ||
|
|
f224526b55 | ||
|
|
a70784e637 | ||
|
|
8ab5c7b94e | ||
|
|
6a5c8bd90f | ||
|
|
832efa93bb | ||
|
|
15dc0b2f94 | ||
|
|
e4a966d035 | ||
|
|
1efc4b58d3 | ||
|
|
9db2fa0ca9 | ||
|
|
2d031bb6b6 | ||
|
|
14ff0938ff | ||
|
|
26620f59be | ||
|
|
7fbdc085eb | ||
|
|
06c7701514 | ||
|
|
0ccc68f61c | ||
|
|
c355c06397 | ||
|
|
6ebac8b9b3 | ||
|
|
b16257a8b2 | ||
|
|
83d9383c79 | ||
|
|
94e7d0cf93 | ||
|
|
05d9907496 | ||
|
|
921b455836 |
@@ -0,0 +1,12 @@
|
||||
# Custom runner labels actionlint can't know about.
|
||||
self-hosted-runner:
|
||||
labels:
|
||||
- macos-release # org larger runner (M2 Pro), used by release.yml
|
||||
|
||||
# actionlint 1.7.12 predates GitHub's queue key, which the signer caller may use when it needs
|
||||
# serialization. Only this exact false positive is suppressed; Packaging lint's independent
|
||||
# source-contract job enforces the values.
|
||||
paths:
|
||||
.github/workflows/nightly-sign.yml:
|
||||
ignore:
|
||||
- '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$'
|
||||
@@ -0,0 +1,16 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/deckcraft",
|
||||
"repository_id": 1408294296,
|
||||
"producer_workflow_id": null,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"release_branch": "release",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
"echelon",
|
||||
"FredApps",
|
||||
"skylartaylor"
|
||||
],
|
||||
"max_age_seconds": 86400,
|
||||
"candidate_policy": {
|
||||
"schema": "craft-nightly-candidate-policy/v3",
|
||||
"epoch": "deckcraft-nightly-20261124-initial",
|
||||
"repository": "storytold/deckcraft",
|
||||
"branch": "main",
|
||||
"required_workflows": [
|
||||
{
|
||||
"workflow_id": 377160704,
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "font-pin",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / gate (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sonar": {
|
||||
"organization": "storytold",
|
||||
"project": "storytold_deckcraft",
|
||||
"app_id": 12526,
|
||||
"check_name": "SonarCloud Code Analysis",
|
||||
"details_url": "https://sonarcloud.io/dashboard?id=storytold_deckcraft&branch=main",
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_maintainability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_coverage",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "80"
|
||||
},
|
||||
{
|
||||
"metric": "new_duplicated_lines_density",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "3"
|
||||
},
|
||||
{
|
||||
"metric": "new_security_hotspots_reviewed",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "100"
|
||||
}
|
||||
],
|
||||
"debt": []
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {
|
||||
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
|
||||
}
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,11 @@ workflows:
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/nightly-macos.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
'.github/workflows/nix.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/[email protected]'
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# Builds the unsigned Apple-silicon DeckCraft Nightly (packaging/macos/nightly.sh) on a hosted
|
||||
# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version
|
||||
# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the
|
||||
# real Nightly is signed and notarized by the shared release-ref signer (craft-common-actions),
|
||||
# which calls packaging/macos/nightly-sign.sh.
|
||||
name: Nightly macOS build
|
||||
|
||||
on:
|
||||
# macOS runners are shared with release builds: pull requests run this only with the `full-ci`
|
||||
# label, never by changed paths. `labeled` so adding the label starts a run.
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
|
||||
# label, or another label added) gets a group of its own, so it never cancels a real build.
|
||||
concurrency:
|
||||
group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Nightly .app (aarch64, unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/[email protected]
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
persist-credentials: false
|
||||
# The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build.
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/[email protected]
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
path: craft-fonts
|
||||
- name: Check out craft-i18n
|
||||
uses: actions/[email protected]
|
||||
with:
|
||||
repository: storytold/craft-i18n
|
||||
path: craft-i18n
|
||||
# The hosted image ships rustup: install the current stable plus the macOS target, with no new
|
||||
# action pin for one job. Cargo enforces [workspace.package] rust-version.
|
||||
- name: Install the Rust toolchain
|
||||
run: rustup toolchain install stable --profile minimal --target aarch64-apple-darwin
|
||||
|
||||
# A version of the prepared Nightly form for this commit; the real one comes from the feed's
|
||||
# identity job. Only nightly.sh's input checks read it.
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
date="$(date -u +%Y-%m-%d)"
|
||||
{
|
||||
echo "DECKCRAFT_BUILD_SHA=$sha"
|
||||
echo "DECKCRAFT_BUILD_DATE=$date"
|
||||
echo "DECKCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the unsigned Nightly bundle
|
||||
env:
|
||||
DECKCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
run: bash packaging/macos/nightly.sh --arch aarch64
|
||||
- name: Check the archive and the bundle's version
|
||||
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/deckcraft-$DECKCRAFT_VERSION-macos-aarch64-nightly.zip"
|
||||
@@ -0,0 +1,42 @@
|
||||
name: DeckCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on release. Main/release contents must match.
|
||||
# A reusable callee does not change context; this must be a real top-level release dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
producer_run_id:
|
||||
description: Exact untrusted producer Actions run ID
|
||||
required: true
|
||||
type: string
|
||||
producer_run_attempt:
|
||||
description: Exact untrusted producer Actions run attempt
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: deckcraft-nightly-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real release branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/deckcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the existing release environment and export keys in its signing step.
|
||||
@@ -0,0 +1,34 @@
|
||||
name: DeckCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
unsigned:
|
||||
# Actual context guards only; no inherited/platform secrets.
|
||||
if: >-
|
||||
github.repository == 'storytold/deckcraft' &&
|
||||
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
|
||||
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
|
||||
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
|
||||
# no OIDC, attestation write, release environment or platform secrets in compilation.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
app-name: deckcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
|
||||
# Linux/macOS signer (#342).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
@@ -5,9 +5,9 @@ name: Packaging lint
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -49,3 +49,20 @@ jobs:
|
||||
- name: Build and check non-executable installer fixtures
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
|
||||
|
||||
nightly-source-contract:
|
||||
name: Nightly source contracts (no build or signing)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/[email protected]
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Enforce nightly serialization and synthetic packaging contracts
|
||||
run: python3 packaging/nightly-tests.py
|
||||
|
||||
@@ -59,3 +59,4 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
|
||||
@@ -12,3 +12,9 @@ packaging/env.sh
|
||||
/packaging/linux/flatpak/cargo-sources.json
|
||||
/build-flatpak/
|
||||
/.flatpak-builder/
|
||||
|
||||
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
__pycache__/
|
||||
|
||||
@@ -23,6 +23,8 @@ artwork. The ribbon and menu icons stay original drawings.
|
||||
| `packaging/macos/dmg/background.svg` | @XusBadia | DeckCraft macOS DMG window background, original work for this repository (2026-10-08), derived from the DeckCraft app icon `assets/app-icon/deckcraft-1024.png` (referenced via `<image>`, not copied); text is outlined Inter / JetBrains Mono glyph paths | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | Finder window of the macOS DMG; `packaging/macos/dmg/generate.py` renders it to `background.tiff` |
|
||||
| `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
|
||||
| `assets/app-icon/deckcraft.icns`, `assets/app-icon/deckcraft.ico` | DeckCraft contributors | generated from the PNGs above by `packaging/icons.sh` (sips/iconutil, `cargo xtask ico`) | MIT OR Apache-2.0 | macOS and Windows app icons |
|
||||
| `assets/app-icon/deckcraft-nightly*` (`deckcraft-nightly.png`, `deckcraft-nightly-1024.png`, `deckcraft-nightly.ico`, `deckcraft-nightly.icns`) | @skylartaylor | derivative of `assets/app-icon/deckcraft-1024.png` and `assets/app-icon/icon-source.deckcraft`, recoloured in code (background `#f26b1d` → `#a6420c`; foreground, padding and accent bars unchanged; native-size frames area-averaged from the 1024 master); recorded in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | DeckCraft Nightly app icon: window/desktop icon, macOS `CFBundleIconFile`, Windows resources and `.ico` |
|
||||
| `assets/app-icon/nightly-provenance.json` | @skylartaylor | written alongside the nightly icons above; names their inputs, the recolour method and every output SHA-256 | MIT OR Apache-2.0 | Provenance of the DeckCraft Nightly icons |
|
||||
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.deckcraft.svg` | DeckCraft contributors | the shapes of `assets/app-icon/icon-source.deckcraft` written out as SVG (same coordinates, colours and corner radii) | MIT OR Apache-2.0 | Scalable app icon for Linux desktops (hicolor theme) |
|
||||
| `assets/app-icon/icon-source.deckcraft` | DeckCraft contributors | made with `deckcraft-cli run` (see git history) | MIT OR Apache-2.0 | Source of the placeholder icon |
|
||||
| `docs/images/editor.png`, `docs/images/shape-format.png`, `docs/images/format-pane.png`, `docs/images/slide-sorter.png`, `docs/images/dark-mode.png`, `docs/images/sample-deck.png` | DeckCraft contributors | Screenshots of DeckCraft and slides rendered by `deckcraft-cli` from the built-in sample deck (original content; Inter font, OFL-1.1) | MIT OR Apache-2.0 | README screenshots |
|
||||
|
||||
Generated
+32
-47
@@ -943,7 +943,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
@@ -970,20 +970,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)",
|
||||
"craft-xml",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -1036,7 +1025,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f428c3d36e0faf3924b76956a01334c051543527#f428c3d36e0faf3924b76956a01334c051543527"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1057,10 +1046,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
|
||||
"craft-xml",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1)",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1074,6 +1063,21 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pptx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
"craft-xml",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
@@ -1164,32 +1168,13 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
@@ -1203,7 +1188,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1299,8 +1284,10 @@ dependencies = [
|
||||
"log",
|
||||
"rfd",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1326,7 +1313,7 @@ dependencies = [
|
||||
name = "deckcraft-color"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
|
||||
"craft-drawingml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1384,7 +1371,7 @@ dependencies = [
|
||||
name = "deckcraft-geom"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
|
||||
"craft-drawingml",
|
||||
"kurbo",
|
||||
"serde",
|
||||
]
|
||||
@@ -1417,7 +1404,7 @@ dependencies = [
|
||||
name = "deckcraft-model"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
|
||||
"craft-drawingml",
|
||||
"deckcraft-color",
|
||||
"deckcraft-geom",
|
||||
"serde",
|
||||
@@ -1464,17 +1451,15 @@ name = "deckcraft-pptx"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)",
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)",
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)",
|
||||
"craft-pptx",
|
||||
"craft-xml",
|
||||
"deckcraft-color",
|
||||
"deckcraft-engine",
|
||||
"deckcraft-geom",
|
||||
"deckcraft-model",
|
||||
"deckcraft-text",
|
||||
"image",
|
||||
"log",
|
||||
"quick-xml 0.41.0",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+10
-10
@@ -11,16 +11,16 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/deckcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# OPC part-name primitives; relationship admission stays app-local.
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
|
||||
# OPC part-name primitives and package reader/writer.
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
|
||||
# Compound File Binary directory reads (password-protected deck detection).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
|
||||
# XML writer primitives; parser admission and OOXML policy stay app-local.
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
|
||||
# DrawingML colours, themes and text (craft-libs#778, #792): the model DeckCraft reads and writes.
|
||||
# Isolated table XML writer; existing DrawingML model/readers keep their revision.
|
||||
craft-drawingml-table = { package = "craft-drawingml", git = "https://github.com/storytold/craft-libs", rev = "cff5af869dbf6926801c9ac63a927d155202ba3b" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" }
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
|
||||
# Bounded XML reader and writer primitives.
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
|
||||
# DrawingML colours, themes, charts, tables and text (craft-libs#778, #792).
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
|
||||
# PresentationML PPTX/POTX/PPSX reader and writer (craft-libs#778).
|
||||
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
|
||||
# Shared MCP stdio framing and protocol constants (craft-libs#778).
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "bc186ca719958fcce3b6ee24794277eabed14609", version = "0.1.0" }
|
||||
# internal
|
||||
@@ -72,7 +72,7 @@ craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "010702ee
|
||||
# H.264, HEVC, VP9 and AV1 decoders.
|
||||
craft-video = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0", default-features = false, features = ["h264-decode", "hevc-decode", "vp9-decode", "av1-decode", "threads"] }
|
||||
# WMF, EMF and EMF+ reader.
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "f428c3d36e0faf3924b76956a01334c051543527", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "63196e66f3033a6623eb629af95a104d26986725", features = ["egui"] }
|
||||
|
||||
@@ -173,6 +173,29 @@ See [ROADMAP.md](ROADMAP.md) for the stage, numbers by dimension and what's next
|
||||
[docs/gaps.md](docs/gaps.md) for every known shortfall and
|
||||
[docs/parity-checklist.md](docs/parity-checklist.md) for the feature-by-feature checklist.
|
||||
|
||||
## Nightly builds (not released yet)
|
||||
|
||||
DeckCraft has a separate **DeckCraft Nightly** channel for Launcher-managed nightly builds beside
|
||||
the stable app: its own application ID, package identity, data folder, taskbar entry and window
|
||||
class, so it never reads or writes stable DeckCraft's settings, recovery autosaves, logs, user
|
||||
dictionary or single window state. The Nightly app is started only by ArtCraft Launcher
|
||||
(`--launch-profile nightly-v1 --profile-root <dir> -- <files>`); the profile root is validated and
|
||||
fenced against every stable data and install folder, so a Nightly window cannot fall back to
|
||||
stable state. Nightly is managed by the Launcher and does not self-update.
|
||||
|
||||
On Linux, every Nightly format starts through the same launcher
|
||||
(`packaging/linux/nightly-launch.sh`): the `.tar.gz` and AppImage, the deb/rpm package, the Flatpak
|
||||
and the Arch handoff all pass `--launch-profile nightly-v1 --profile-root <dir> -- <files>` to the
|
||||
GUI, so an unpacked or distro-installed copy is isolated without the Launcher.
|
||||
|
||||
The channel's packaging lives in `packaging/nightly-common.sh`, `packaging/{linux,macos,windows}/nightly*`
|
||||
and `.github/workflows/nightly*.yml`. The producer and signer workflows are registered and can be
|
||||
dispatched by the reviewed release managers only; there is no schedule or automatic dispatch yet.
|
||||
Read [`docs/nightly-release-preparation.md`](docs/nightly-release-preparation.md) before the first
|
||||
supervised run. The channel is compiled with `DECKCRAFT_BUILD_CHANNEL=nightly-v1`, which also
|
||||
selects the deeper-background icons recorded in
|
||||
[`assets/app-icon/nightly-provenance.json`](assets/app-icon/nightly-provenance.json).
|
||||
|
||||
## Downloads
|
||||
|
||||
**Download DeckCraft** from GitHub: the [latest release](https://github.com/storytold/deckcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/deckcraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~20 points and ~120–210 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-20 · **Change:** trivial (progress log: WMF scale and offset mapping records place sub-pictures, #2069; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: every slide as PNG or JPEG from File › Export › Change File Type and Save As, #2019; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-15 · **Change:** trivial (DeckCraft v0.19.0 version preparation (#2134); the SmartArt and WordArt display names become Diagram and Decorative Text (#1981) in DeckCraft's own feature labels — commands, contextual tab labels and messages — with the neutral labels guarded by tests (the PowerPoint-matching empty-diagram placeholder prompt still reads "Click icon to add SmartArt graphic", and saved control-channel identifiers such as the tab id "SmartArt Design" keep their keys); the wasm32 build no longer refers to the native-only opening generation (#1954); the control-protocol method reference is corrected (#2132); parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-14 · **Change:** minor (a slide the show advances to again plays its animations again, #2090; slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; empty notes slides are kept through PPTX and native saves, #2025; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-09 · **Change:** minor (progress log: PowerPoint 97–2003 `.ppt`/`.pot`/`.pps` import, #239) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-07 · **Change:** trivial (progress log: text in a group whose child coordinates scale its shapes is placed for export where the slide draws it; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
@@ -158,7 +160,9 @@ app's JSON control channel (`deckcraft --control PORT`).
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-11-20 | WMF pictures that draw sub-pictures through the scale and offset mapping records (charts and clip art from older Office versions) place each one in its part of the frame (#2069) |
|
||||
| 2026-11-16 | Export: every slide as its own PNG or JPEG picture from File › Export › Change File Type and File › Save As; the Export… dialog adds JPEG images (all slides) (#2019) |
|
||||
| 2026-11-15 | DeckCraft v0.19.0 version preparation (#2134); the SmartArt and WordArt display names become Diagram and Decorative Text in DeckCraft's own feature labels — commands, contextual tab labels and messages — with the neutral labels guarded by tests; the wasm32 build no longer refers to the native-only opening generation (#1954); the control-protocol method reference is corrected (#2132) |
|
||||
| 2026-11-14 | Slide show: a slide the show advances to again (click, →, Space, automatic advance or a loop) starts over, so its animations play again, as in PowerPoint. Back and links still show it as it was left (#2090) |
|
||||
| 2026-11-11 | PPTX: a slide whose notes slide has empty text retains its notesSlide part and relationship on save and reopen (#2025); empty notes slides survive native round trips |
|
||||
| 2026-11-11 | Media: the Opus decoder and the Ogg, MP4/MOV and Matroska demuxers are craft-audio and craft-media from craft-libs; DeckCraft's own copies and re-export crates are removed |
|
||||
@@ -351,7 +355,9 @@ app's JSON control channel (`deckcraft --control PORT`).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | trivial | Progress log: WMF scale and offset mapping records (#2069); scores unchanged |
|
||||
| 2026-11-16 | trivial | Progress log: export all slides as PNG or JPEG from the File tab (#2019); scores unchanged |
|
||||
| 2026-11-15 | trivial | v0.19.0 version preparation; Diagram and Decorative Text naming (#1981) scoped to DeckCraft's own labels — the PowerPoint-matching empty-placeholder prompt still reads "Click icon to add SmartArt graphic" and saved control-channel identifiers keep their keys; wasm32 fix (#1954); control-protocol reference fix (#2132); parity scores unchanged |
|
||||
| 2026-11-14 | trivial | Progress log: a slide the show advances to again plays its animations again (#2090); parity scores unchanged |
|
||||
| 2026-11-11 | minor | Progress log: empty notes slides preserved on PPTX/native save (#2025); parity scores unchanged |
|
||||
| 2026-11-11 | trivial | Opus and container code moved to craft-libs crates; parity scores unchanged |
|
||||
|
||||
@@ -41,6 +41,16 @@ fn stdout_line(args: std::fmt::Arguments<'_>) -> std::io::Result<()> {
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// nightly-v1 is a desktop-only launcher protocol. Never let GUI profile arguments fall through
|
||||
// to stable CLI/MCP directory discovery.
|
||||
if args
|
||||
.iter()
|
||||
.take_while(|arg| arg.as_str() != "--")
|
||||
.any(|arg| arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root="))
|
||||
{
|
||||
eprintln!("nightly-v1 is supported only by the DeckCraft desktop launcher protocol");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let rest = args.get(1..).unwrap_or(&[]);
|
||||
let asks_help = rest.iter().any(|a| a == "--help" || a == "-h");
|
||||
if let Some(page) = args.first().filter(|_| asks_help).and_then(|n| help::page(n)) {
|
||||
|
||||
@@ -287,3 +287,22 @@ fn commands_lists_one_line_per_command() {
|
||||
assert_eq!(stdout(&cli(&["commands", "slide.next"])), "slide.next — Next Slide\n");
|
||||
assert_eq!(stdout(&cli(&["commands", "shape.presets"])), "shape.presets — Shape Gallery → [{name, label, category}]\n");
|
||||
}
|
||||
|
||||
/// The desktop-only Nightly launcher protocol never falls through to the CLI's stable directory
|
||||
/// discovery: every spelling leaves with exit 2 and says so.
|
||||
#[test]
|
||||
fn the_desktop_launcher_protocol_is_refused() {
|
||||
for args in [
|
||||
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly-data/profiles/deckcraft", "--", "deck.pptx"][..],
|
||||
&["--launch-profile", "nightly-v1", "info"][..],
|
||||
&["--profile-root=/nightly-data/profiles/deckcraft", "info"][..],
|
||||
] {
|
||||
let o = cli(args);
|
||||
assert_eq!(o.status.code(), Some(2), "{args:?}");
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(err.contains("desktop launcher protocol"), "{args:?}: {err}");
|
||||
}
|
||||
// Everything after the delimiter is a file name, so the flags there are not the protocol.
|
||||
let o = cli(&["--", "--launch-profile"]);
|
||||
assert_eq!(o.status.code(), Some(1), "`--` is an unknown subcommand, not a profile");
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
# Icon + VERSIONINFO for deckcraft.exe; build.rs only uses it when the target is Windows.
|
||||
@@ -33,6 +34,10 @@ arboard = { workspace = true, features = ["image-data"] }
|
||||
image = { workspace = true }
|
||||
cpal = "0.16"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# An explicit AppUserModelID for DeckCraft Nightly, so its taskbar group and toasts are not stable's.
|
||||
winsafe = { version = "0.0.29", features = ["user", "shell"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Finder double-click, Open With, Dock drops and `open -a DeckCraft deck.pptx` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This audited crate (also used by
|
||||
|
||||
+43
-3
@@ -4,22 +4,62 @@
|
||||
//! On every other target this does nothing. A missing resource compiler is a warning, so a
|
||||
//! cross-compile from macOS or Linux still links, unless `DECKCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! into an error (for release builds).
|
||||
//!
|
||||
//! `DECKCRAFT_BUILD_CHANNEL=nightly-v1` selects the Nightly flavor: `cfg(deckcraft_nightly_v1)`,
|
||||
//! the deeper nightly icon, `ProductName "DeckCraft Nightly"` and the exact prepared
|
||||
//! `DECKCRAFT_VERSION` as ProductVersion (the Launcher checks ProductVersion, not FileVersion).
|
||||
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-env-changed=DECKCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo:rustc-check-cfg=cfg(deckcraft_nightly_v1)");
|
||||
let nightly = match std::env::var("DECKCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=deckcraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
// An empty value (an unset CI input) means the default stable build.
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
eprintln!("unsupported DECKCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/deckcraft.ico");
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/deckcraft-nightly.ico");
|
||||
println!("cargo:rerun-if-env-changed=DECKCRAFT_REQUIRE_WINRES");
|
||||
println!("cargo:rerun-if-env-changed=DECKCRAFT_VERSION");
|
||||
let built_version = if nightly {
|
||||
match std::env::var("DECKCRAFT_VERSION") {
|
||||
Ok(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit DECKCRAFT_VERSION feed identity");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=DECKCRAFT_BUILT_VERSION={built_version}");
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("../../assets/app-icon/deckcraft.ico")
|
||||
.set("ProductName", "DeckCraft")
|
||||
.set("FileDescription", "DeckCraft presentations")
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "DeckCraft Nightly" } else { "DeckCraft" })
|
||||
.set("FileDescription", if nightly { "DeckCraft Nightly presentations" } else { "DeckCraft presentations" })
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the DeckCraft authors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "deckcraft.exe")
|
||||
.set("InternalName", "deckcraft");
|
||||
if nightly {
|
||||
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
|
||||
res.set("ProductVersion", &built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("DECKCRAFT_REQUIRE_WINRES").is_some() {
|
||||
eprintln!("embedding Windows resources failed: {e}");
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Where the desktop app keeps its per-user data: `ui.json`, `prefs.json`, `logs/`, the crash
|
||||
//! recovery folder and the user dictionary all live under the directory [`config_dir`] returns.
|
||||
//!
|
||||
//! In order:
|
||||
//! 1. A selected Nightly profile root ([`crate::launch_profile`]): everything lives under it, and
|
||||
//! nothing is read from or written to a stable folder.
|
||||
//! 2. The platform convention: macOS `~/Library/Application Support/DeckCraft`, Windows
|
||||
//! `%APPDATA%\DeckCraft`, Linux `$XDG_CONFIG_HOME/deckcraft` or `~/.config/deckcraft`.
|
||||
//!
|
||||
//! DeckCraft has no portable mode and no `DECKCRAFT_CONFIG_DIR` override, so the stable resolution
|
||||
//! is exactly the one `main.rs` used before the Nightly channel; the fence module
|
||||
//! ([`crate::profile_root`]) still refuses a `DeckCraftData` folder or a `portable.txt` beside a
|
||||
//! DeckCraft executable, which a hand-made portable copy could carry.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// The portable data folder name a hand-made portable copy could use. No DeckCraft package
|
||||
/// writes it, but the fence refuses a profile inside one (see [`crate::profile_root`]).
|
||||
pub const PORTABLE_DATA_DIR: &str = "DeckCraftData";
|
||||
|
||||
/// The marker file of a portable copy, beside its executable.
|
||||
pub const PORTABLE_MARKERS: [&str; 1] = ["portable.txt"];
|
||||
|
||||
/// The portable marker in `dir`, when it is a regular file.
|
||||
pub fn portable_marker(dir: &Path) -> Option<PathBuf> {
|
||||
PORTABLE_MARKERS.iter().map(|name| dir.join(name)).find(|path| path.is_file())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// The profile root chosen by the Launcher (`--launch-profile nightly-v1`).
|
||||
Override,
|
||||
/// The platform convention (stable).
|
||||
Platform,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DataDir {
|
||||
pub dir: Option<PathBuf>,
|
||||
pub mode: Mode,
|
||||
}
|
||||
|
||||
/// The data directory for this process, resolved once.
|
||||
pub fn current() -> &'static DataDir {
|
||||
static DIR: OnceLock<DataDir> = OnceLock::new();
|
||||
DIR.get_or_init(|| match crate::launch_profile::current().root() {
|
||||
Some(root) => DataDir { dir: Some(root.to_path_buf()), mode: Mode::Override },
|
||||
None => DataDir { dir: platform_dir(|key| std::env::var_os(key)), mode: Mode::Platform },
|
||||
})
|
||||
}
|
||||
|
||||
/// The per-user settings directory (see the module docs).
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
current().dir.clone()
|
||||
}
|
||||
|
||||
/// The platform's settings directory. Read from the environment every call, so tests can vary it.
|
||||
pub fn platform_dir(env: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/DeckCraft"))
|
||||
} else if cfg!(windows) {
|
||||
env("APPDATA").map(|a| PathBuf::from(a).join("DeckCraft"))
|
||||
} else {
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("deckcraft"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The crash-recovery folder: inside the profile for Nightly, the platform's own folder for stable
|
||||
/// (`deckcraft_engine::recovery::default_dir`, which keeps autosaves out of the synced config).
|
||||
fn recovery_dir_for(current: &DataDir) -> Option<PathBuf> {
|
||||
match current {
|
||||
DataDir { dir: Some(root), mode: Mode::Override } => Some(root.join("Recovery")),
|
||||
_ => deckcraft_engine::recovery::default_dir(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`recovery_dir_for`] for this process.
|
||||
pub fn recovery_dir() -> Option<PathBuf> {
|
||||
recovery_dir_for(current())
|
||||
}
|
||||
|
||||
/// The user dictionary (`user.dic`, the words "Add to dictionary" keeps): inside the profile for
|
||||
/// Nightly, the platform's dictionary folder for stable.
|
||||
fn user_dictionary_for(current: &DataDir) -> Option<PathBuf> {
|
||||
match current {
|
||||
DataDir { dir: Some(root), mode: Mode::Override } => Some(root.join("Dictionaries").join("user.dic")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`user_dictionary_for`] for this process.
|
||||
pub fn user_dictionary() -> Option<PathBuf> {
|
||||
user_dictionary_for(current())
|
||||
}
|
||||
|
||||
/// The app's exclusive write probe: a new file created in `dir` and removed again. It never falls
|
||||
/// back to another directory, so the Nightly validator can refuse a root it cannot write.
|
||||
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
// A probe left behind by an interrupted launch must not make a writable profile look
|
||||
// unwritable, so each attempt uses a fresh name and a collision tries the next one.
|
||||
// `create_new` still guarantees a create rather than a truncation.
|
||||
for attempt in 0..8u32 {
|
||||
let probe = dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id()));
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(file) => {
|
||||
drop(file);
|
||||
return std::fs::remove_file(probe);
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name in the profile"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn env(pairs: &[(&str, &str)]) -> BTreeMap<String, OsString> {
|
||||
pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_dirs_follow_the_platform_convention() {
|
||||
let home = if cfg!(windows) { r"C:\Users\me" } else { "/home/me" };
|
||||
let env = env(&[("HOME", home), ("APPDATA", r"C:\Users\me\AppData\Roaming"), ("XDG_CONFIG_HOME", "/xdg/config")]);
|
||||
let dir = platform_dir(|k| env.get(k).cloned()).expect("a platform directory");
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(dir, PathBuf::from(home).join("Library/Application Support/DeckCraft"));
|
||||
} else if cfg!(windows) {
|
||||
assert_eq!(dir, PathBuf::from(r"C:\Users\me\AppData\Roaming").join("DeckCraft"));
|
||||
} else {
|
||||
assert_eq!(dir, PathBuf::from("/xdg/config").join("deckcraft"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovery and the dictionary follow the profile; stable keeps the engine's own folders and
|
||||
/// writes no per-profile dictionary.
|
||||
#[test]
|
||||
fn the_nightly_profile_owns_recovery_and_the_dictionary() {
|
||||
let root = PathBuf::from("/nightly-data/profiles/deckcraft");
|
||||
let profile = DataDir { dir: Some(root.clone()), mode: Mode::Override };
|
||||
assert_eq!(recovery_dir_for(&profile), Some(root.join("Recovery")));
|
||||
assert_eq!(user_dictionary_for(&profile), Some(root.join("Dictionaries").join("user.dic")));
|
||||
let stable = DataDir { dir: None, mode: Mode::Platform };
|
||||
assert_eq!(user_dictionary_for(&stable), None);
|
||||
assert_eq!(recovery_dir_for(&stable), deckcraft_engine::recovery::default_dir());
|
||||
}
|
||||
|
||||
/// The process resolves its data directory once; every caller must get that same decision.
|
||||
#[test]
|
||||
fn the_data_directory_is_resolved_once() {
|
||||
let resolved = current();
|
||||
assert!(std::ptr::eq(resolved, current()));
|
||||
assert_eq!(resolved.dir, config_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permanent_probe_does_not_replace_an_existing_entry() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-writable-{}-{}", std::process::id(), line!()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let probe = |attempt: u32| dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id()));
|
||||
// An entry already at the probe's name must never be truncated: the probe takes the next
|
||||
// free name, and it removes only the file it created.
|
||||
std::fs::write(probe(0), b"someone else's file").unwrap();
|
||||
ensure_writable(&dir).unwrap();
|
||||
assert_eq!(std::fs::read(probe(0)).unwrap(), b"someone else's file");
|
||||
assert!(!probe(1).exists());
|
||||
// Every name taken is an error, not a truncation of any of them.
|
||||
for attempt in 0..8 {
|
||||
std::fs::write(probe(attempt), b"someone else's file").unwrap();
|
||||
}
|
||||
assert!(ensure_writable(&dir).is_err(), "no free probe name is reported, not truncated");
|
||||
for attempt in 0..8 {
|
||||
assert_eq!(std::fs::read(probe(attempt)).unwrap(), b"someone else's file", "{attempt}");
|
||||
}
|
||||
for attempt in 0..8 {
|
||||
std::fs::remove_file(probe(attempt)).unwrap();
|
||||
}
|
||||
// A folder whose stale probes were cleared is writable, and the probe leaves nothing behind.
|
||||
ensure_writable(&dir).unwrap();
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/deckcraft-nightly.ico" } else { "../../assets/app-icon/deckcraft.ico" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
|
||||
assert_eq!(windows_icon_path(false), "../../assets/app-icon/deckcraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/deckcraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.19.0-nightly.20261124.17.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.19.0",
|
||||
"0.19.0-nightly",
|
||||
"0.19.0-nightly.20261124",
|
||||
"0.19.0-nightly.20261124.17.1.gABCDEF012345",
|
||||
"0.19.0-nightly.20261124.17.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.19.0-nightly.20261124.1.1.gabcdef012345",
|
||||
"0.19.0-nightly.20261124.1.1.gabcdef012345/other",
|
||||
"0.19.0-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(deckcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open DeckCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable DeckCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.19.0"), "0.19.0");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.19.0"), "0.19.0 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::app_dirs::ensure_writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" }
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
/// The process installs one profile; later answers are read-only and a second install fails.
|
||||
#[test]
|
||||
fn the_process_installs_its_profile_once() {
|
||||
assert_eq!(current(), &Profile::Stable, "an unselected process is a stable launch");
|
||||
assert!(install(Profile::Stable).is_ok());
|
||||
assert_eq!(current(), &Profile::Stable);
|
||||
assert!(install(Profile::Stable).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--sample", "a.pptx"]), args(&["--", "--launch-profile", "file.pptx"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "talk with spaces.pptx"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "talk with spaces.pptx"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "4242", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "1", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
+204
-41
@@ -14,17 +14,25 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod app_dirs;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod apple_events;
|
||||
mod audio;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod display;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod graphics;
|
||||
mod launch_profile;
|
||||
mod logging;
|
||||
mod nightly_session;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod pasteboard;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
|
||||
use deckcraft_engine::Session;
|
||||
use deckcraft_ui_egui::{Services, SlideApp};
|
||||
@@ -50,6 +58,10 @@ impl eframe::App for App {
|
||||
self.0.ui(ui);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
// The one exit path macOS has: run the hook exactly once (the Nightly session record).
|
||||
if let Some(hook) = self.0.services.at_exit.take() {
|
||||
hook();
|
||||
}
|
||||
save_prefs(&self.0);
|
||||
// The window is closing for good: a ready update's helper starts now and installs it once
|
||||
// the process has exited.
|
||||
@@ -69,25 +81,11 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-user settings directory: `ui.json`, `prefs.json` and `logs/` live here.
|
||||
fn config_dir() -> Option<std::path::PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/DeckCraft"))
|
||||
} else if cfg!(windows) {
|
||||
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("DeckCraft"))
|
||||
} else {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("deckcraft"))
|
||||
}
|
||||
}
|
||||
|
||||
fn load_prefs(app: &mut SlideApp) {
|
||||
if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = config_dir() else { return };
|
||||
let Some(dir) = app_dirs::config_dir() else { return };
|
||||
let (ui, prefs) = deckcraft_ui_egui::settings::load(&dir);
|
||||
if let Some(ui) = ui {
|
||||
app.ui = ui;
|
||||
@@ -101,7 +99,7 @@ fn save_prefs(app: &SlideApp) {
|
||||
if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(dir) = config_dir() {
|
||||
if let Some(dir) = app_dirs::config_dir() {
|
||||
deckcraft_ui_egui::settings::save(&dir, &app.ui, &app.session.prefs);
|
||||
}
|
||||
}
|
||||
@@ -155,8 +153,6 @@ fn display_count(window: &winit::window::Window) -> Option<usize> {
|
||||
(n > 0).then_some(n)
|
||||
}
|
||||
|
||||
const APP_ID: &str = "ai.storyteller.deckcraft";
|
||||
|
||||
const USAGE: &str = "\
|
||||
Usage: deckcraft [--control PORT] [--sample] [--show] [FILE...]
|
||||
|
||||
@@ -183,6 +179,11 @@ fn startup(mut control_port: Option<u16>, args: impl IntoIterator<Item = String>
|
||||
let mut args = args.into_iter();
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
// The Nightly Launcher form: everything after the delimiter is a file.
|
||||
"--" => {
|
||||
files.extend(args.by_ref());
|
||||
break;
|
||||
}
|
||||
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
|
||||
"--sample" => sample = true,
|
||||
"--show" => show = true,
|
||||
@@ -197,40 +198,134 @@ fn startup(mut control_port: Option<u16>, args: impl IntoIterator<Item = String>
|
||||
}
|
||||
|
||||
fn app_icon() -> Option<egui::IconData> {
|
||||
// The window icon follows the compiled channel, so a Nightly window is not the stable icon.
|
||||
#[cfg(deckcraft_nightly_v1)]
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/deckcraft-nightly.png");
|
||||
#[cfg(not(deckcraft_nightly_v1))]
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png");
|
||||
eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok()
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before any startup service or side effect.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before logger/crash/update/font/prefs access.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version()));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() {
|
||||
deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
|
||||
} else {
|
||||
deckcraft_ui_egui::os_window::LaunchIdentity::Stable
|
||||
};
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| deckcraft_ui_egui::os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(
|
||||
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
|
||||
deckcraft_ui_egui::os_window::id_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
|
||||
)
|
||||
}
|
||||
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("DeckCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("DeckCraft launch profile: {error}");
|
||||
return;
|
||||
}
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title("DeckCraft Nightly")
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Install logging, parse startup arguments and environment, launch the native app, and
|
||||
/// propagate an eframe startup failure.
|
||||
fn main() -> eframe::Result {
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
// Nightly session health: the record names this window's owner and survives an abnormal end.
|
||||
let (watch, session_unavailable) = nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
deckcraft_ui_egui::flavor::version(),
|
||||
option_env!("DECKCRAFT_BUILD_SHA"),
|
||||
)
|
||||
.unwrap_or_else(|error| {
|
||||
eprintln!("DeckCraft Nightly session state: {error}");
|
||||
(None, false)
|
||||
});
|
||||
let previous_unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
let session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(watch));
|
||||
let notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let exit_session = session.clone();
|
||||
let exit_notice = notice_shown.clone();
|
||||
// First, so every start-up record (and the engine's panic hook, installed with the first
|
||||
// Session) is captured; see `logging`.
|
||||
let logger = logging::install();
|
||||
if let Some(done) = craft_update::self_update::finish(&deckcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
// Nightly is managed by ArtCraft Launcher: no stable self-update helper runs in it.
|
||||
if !nightly
|
||||
&& let Some(done) = craft_update::self_update::finish(&deckcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
{
|
||||
if let Err(e) = done {
|
||||
eprintln!("DeckCraft update helper failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let (control_port, files, sample, show) =
|
||||
match startup(std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()), std::env::args().skip(1)) {
|
||||
Startup::Help => {
|
||||
print!("{USAGE}");
|
||||
return Ok(());
|
||||
}
|
||||
Startup::Version => {
|
||||
println!("deckcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
}
|
||||
Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show),
|
||||
};
|
||||
log::info!("DeckCraft {} ({} {})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH);
|
||||
let (control_port, files, sample, show) = match startup(
|
||||
if nightly { None } else { std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()) },
|
||||
arguments.into_iter().map(|a| a.to_string_lossy().into_owned()),
|
||||
) {
|
||||
Startup::Help => {
|
||||
print!("{USAGE}");
|
||||
return Ok(());
|
||||
}
|
||||
Startup::Version => {
|
||||
println!("deckcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
}
|
||||
Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show),
|
||||
};
|
||||
log::info!("DeckCraft {} ({} {})", deckcraft_ui_egui::flavor::version(), std::env::consts::OS, std::env::consts::ARCH);
|
||||
|
||||
// The log file lives under the settings directory; opened after the arguments, so `--help` and
|
||||
// `--version` leave no file behind. Records logged until now are written to it first.
|
||||
if let Some(logger) = logger {
|
||||
match config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
|
||||
match app_dirs::config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
|
||||
Some(Ok(path)) => log::info!("log file {}", path.display()),
|
||||
Some(Err(e)) => log::warn!("no log file: {e}"),
|
||||
None => {
|
||||
@@ -241,7 +336,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("DeckCraft")
|
||||
.with_title(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()))
|
||||
.with_inner_size([1440.0, 900.0])
|
||||
.with_min_inner_size([900.0, 560.0])
|
||||
.with_drag_and_drop(true)
|
||||
@@ -250,7 +345,7 @@ fn main() -> eframe::Result {
|
||||
.with_title_shown(false),
|
||||
..Default::default()
|
||||
};
|
||||
options.viewport = options.viewport.with_app_id(APP_ID);
|
||||
options.viewport = options.viewport.with_app_id(deckcraft_ui_egui::os_window::app_id());
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
}
|
||||
@@ -286,28 +381,46 @@ fn main() -> eframe::Result {
|
||||
let apple_events = apple_events::AppleEvents::install();
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
eframe::run_native(
|
||||
"DeckCraft",
|
||||
let creator_notice = notice_shown.clone();
|
||||
let mut services = services(native_wayland);
|
||||
// The Nightly session record is finished exactly once, on the clean exit path macOS has.
|
||||
services.at_exit = Some(Box::new(move || {
|
||||
nightly_session::finish_once(&exit_session, exit_notice.load(std::sync::atomic::Ordering::Relaxed));
|
||||
}));
|
||||
let result = eframe::run_native(
|
||||
deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx);
|
||||
let mut app = SlideApp::new(Session::new(), services(native_wayland));
|
||||
let mut app = SlideApp::new(Session::new(), services);
|
||||
// Presenter View asks winit how many displays there are when a show starts.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if let Some(window) = cc.winit_window().cloned() {
|
||||
app.services.displays = Some(Box::new(move || display_count(&window)));
|
||||
}
|
||||
load_prefs(&mut app);
|
||||
app.enable_update_checks();
|
||||
if !nightly {
|
||||
// Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed.
|
||||
app.enable_update_checks();
|
||||
}
|
||||
// AutoRecover: reopen what a previous run left unsaved, then keep it current.
|
||||
if std::env::var_os("DECKCRAFT_NO_RECOVERY").is_none() {
|
||||
app.session.recovery_dir = deckcraft_engine::recovery::default_dir();
|
||||
app.session.recovery_dir = app_dirs::recovery_dir();
|
||||
if let Ok(v) = app.session.execute("file.recovery.open", &serde_json::json!({}))
|
||||
&& let Some(n) = v.get("opened").and_then(|o| o.as_array()).map(Vec::len).filter(|n| *n > 0)
|
||||
{
|
||||
app.set_status(format!("Recovered {n} unsaved presentation{} from the last session", if n == 1 { "" } else { "s" }));
|
||||
}
|
||||
}
|
||||
if let Some(dictionary) = app_dirs::user_dictionary() {
|
||||
deckcraft_engine::spell::set_user_dictionary_path(dictionary);
|
||||
}
|
||||
if session_unavailable {
|
||||
app.set_status("Another DeckCraft Nightly window owns this profile: its session health is unavailable here.");
|
||||
} else if previous_unclean {
|
||||
app.set_status("DeckCraft Nightly closed unexpectedly last time.");
|
||||
creator_notice.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
@@ -329,7 +442,10 @@ fn main() -> eframe::Result {
|
||||
apple_events.connect(&cc.egui_ctx),
|
||||
)))
|
||||
}),
|
||||
)
|
||||
);
|
||||
// The exit hook normally finished it already; this covers a start that never created a window.
|
||||
nightly_session::finish_once(&session, notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -399,6 +515,53 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The delimiter is the Nightly Launcher's file list, never a file name of its own.
|
||||
#[test]
|
||||
fn the_delimiter_ends_the_flags_and_leaves_only_files() {
|
||||
let launch = startup(None, ["--", "--control", "deck.pptx"].map(str::to_string));
|
||||
assert!(matches!(launch, Startup::Run { control_port: None, .. }));
|
||||
if let Startup::Run { files, .. } = launch {
|
||||
assert_eq!(files, ["--control".to_string(), "deck.pptx".to_string()]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop crate's build script and the UI crate's read the same channel switch.
|
||||
#[test]
|
||||
fn both_crates_agree_on_the_compiled_channel() {
|
||||
assert_eq!(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, deckcraft_ui_egui::flavor::is_nightly());
|
||||
assert_eq!(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1), "DeckCraft Nightly");
|
||||
}
|
||||
|
||||
/// The exit hook (the Nightly session record) runs once, on the one exit path macOS has.
|
||||
/// The check runs in a child with `DECKCRAFT_NO_PREFS=1`: `on_exit` saves the preferences
|
||||
/// otherwise, and this test never loads the ones already on the machine. Not on macOS
|
||||
/// itself: there `on_exit` ends the process, which is the behaviour the test above checks.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn leaving_runs_the_exit_hook_once() {
|
||||
if std::env::var_os("DECKCRAFT_TEST_EXIT_HOOK").is_some() {
|
||||
let runs = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let counted = runs.clone();
|
||||
let services = Services { at_exit: Some(Box::new(move || counted.set(counted.get() + 1))), ..Default::default() };
|
||||
let mut app = App(SlideApp::new(Session::new(), services));
|
||||
eframe::App::on_exit(&mut app);
|
||||
assert_eq!(runs.get(), 1);
|
||||
eframe::App::on_exit(&mut app);
|
||||
assert_eq!(runs.get(), 1, "a second exit must not run the hook again");
|
||||
println!("exit hook ran once");
|
||||
return;
|
||||
}
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "tests::leaving_runs_the_exit_hook_once", "--nocapture"])
|
||||
.env("DECKCRAFT_TEST_EXIT_HOOK", "1")
|
||||
.env("DECKCRAFT_NO_PREFS", "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(out.status.success(), "{stdout}");
|
||||
assert!(stdout.contains("exit hook ran once"), "the child didn't run the test: {stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finder_process_serial_number_is_not_a_file() {
|
||||
let launch = startup(None, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]);
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! App-private Nightly session health, not telemetry or a Launcher protocol.
|
||||
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
|
||||
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const RECORD: &str = "nightly-session.json";
|
||||
const LEASE: &str = "nightly-session.lock";
|
||||
const MAX_METADATA_BYTES: usize = 256;
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through a new file in the same directory, then rename it into place.
|
||||
/// The rename replaces a symlink rather than following it, so a raced alias never reaches another
|
||||
/// file; the created file is mode 0600 and is synced before the rename.
|
||||
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let directory = path.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the session record has no directory"))?;
|
||||
let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the session record has no file name"))?;
|
||||
let temporary = directory.join(format!(".{}.{}.{}.tmp", name.to_string_lossy(), std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(&temporary)?;
|
||||
let written = file.write_all(bytes).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
if let Err(error) = written {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
match std::fs::rename(&temporary, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) => {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
|
||||
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
|
||||
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
|
||||
/// still runs for a start that created no window.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
|
||||
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
|
||||
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
if let Some(watch) = watch
|
||||
&& let Err(error) = watch.finish(unclean_notice_shown)
|
||||
{
|
||||
log::warn!("Nightly session state was left intact: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The warning belongs to this window: a busy secondary has no health-record coverage,
|
||||
/// while Stable and a lease-owning Nightly window preserve their existing result.
|
||||
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
|
||||
let watch = Self::begin(root, version, commit)?;
|
||||
let unavailable = root.is_some() && watch.is_none();
|
||||
Ok((watch, unavailable))
|
||||
}
|
||||
|
||||
/// `None` is stable or another owner of this profile. Neither case touches the record.
|
||||
/// The supplied root must already be the validated private Nightly profile.
|
||||
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed
|
||||
/// it yet (a renderer failure before the app callback), the record is left for the next owner
|
||||
/// to report; otherwise this is [`Self::complete`].
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
|
||||
/// An unwind, abort, forced exit or killed process never calls this method.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("deckcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
|
||||
assert!(!unfinished.previous_unclean());
|
||||
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
|
||||
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
|
||||
let fixture = Fixture::new();
|
||||
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
|
||||
// Renderer initialization failed before the app callback: no notice was shown.
|
||||
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The next start still sees the interruption and shows it.
|
||||
let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
|
||||
assert!(retry.previous_unclean());
|
||||
retry.finish(true).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
|
||||
// Without an earlier interruption, a handled failure still clears normally.
|
||||
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
|
||||
assert!(!clean.previous_unclean());
|
||||
clean.finish(false).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
|
||||
let fixture = Fixture::new();
|
||||
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
|
||||
// The exit hook (macOS quit: the only path that runs there).
|
||||
finish_once(&shared, false);
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
|
||||
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
|
||||
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
|
||||
assert!(!successor.previous_unclean());
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
finish_once(&shared, false);
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
|
||||
successor.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
|
||||
assert!(watch.complete().is_err());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
|
||||
let fixture = Fixture::new();
|
||||
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
|
||||
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
|
||||
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
|
||||
assert!(data["commit"].is_null(), "missing provenance must not be invented");
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn reserved_state_aliases_do_not_modify_external_files() {
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
for name in [LEASE, RECORD] {
|
||||
let alias = fixture.0.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Set the immutable nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
pub enum IdentityError {
|
||||
#[error("{0}")]
|
||||
Configuration(String),
|
||||
}
|
||||
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
|
||||
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError::Configuration)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::app_dirs::{PORTABLE_DATA_DIR, portable_marker};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The DeckCraft Nightly Flatpak app id (`packaging/linux/flatpak-bundle.sh`), the one Flatpak
|
||||
/// instance a Nightly profile may inherit.
|
||||
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.deckcraft.nightly";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("DeckCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
|
||||
// install folder is not known here; the executable's own folder is fenced below.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DeckCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("DeckCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("deckcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/deckcraft", "/usr/local/bin/deckcraft", "/opt/deckcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.deckcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/DeckCraft"),
|
||||
library.join("Caches/DeckCraft"),
|
||||
library.join("Caches/ai.storyteller.deckcraft"),
|
||||
library.join("Preferences/DeckCraft"),
|
||||
library.join("Preferences/ai.storyteller.deckcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.deckcraft.savedState"),
|
||||
home.join("Applications/DeckCraft.app"),
|
||||
PathBuf::from("/Applications/DeckCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (Dictionaries, logs, settings and so on) must
|
||||
/// resolve inside it, so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
// The one nested file Nightly writes itself: a link at Dictionaries/user.dic would append
|
||||
// "add to dictionary" words to the stable app's file instead of this profile's.
|
||||
private_subdirectory(root, std::path::Path::new("Dictionaries").join("user.dic"), "user dictionary")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise a portable data namespace in both the supplied and resolved path. DeckCraft ships no
|
||||
/// portable package, so this only refuses a hand-made copy; it is not an inventory of arbitrary
|
||||
/// custom Stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
// Above the chosen folder itself, a marker only counts beside a DeckCraft executable, so an
|
||||
// unrelated portable.txt higher up (in a user folder or at a drive root) does not refuse it.
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
portable_marker(ancestor).is_some() && (depth == 0 || ["deckcraft.exe", "deckcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.components().any(|component| match component {
|
||||
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
|
||||
Component::Normal(name) => name == PORTABLE_DATA_DIR,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
|
||||
/// boundary tests exercise the real policy without starting the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) {
|
||||
// The native tar and app-bundle rows are not Flatpak packages: inheriting a Flatpak
|
||||
// runtime could point another profile at the stable app's data. DeckCraft Nightly's own
|
||||
// Flatpak (packaging/linux/flatpak-bundle.sh) is the one allowed instance, matched by its
|
||||
// exact id; the stable id and any other app are refused.
|
||||
if platform == Platform::Windows || id != NIGHTLY_FLATPAK_ID {
|
||||
return Err("nightly-v1 accepts only the DeckCraft Nightly Flatpak instance; launch through the native Launcher".into());
|
||||
}
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
|
||||
return Err("the nightly root must not use a portable DeckCraft copy or its DeckCraftData settings folder".into());
|
||||
}
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this
|
||||
// private profile, including toward a Stable portable directory not in our known roots.
|
||||
private_subdirectory(&chosen, "Recovery", "recovery folder")?;
|
||||
private_subdirectory(&chosen, "Dictionaries", "dictionary folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, "Recovery", "recovery folder")?;
|
||||
private_subdirectory(&confirmed, "Dictionaries", "dictionary folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("deckcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/deckcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_settings_from_another_install_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let stable_install = fixture.root.join("stable portable install");
|
||||
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&stable_data).unwrap();
|
||||
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
|
||||
assert!(!probed.get(), "reject portable data before a writable probe");
|
||||
assert!(!stable_data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
|
||||
}
|
||||
}
|
||||
let private = fixture.root.join("DeckCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/share/deckcraft/recovery");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-self");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let recovery = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&recovery).unwrap();
|
||||
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery);
|
||||
}
|
||||
|
||||
/// The public entry point reads the host platform and refuses a relative root before probing.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn the_public_validator_uses_the_host_platform_and_creates_only_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/deckcraft");
|
||||
let created = validate(&root, |key| fixture.get(key), Some(&fixture.exe), crate::app_dirs::ensure_writable)
|
||||
.expect("a private profile under HOME is valid on Linux");
|
||||
assert_eq!(created, root);
|
||||
assert!(created.is_dir());
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let refused = validate(
|
||||
Path::new("relative/profile"),
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(refused.is_err());
|
||||
assert!(!probed.get(), "a relative root is refused before the write probe");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/deckcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Recovery"), platform));
|
||||
assert!(overlaps(&root.join("Recovery"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("deckcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("deckcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/deckcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/DeckCraft Nightly.app/Contents/MacOS/DeckCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/DeckCraft",
|
||||
"Caches/DeckCraft",
|
||||
"Caches/ai.storyteller.deckcraft",
|
||||
"Preferences/DeckCraft",
|
||||
"Saved Application State/ai.storyteller.deckcraft.savedState",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/deckcraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_roaming_local_and_install_fences_remain_active() {
|
||||
let fixture = Fixture::new();
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("DeckCraft");
|
||||
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/deckcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_msi_install_folders_are_fenced() {
|
||||
let mut fixture = Fixture::new();
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("DeckCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("DeckCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("deckcraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not DeckCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let portable = fixture.root.join("D/DC");
|
||||
std::fs::create_dir_all(&portable).unwrap();
|
||||
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
|
||||
std::fs::write(portable.join("deckcraft.exe"), b"stable portable executable, never run").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("portable"));
|
||||
assert!(!probed.get());
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
}
|
||||
// A portable.txt that no DeckCraft executable sits beside is someone else's file.
|
||||
let unrelated = fixture.root.join("user folder");
|
||||
std::fs::create_dir_all(&unrelated).unwrap();
|
||||
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
|
||||
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/deckcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.deckcraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn any_profile_entry_alias_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/deckcraft/logs");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-log"), b"stable log bytes").unwrap();
|
||||
for name in ["Dictionaries", "logs", "ui.json"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "{name} must not lead outside the profile");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("real-dictionaries")).unwrap();
|
||||
std::fs::write(private.join("ui.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("real-dictionaries"), private.join("Dictionaries")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(stable.join("stable-log")).unwrap(), b"stable log bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/deckcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
// The stable Flatpak instance, or any other app's, is not a Nightly launch.
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.deckcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
fixture.env.insert("FLATPAK_ID".into(), "org.example.other".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
// DeckCraft Nightly's own Flatpak is the one allowed instance.
|
||||
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).is_ok());
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let file = fixture.home().join("not-a-directory");
|
||||
std::fs::write(&file, b"regular file").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &file.join("nightly")).is_err());
|
||||
let candidate = fixture.home().join("nightly/profiles/deckcraft");
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "read-only")),
|
||||
);
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert!(!candidate.join("Recovery").exists(), "a failed probe leaves no stable fallback behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_roots_and_parent_traversal_are_refused() {
|
||||
let fixture = Fixture::new();
|
||||
for candidate in [PathBuf::from("relative/nightly"), fixture.home().join("nightly/../escape")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 111 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.1 KiB |
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"title": "DeckCraft nightly deep-background icons",
|
||||
"author": "@skylartaylor",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"inputs": [
|
||||
{
|
||||
"path": "assets/app-icon/deckcraft-1024.png",
|
||||
"sha256": "457cb046a1a4f2e13f06cf7e2e071cb48f6011633ed629b99ff348be4ca91ce0",
|
||||
"purpose": "native padded Mac 1024 master; not upscaled from 256"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png",
|
||||
"sha256": "66343901b993332bceadf13277e6a028b80b2fb3a1e215b841c855be731e5130",
|
||||
"purpose": "stable 256 window icon the nightly icon replaces"
|
||||
}
|
||||
],
|
||||
"method": {
|
||||
"kind": "original code-generated derivative of the project-owned icon",
|
||||
"original_palette": {
|
||||
"ink": "#0b0b0c",
|
||||
"paper": "#efe9dc",
|
||||
"background": "#f26b1d"
|
||||
},
|
||||
"nightly_background": "#a6420c",
|
||||
"transform": "Solve each pixel's background contribution a in p = a*F + (1-a)*background for the ink and paper foregrounds, then recolour only the background region reached by a flush inward from the icon's transparent padding, so the accent bars that share the background colour keep their brightness behind the ink outlines. Preserve alpha, padding, foreground and detail RGBA. Derive native-size frames separately by area-averaging from the 1024 master (not upscaled from 256) and pack them into ICO/ICNS. No crescent, letter or badge.",
|
||||
"generator": "pure-Python stdlib script (zlib/struct), run once by the porting agent; not committed, matching PhotoCraft's provenance-only record",
|
||||
"generator_sha256": "0f90e2d49fe8fc3f2c75c442e730f49652e9b47b0bf9b8ee83c0a9214088569e"
|
||||
},
|
||||
"outputs": {
|
||||
"assets/app-icon/deckcraft-nightly.png": "560b27431cba6bc8658bf654c34981687c2061499139a03ba8b15a6ffed0bc9b",
|
||||
"assets/app-icon/deckcraft-nightly.ico": "8c66648b036da025b29e1f3d981c959f5d3aab818ddea5049a49706eee800a3a",
|
||||
"assets/app-icon/deckcraft-nightly-1024.png": "b64ef900d0997d7fe99d75b1f5471276cca75029902841d02f045a4f3f8a7f09",
|
||||
"assets/app-icon/deckcraft-nightly.icns": "3eb88330c1fffb8e7a27667ac7d53deea62d4c99f43e6bf878a0b89d43934b8d"
|
||||
},
|
||||
"ico_frame_sizes": [
|
||||
16,
|
||||
20,
|
||||
24,
|
||||
32,
|
||||
40,
|
||||
48,
|
||||
64,
|
||||
128,
|
||||
256
|
||||
],
|
||||
"icns_png_slots": {
|
||||
"icp4": 16,
|
||||
"icp5": 32,
|
||||
"ic11": 32,
|
||||
"icp6": 64,
|
||||
"ic12": 64,
|
||||
"ic07": 128,
|
||||
"ic08": 256,
|
||||
"ic13": 256,
|
||||
"ic09": 512,
|
||||
"ic14": 512,
|
||||
"ic10": 1024
|
||||
},
|
||||
"validation": "Input/output hashes, PNG CRC/dimensions and exact container members checked; the source master is unchanged. Native Explorer/Finder/iconutil/app-package qualification remains unrun.",
|
||||
"ico_frame_format": "16-128 are 32bpp BGRA DIB frames with AND masks (rc.exe/Explorer); 256 is a PNG frame"
|
||||
}
|
||||
+114
-144
@@ -91,12 +91,6 @@ const SKIP: &[&str] = &[
|
||||
"pntxtb",
|
||||
];
|
||||
|
||||
/// `i + n`, or one character on when that would land inside a multi-byte character (a fallback
|
||||
/// run after `\uN` or `\'hh` may be followed by non-ASCII text).
|
||||
fn advance(rtf: &str, i: usize, n: usize) -> usize {
|
||||
if rtf.is_char_boundary(i + n) { i + n } else { i + rtf.get(i..).and_then(|r| r.chars().next()).map_or(1, char::len_utf8) }
|
||||
}
|
||||
|
||||
/// Group state: whether the text is being skipped, and the `\uc` fallback count.
|
||||
#[derive(Clone, Copy)]
|
||||
struct St {
|
||||
@@ -105,10 +99,7 @@ struct St {
|
||||
}
|
||||
|
||||
/// Parser state for [`rtf_to_outline`]: the cursor, the group stack and the outline so far.
|
||||
struct Outline<'a> {
|
||||
rtf: &'a str,
|
||||
b: &'a [u8],
|
||||
i: usize,
|
||||
struct Outline {
|
||||
stack: Vec<St>,
|
||||
st: St,
|
||||
level: Option<u32>,
|
||||
@@ -118,6 +109,9 @@ struct Outline<'a> {
|
||||
/// Which `\s1`-`\s9` the stylesheet names "heading N"; any other `\sN` is a body style.
|
||||
headings: [bool; 10],
|
||||
pending_skip: usize,
|
||||
/// Remaining UTF-8 continuation bytes to skip from the next `Token::Text` after a
|
||||
/// non-ASCII `Token::Symbol`.
|
||||
skip_cont: usize,
|
||||
line: String,
|
||||
/// Paragraphs so far: outline level and text (empty only for an empty level-0 title).
|
||||
out: Vec<(usize, String)>,
|
||||
@@ -153,60 +147,49 @@ pub fn rtf_to_slides(p: &mut Presentation, rtf: &str) -> usize {
|
||||
/// The `\sN` styles the stylesheet calls "heading N": `{\s1\li360 heading 1;}`.
|
||||
fn heading_styles(rtf: &str) -> [bool; 10] {
|
||||
let mut out = [false; 10];
|
||||
let Some(at) = rtf.find("\\stylesheet") else { return out };
|
||||
let b = rtf.as_bytes();
|
||||
let (mut i, mut depth) = (at + "\\stylesheet".len(), 1);
|
||||
let (mut style, mut name): (Option<usize>, String) = (None, String::new());
|
||||
while i < b.len() && depth > 0 {
|
||||
match b[i] {
|
||||
b'{' => {
|
||||
let mut depth = 0usize;
|
||||
let mut stylesheet_depth: Option<usize> = None;
|
||||
let mut style: Option<i32> = None;
|
||||
let mut name = String::new();
|
||||
for token in craft_rtf::Tokens::new(rtf.as_bytes()) {
|
||||
match token {
|
||||
craft_rtf::Token::Open => {
|
||||
depth += 1;
|
||||
(style, name) = (None, String::new());
|
||||
if stylesheet_depth.is_some_and(|sd| depth == sd + 1) {
|
||||
style = None;
|
||||
name.clear();
|
||||
}
|
||||
}
|
||||
b'}' => {
|
||||
depth -= 1;
|
||||
if depth == 1
|
||||
&& let Some(n) = style.filter(|n| (1..=9).contains(n))
|
||||
craft_rtf::Token::Close => {
|
||||
if stylesheet_depth.is_some_and(|sd| depth == sd + 1)
|
||||
&& let Some(n) = style.filter(|&n| (1..=9).contains(&n))
|
||||
{
|
||||
out[n] = name.trim().to_ascii_lowercase().starts_with("heading");
|
||||
out[n as usize] = name.trim().to_ascii_lowercase().starts_with("heading");
|
||||
}
|
||||
depth = depth.saturating_sub(1);
|
||||
if stylesheet_depth.is_some_and(|sd| depth < sd) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
b'\\' => {
|
||||
let w = i + 1;
|
||||
let mut j = w;
|
||||
while j < b.len() && b[j].is_ascii_alphabetic() {
|
||||
j += 1;
|
||||
craft_rtf::Token::Word { name: "stylesheet", .. } if stylesheet_depth.is_none() && depth > 0 => {
|
||||
stylesheet_depth = Some(depth);
|
||||
}
|
||||
craft_rtf::Token::Word { name: "s", param: Some(n) } if stylesheet_depth.is_some_and(|sd| depth == sd + 1) => {
|
||||
style = Some(n);
|
||||
}
|
||||
craft_rtf::Token::Text(t) if stylesheet_depth.is_some_and(|sd| depth == sd + 1) => {
|
||||
for &b in t {
|
||||
name.push(b as char);
|
||||
}
|
||||
let k = j;
|
||||
while j < b.len() && (b[j].is_ascii_digit() || j == k && b[j] == b'-') {
|
||||
j += 1;
|
||||
}
|
||||
if depth == 2 && &rtf[w..k] == "s" {
|
||||
style = rtf[k..j].parse().ok();
|
||||
}
|
||||
// A control symbol is one character; a control word may be followed by a space.
|
||||
i = if k == w {
|
||||
w + 1
|
||||
} else if b.get(j) == Some(&b' ') {
|
||||
j + 1
|
||||
} else {
|
||||
j
|
||||
};
|
||||
continue;
|
||||
}
|
||||
c if depth == 2 && !matches!(c, b'\r' | b'\n') => name.push(c as char),
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
|
||||
let mut p = Outline {
|
||||
rtf,
|
||||
b: rtf.as_bytes(),
|
||||
i: 0,
|
||||
stack: vec![],
|
||||
st: St { skip: false, uc: 1 },
|
||||
level: None,
|
||||
@@ -214,79 +197,56 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
|
||||
indent: 0,
|
||||
headings: heading_styles(rtf),
|
||||
pending_skip: 0,
|
||||
skip_cont: 0,
|
||||
line: String::new(),
|
||||
out: vec![],
|
||||
};
|
||||
p.run();
|
||||
p.run(rtf);
|
||||
p.flush(false);
|
||||
p.out.into_iter().map(|(n, t)| (n, finish_surrogates(t))).collect()
|
||||
}
|
||||
|
||||
impl Outline<'_> {
|
||||
fn run(&mut self) {
|
||||
while self.i < self.b.len() {
|
||||
match self.b[self.i] {
|
||||
b'{' => self.open_group(),
|
||||
b'}' => self.close_group(),
|
||||
b'\\' => {
|
||||
self.i += 1;
|
||||
if !self.escape() {
|
||||
break;
|
||||
}
|
||||
impl Outline {
|
||||
fn run(&mut self, rtf: &str) {
|
||||
let mut tokens = craft_rtf::Tokens::new(rtf.as_bytes());
|
||||
while let Some(token) = tokens.next() {
|
||||
match token {
|
||||
craft_rtf::Token::Open => self.open_group(),
|
||||
craft_rtf::Token::Close => self.close_group(),
|
||||
craft_rtf::Token::Star => {
|
||||
self.pending_skip = 0;
|
||||
self.skip_cont = 0;
|
||||
self.st.skip = true;
|
||||
}
|
||||
b'\r' | b'\n' => self.i += 1,
|
||||
_ => self.text(),
|
||||
craft_rtf::Token::Word { name, param } => {
|
||||
self.skip_cont = 0;
|
||||
self.word(name, param);
|
||||
}
|
||||
craft_rtf::Token::Hex(h) => {
|
||||
self.skip_cont = 0;
|
||||
self.hex_escape(h);
|
||||
}
|
||||
craft_rtf::Token::Symbol(n) => self.symbol(n, rtf, tokens.offset()),
|
||||
craft_rtf::Token::Text(t) => self.text(t),
|
||||
craft_rtf::Token::Bin(_) => self.skip_cont = 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `{`: push the group; `{\*\dest …}` is an ignorable destination.
|
||||
fn open_group(&mut self) {
|
||||
self.pending_skip = 0;
|
||||
self.skip_cont = 0;
|
||||
self.stack.push(self.st);
|
||||
self.i += 1;
|
||||
if self.b[self.i..].starts_with(b"\\*") {
|
||||
self.st.skip = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn close_group(&mut self) {
|
||||
self.pending_skip = 0;
|
||||
self.skip_cont = 0;
|
||||
self.st = self.stack.pop().unwrap_or(St { skip: false, uc: 1 });
|
||||
self.i += 1;
|
||||
}
|
||||
|
||||
/// The character after a backslash: a control word, a hex escape or a symbol. False at the
|
||||
/// end of the input.
|
||||
fn escape(&mut self) -> bool {
|
||||
let Some(&n) = self.b.get(self.i) else { return false };
|
||||
if n.is_ascii_alphabetic() {
|
||||
self.control_word();
|
||||
} else if n == b'\'' {
|
||||
self.hex_escape();
|
||||
} else {
|
||||
self.symbol(n);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn control_word(&mut self) {
|
||||
let rtf = self.rtf;
|
||||
let s = self.i;
|
||||
while self.i < self.b.len() && self.b[self.i].is_ascii_alphabetic() {
|
||||
self.i += 1;
|
||||
}
|
||||
let word = &rtf[s..self.i];
|
||||
let ns = self.i;
|
||||
if self.i < self.b.len() && (self.b[self.i] == b'-' || self.b[self.i].is_ascii_digit()) {
|
||||
self.i += 1;
|
||||
while self.i < self.b.len() && self.b[self.i].is_ascii_digit() {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
let arg: Option<i64> = rtf[ns..self.i].parse().ok();
|
||||
if self.i < self.b.len() && self.b[self.i] == b' ' {
|
||||
self.i += 1;
|
||||
}
|
||||
if self.pending_skip > 0 {
|
||||
fn word(&mut self, word: &str, arg: Option<i32>) {
|
||||
if self.pending_skip > 0 && word != "u" {
|
||||
self.pending_skip -= 1;
|
||||
return;
|
||||
}
|
||||
@@ -298,7 +258,7 @@ impl Outline<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, word: &str, arg: Option<i64>) {
|
||||
fn apply(&mut self, word: &str, arg: Option<i32>) {
|
||||
match word {
|
||||
"par" => self.flush(true),
|
||||
"pard" => {
|
||||
@@ -312,10 +272,10 @@ impl Outline<'_> {
|
||||
"s" => {
|
||||
self.style_level = arg.filter(|a| (1..=9).contains(a) && self.headings[*a as usize]).map(|a| a as u32 - 1);
|
||||
}
|
||||
"li" => self.indent = arg.unwrap_or(0),
|
||||
"li" => self.indent = i64::from(arg.unwrap_or(0)),
|
||||
"tab" | "line" => self.line.push(' '),
|
||||
"uc" => self.st.uc = arg.unwrap_or(1).clamp(0, 8) as usize,
|
||||
"u" => self.unicode(arg.unwrap_or(0)),
|
||||
"u" => self.unicode(i64::from(arg.unwrap_or(0))),
|
||||
"emdash" => self.line.push('—'),
|
||||
"endash" => self.line.push('–'),
|
||||
"bullet" => self.line.push('•'),
|
||||
@@ -331,40 +291,32 @@ impl Outline<'_> {
|
||||
fn unicode(&mut self, v: i64) {
|
||||
// RTF writes UTF-16 units as signed 16-bit values.
|
||||
push_utf16(&mut self.line, (v & 0xffff) as u32);
|
||||
self.pending_skip = 0;
|
||||
let mut k = self.st.uc;
|
||||
while k > 0 && self.i < self.b.len() {
|
||||
if self.b[self.i] == b'\\' && self.b.get(self.i + 1) == Some(&b'\'') {
|
||||
self.i = advance(self.rtf, self.i, 4);
|
||||
} else if self.b[self.i] == b'\\' && self.b.get(self.i + 1).is_some_and(|b| !b.is_ascii_alphabetic()) {
|
||||
// An escaped control symbol counts as one Unicode fallback character.
|
||||
self.i = advance(self.rtf, self.i + 1, 1);
|
||||
} else if matches!(self.b[self.i], b'{' | b'}' | b'\\') {
|
||||
break;
|
||||
} else {
|
||||
self.i = advance(self.rtf, self.i, 1);
|
||||
}
|
||||
k -= 1;
|
||||
}
|
||||
self.pending_skip = self.st.uc;
|
||||
}
|
||||
|
||||
/// `\'hh`: one cp1252 byte.
|
||||
fn hex_escape(&mut self) {
|
||||
let hex =
|
||||
self.rtf.get(self.i + 1..self.i + 3).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())).and_then(|h| u8::from_str_radix(h, 16).ok());
|
||||
self.i = advance(self.rtf, self.i, 3);
|
||||
if !self.st.skip
|
||||
&& let Some(h) = hex
|
||||
&& h != 0
|
||||
{
|
||||
fn hex_escape(&mut self, h: u8) {
|
||||
if self.pending_skip > 0 {
|
||||
self.pending_skip -= 1;
|
||||
return;
|
||||
}
|
||||
if !self.st.skip && h != 0 {
|
||||
self.line.push(craft_rtf::codepage::cp1252(h));
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-character control symbol (`\\`, `\{`, `\~`, ...).
|
||||
fn symbol(&mut self, n: u8) {
|
||||
let c = self.rtf.get(self.i..).and_then(|r| r.chars().next());
|
||||
self.i = advance(self.rtf, self.i, 1);
|
||||
fn symbol(&mut self, n: u8, rtf: &str, offset: usize) {
|
||||
let cont = if !n.is_ascii() {
|
||||
rtf.get(offset.saturating_sub(1)..).and_then(|r| r.chars().next()).map(|c| (c, c.len_utf8().saturating_sub(1)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.skip_cont = cont.map_or(0, |(_, k)| k);
|
||||
if self.pending_skip > 0 {
|
||||
self.pending_skip -= 1;
|
||||
return;
|
||||
}
|
||||
if self.st.skip {
|
||||
return;
|
||||
}
|
||||
@@ -373,21 +325,30 @@ impl Outline<'_> {
|
||||
b'~' => self.line.push('\u{a0}'),
|
||||
b'_' => self.line.push('\u{2011}'),
|
||||
b'\n' | b'\r' => self.flush(true),
|
||||
_ if !n.is_ascii() => self.line.extend(c),
|
||||
_ => {}
|
||||
_ => {
|
||||
if let Some((c, _)) = cont {
|
||||
self.line.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain text up to the next special character.
|
||||
fn text(&mut self) {
|
||||
let s = self.i;
|
||||
while self.i < self.b.len() && !matches!(self.b[self.i], b'{' | b'}' | b'\\' | b'\r' | b'\n') {
|
||||
self.i += 1;
|
||||
fn text(&mut self, t: &[u8]) {
|
||||
let skip_cont = std::mem::take(&mut self.skip_cont);
|
||||
let t = t.get(skip_cont..).unwrap_or_default();
|
||||
let Ok(mut s) = std::str::from_utf8(t) else { return };
|
||||
if self.pending_skip > 0 {
|
||||
if let Some((idx, _)) = s.char_indices().nth(self.pending_skip) {
|
||||
self.pending_skip = 0;
|
||||
s = &s[idx..];
|
||||
} else {
|
||||
self.pending_skip -= s.chars().count();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if !self.st.skip
|
||||
&& let Some(t) = self.rtf.get(s..self.i)
|
||||
{
|
||||
self.line.push_str(&t.replace('\u{0}', ""));
|
||||
if !self.st.skip {
|
||||
self.line.push_str(s);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -535,7 +496,7 @@ mod tests {
|
||||
/// A sign in a `\'hh` escape is not a hex digit and must be ignored.
|
||||
#[test]
|
||||
fn hex_escape_rejects_sign() {
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1 a\'+5b\par}"), "ab\n");
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1 a\'+5b\par}"), "a+5b\n");
|
||||
}
|
||||
|
||||
/// Non-ASCII text after a `\\uN` or `\\'hh` escape used to split a character and panic.
|
||||
@@ -585,10 +546,10 @@ mod tests {
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1\pard Year\_end review\par}"), "Year\u{2011}end review\n");
|
||||
}
|
||||
|
||||
/// A hostile `\li` near `i64::MAX` overflowed the rounding addend in debug builds.
|
||||
/// A hostile `\li` near `i32::MAX` (clamped from 10 digits by `craft_rtf::Tokens`) must not overflow.
|
||||
#[test]
|
||||
fn huge_left_indent_gives_the_deepest_level() {
|
||||
let out = rtf_to_outline(r"{\rtf1\pard\li9223372036854775807 deep\par\pard\li-9223372036854775808 flat\par}");
|
||||
let out = rtf_to_outline(r"{\rtf1\pard\li9999999999 deep\par\pard\li-9999999999 flat\par}");
|
||||
assert_eq!(out, format!("{}deep\nflat\n", "\t".repeat(9)));
|
||||
}
|
||||
|
||||
@@ -681,4 +642,13 @@ mod tests {
|
||||
let rtf = r"{\rtf1\ansi\pard Title\par\pard\fi-360\li720{\listtext\pard\plain\f1\'b7\tab}Point\par\pard\li720{\pntext\f1\'b7\tab}Old\par}";
|
||||
assert_eq!(rtf_to_outline(rtf), "Title\n\t\tPoint\n\t\tOld\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surrogate_pairs_bullets_and_binary_groups_survive_tokenization() {
|
||||
let rtf = "{\\rtf1\\ansi{\\stylesheet{\\s1\\li360 heading 1;}{\\s2\\li1080 heading 2;}}\\pard\\s1 \\u-10179?\\u-8704? \\u-10179?\\par\\pard\\s1 \\par\\pard\\s2 \\bullet item\\par{\\pict\\bin5 {\\}\0\\x}\\pard\\s1 - title\\par}";
|
||||
assert_eq!(rtf_to_outline(rtf), "😀 \u{fffd}\n\t• item\n- title\n");
|
||||
let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false);
|
||||
assert_eq!(rtf_to_slides(&mut p, rtf), 3);
|
||||
assert_eq!(crate::slides_to_outline(&p), "😀 \u{fffd}\n\n\t• item\n- title\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,3 +304,73 @@ fn export_tool_lists_gif_and_its_options() {
|
||||
assert_eq!(r["result"]["isError"], true, "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_initialize_negotiation_transcript() {
|
||||
let mut lines: Vec<Value> = craft_mcp_server::SUPPORTED_VERSIONS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, version)| {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": i + 1,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": version, "capabilities": {}, "clientInfo": {"name": "parity-client", "version": "1.0"}},
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
lines.push(json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 99,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": "1999-01-01", "capabilities": {}, "clientInfo": {"name": "parity-client", "version": "1.0"}},
|
||||
}));
|
||||
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
|
||||
lines.push(json!({"jsonrpc": "2.0", "id": 100, "method": "ping", "params": {}}));
|
||||
let input: String = lines.iter().map(|v| v.to_string() + "\n").collect();
|
||||
|
||||
let mut s = Server::new(Box::new(Headless::new()));
|
||||
let mut out = Vec::new();
|
||||
s.serve(std::io::Cursor::new(input), &mut out).unwrap();
|
||||
assert!(s.is_initialized());
|
||||
|
||||
let replies: Vec<Value> = std::str::from_utf8(&out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(replies.len(), craft_mcp_server::SUPPORTED_VERSIONS.len() + 2);
|
||||
for (i, version) in craft_mcp_server::SUPPORTED_VERSIONS.iter().enumerate() {
|
||||
assert_eq!(replies[i]["id"], i + 1);
|
||||
assert_eq!(replies[i]["result"]["protocolVersion"], *version);
|
||||
assert_eq!(replies[i]["result"]["serverInfo"]["name"], "deckcraft");
|
||||
}
|
||||
let fallback = &replies[craft_mcp_server::SUPPORTED_VERSIONS.len()];
|
||||
assert_eq!(fallback["id"], 99);
|
||||
assert_eq!(fallback["result"]["protocolVersion"], craft_mcp_server::PROTOCOL_VERSION);
|
||||
let ping = &replies[craft_mcp_server::SUPPORTED_VERSIONS.len() + 1];
|
||||
assert_eq!(ping["id"], 100);
|
||||
assert_eq!(ping["result"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_cancel_and_batch_transcript() {
|
||||
let input = concat!(
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\"}}\n",
|
||||
"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
|
||||
"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":1,\"reason\":\"client\"}}\n",
|
||||
"[]\n",
|
||||
"[{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":9}}]\n",
|
||||
"[{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"},{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}]\n",
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\",\"params\":{}}\n"
|
||||
);
|
||||
let mut s = Server::new(Box::new(Headless::new()));
|
||||
let mut out = Vec::new();
|
||||
s.serve(std::io::Cursor::new(input), &mut out).unwrap();
|
||||
assert!(s.is_initialized());
|
||||
|
||||
let replies: Vec<Value> = std::str::from_utf8(&out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(replies.len(), 4, "{replies:?}");
|
||||
assert_eq!(replies[0]["id"], 1);
|
||||
assert_eq!(replies[0]["result"]["serverInfo"]["name"], "deckcraft");
|
||||
assert_eq!(replies[1]["id"], Value::Null);
|
||||
assert_eq!(replies[1]["error"]["code"], -32600);
|
||||
assert_eq!(replies[2], json!([{"jsonrpc": "2.0", "id": 2, "result": {}}]));
|
||||
assert_eq!(replies[3], json!({"jsonrpc": "2.0", "id": 3, "result": {}}));
|
||||
}
|
||||
|
||||
@@ -9,19 +9,15 @@ description = "DeckCraft PPTX: Office Open XML (PresentationML/DrawingML) import
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-pptx.workspace = true
|
||||
craft-opc.workspace = true
|
||||
craft-xml.workspace = true
|
||||
craft-cfb.workspace = true
|
||||
craft-drawingml.workspace = true
|
||||
craft-drawingml-table.workspace = true
|
||||
deckcraft-model = { workspace = true }
|
||||
deckcraft-text = { workspace = true }
|
||||
deckcraft-geom = { workspace = true }
|
||||
deckcraft-color = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
deckcraft-engine = { workspace = true }
|
||||
@@ -29,4 +25,5 @@ serde_json = { workspace = true }
|
||||
deckcraft-color = { workspace = true }
|
||||
deckcraft-geom = { workspace = true }
|
||||
image = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,547 +0,0 @@
|
||||
//! DrawingML custom geometry (`a:custGeom`): guide formula evaluation and conversion of
|
||||
//! `a:pathLst` to our `M L C Q Z` path syntax, and back.
|
||||
//!
|
||||
//! Formulas follow the ECMA-376 shape guide semantics (§20.1.9.11): angles are in 1/60 000 degree,
|
||||
//! and every operand is a guide name, a built-in variable or an integer literal.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::f64::consts::PI;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use deckcraft_geom::preset::FillMode;
|
||||
use deckcraft_model::CustomPath;
|
||||
|
||||
use crate::xml::{A, El, W};
|
||||
|
||||
const DEG: f64 = 60_000.0;
|
||||
|
||||
/// Distinct path coordinate spaces whose guides are evaluated for one custom geometry; paths in
|
||||
/// further spaces are left out.
|
||||
const MAX_SPACES: usize = 16;
|
||||
|
||||
/// Guide-name bytes all cached spaces may hold between them; the first space counts towards it but is always kept.
|
||||
/// Every space copies the names, which the XML limits bound only once.
|
||||
const MAX_SPACE_NAME_BYTES: usize = 4 << 20;
|
||||
|
||||
/// Guide variables for one shape.
|
||||
pub struct Guides {
|
||||
vars: HashMap<String, f64>,
|
||||
}
|
||||
|
||||
fn to_rad(a: f64) -> f64 {
|
||||
a / DEG * PI / 180.0
|
||||
}
|
||||
|
||||
fn to_ang(r: f64) -> f64 {
|
||||
r * 180.0 / PI * DEG
|
||||
}
|
||||
|
||||
fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() { v.clamp(-1.0e15, 1.0e15) } else { 0.0 }
|
||||
}
|
||||
|
||||
impl Guides {
|
||||
/// Built-in variables for a shape `w` × `h` (in the shape's coordinate units).
|
||||
pub fn new(w: f64, h: f64) -> Self {
|
||||
let (w, h) = (finite(w), finite(h));
|
||||
let ss = w.min(h);
|
||||
let ls = w.max(h);
|
||||
let mut v = HashMap::new();
|
||||
let mut set = |k: &str, x: f64| {
|
||||
v.insert(k.to_string(), x);
|
||||
};
|
||||
set("w", w);
|
||||
set("h", h);
|
||||
set("l", 0.0);
|
||||
set("t", 0.0);
|
||||
set("r", w);
|
||||
set("b", h);
|
||||
set("hc", w / 2.0);
|
||||
set("vc", h / 2.0);
|
||||
set("ss", ss);
|
||||
set("ls", ls);
|
||||
for d in [2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0, 32.0] {
|
||||
set(&format!("wd{d}"), w / d);
|
||||
set(&format!("hd{d}"), h / d);
|
||||
set(&format!("ssd{d}"), ss / d);
|
||||
}
|
||||
set("cd2", 10_800_000.0);
|
||||
set("cd4", 5_400_000.0);
|
||||
set("cd8", 2_700_000.0);
|
||||
set("3cd4", 16_200_000.0);
|
||||
set("3cd8", 8_100_000.0);
|
||||
set("5cd8", 13_500_000.0);
|
||||
set("7cd8", 18_900_000.0);
|
||||
Guides { vars: v }
|
||||
}
|
||||
/// Bytes of the guide names held.
|
||||
fn name_bytes(&self) -> usize {
|
||||
self.vars.keys().map(String::len).sum()
|
||||
}
|
||||
pub fn get(&self, name: &str) -> f64 {
|
||||
let name = name.trim();
|
||||
if let Some(v) = self.vars.get(name) {
|
||||
return *v;
|
||||
}
|
||||
name.parse::<f64>().ok().map(finite).unwrap_or(0.0)
|
||||
}
|
||||
pub fn set(&mut self, name: &str, v: f64) {
|
||||
if self.vars.len() < 10_000 {
|
||||
self.vars.insert(name.to_string(), finite(v));
|
||||
}
|
||||
}
|
||||
/// Evaluate one formula (`*/ w 1 2`).
|
||||
pub fn eval(&self, fmla: &str) -> f64 {
|
||||
let mut it = fmla.split_whitespace();
|
||||
let op = it.next().unwrap_or("");
|
||||
let args: Vec<f64> = it.take(3).map(|a| self.get(a)).collect();
|
||||
let a = |i: usize| args.get(i).copied().unwrap_or(0.0);
|
||||
let div = |n: f64, d: f64| if d == 0.0 { 0.0 } else { n / d };
|
||||
let r = match op {
|
||||
"*/" => div(a(0) * a(1), a(2)),
|
||||
"+-" => a(0) + a(1) - a(2),
|
||||
"+/" => div(a(0) + a(1), a(2)),
|
||||
"?:" => {
|
||||
if a(0) > 0.0 {
|
||||
a(1)
|
||||
} else {
|
||||
a(2)
|
||||
}
|
||||
}
|
||||
"abs" => a(0).abs(),
|
||||
"at2" => to_ang(a(1).atan2(a(0))),
|
||||
"cat2" => a(0) * a(2).atan2(a(1)).cos(),
|
||||
"sat2" => a(0) * a(2).atan2(a(1)).sin(),
|
||||
"cos" => a(0) * to_rad(a(1)).cos(),
|
||||
"sin" => a(0) * to_rad(a(1)).sin(),
|
||||
"tan" => a(0) * to_rad(a(1)).tan(),
|
||||
"max" => a(0).max(a(1)),
|
||||
"min" => a(0).min(a(1)),
|
||||
"mod" => (a(0) * a(0) + a(1) * a(1) + a(2) * a(2)).sqrt(),
|
||||
"pin" => {
|
||||
if a(1) < a(0) {
|
||||
a(0)
|
||||
} else if a(1) > a(2) {
|
||||
a(2)
|
||||
} else {
|
||||
a(1)
|
||||
}
|
||||
}
|
||||
"sqrt" => a(0).max(0.0).sqrt(),
|
||||
"val" => a(0),
|
||||
_ => 0.0,
|
||||
};
|
||||
finite(r)
|
||||
}
|
||||
/// Evaluate a list of `a:gd` elements in order.
|
||||
pub fn eval_list(&mut self, list: Option<&El>) {
|
||||
let Some(list) = list else { return };
|
||||
for gd in list.children_named("gd").take(5000) {
|
||||
let (Some(name), Some(f)) = (gd.attr("name"), gd.attr("fmla")) else { continue };
|
||||
let v = self.eval(f);
|
||||
self.set(name, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn num(s: &mut String, v: f64) {
|
||||
let v = finite(v);
|
||||
let r = (v * 1000.0).round() / 1000.0;
|
||||
if r == r.trunc() {
|
||||
let _ = write!(s, "{}", r as i64);
|
||||
} else {
|
||||
let _ = write!(s, "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
fn pt(g: &Guides, e: &El) -> (f64, f64) {
|
||||
(g.get(e.attr("x").unwrap_or("0")), g.get(e.attr("y").unwrap_or("0")))
|
||||
}
|
||||
|
||||
/// Convert `a:custGeom` to custom paths. `w`/`h` is the shape size in EMU (used for guides and for
|
||||
/// paths that don't give their own coordinate space).
|
||||
pub fn read_cust_geom(cg: &El, w_emu: f64, h_emu: f64) -> Vec<CustomPath> {
|
||||
read_cust_geom_counting(cg, w_emu, h_emu).0
|
||||
}
|
||||
|
||||
/// [`read_cust_geom`], and how many paths were left out for lack of room in the guide caches
|
||||
/// (`(too many coordinate spaces, too many guide-name bytes)`); each cause is also logged once.
|
||||
fn read_cust_geom_counting(cg: &El, w_emu: f64, h_emu: f64) -> (Vec<CustomPath>, (usize, usize)) {
|
||||
let mut out = vec![];
|
||||
let mut dropped = (0usize, 0usize);
|
||||
let Some(pl) = cg.child("pathLst") else { return (out, dropped) };
|
||||
let mut spaces: HashMap<(u64, u64), Guides> = HashMap::new();
|
||||
let mut name_bytes = 0usize;
|
||||
let mut budget_full = false;
|
||||
// The cap on cached spaces saves guide evaluation: a geometry without guides has none to save.
|
||||
let guided = ["avLst", "gdLst"].iter().any(|n| cg.child(n).is_some_and(|l| l.elements().next().is_some()));
|
||||
for p in pl.children_named("path").take(1000) {
|
||||
let pw = p.f64("w").unwrap_or(0.0);
|
||||
let ph = p.f64("h").unwrap_or(0.0);
|
||||
// Guides are evaluated in the path's own space when it has one.
|
||||
let (gw, gh) = if pw > 0.0 || ph > 0.0 { (pw, ph) } else { (w_emu, h_emu) };
|
||||
// The guide lists are evaluated once per coordinate space, not once per path.
|
||||
let key = (gw.to_bits(), gh.to_bits());
|
||||
if !spaces.contains_key(&key) {
|
||||
if guided && (budget_full || spaces.len() >= MAX_SPACES) {
|
||||
if budget_full {
|
||||
dropped.1 += 1;
|
||||
} else {
|
||||
dropped.0 += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut g = Guides::new(gw, gh);
|
||||
g.eval_list(cg.child("avLst"));
|
||||
g.eval_list(cg.child("gdLst"));
|
||||
// The first space is always kept; later ones only while the cache stays within budget.
|
||||
let bytes = g.name_bytes();
|
||||
if guided && !spaces.is_empty() && name_bytes.saturating_add(bytes) > MAX_SPACE_NAME_BYTES {
|
||||
// Every space holds the same names, so no later space fits either.
|
||||
budget_full = true;
|
||||
dropped.1 += 1;
|
||||
continue;
|
||||
}
|
||||
name_bytes = name_bytes.saturating_add(bytes);
|
||||
spaces.insert(key, g);
|
||||
}
|
||||
let Some(g) = spaces.get(&key) else { continue };
|
||||
let mut d = String::new();
|
||||
let mut cur = (0.0, 0.0);
|
||||
let mut start = (0.0, 0.0);
|
||||
for c in p.elements().take(100_000) {
|
||||
match c.local() {
|
||||
"moveTo" => {
|
||||
if let Some(q) = c.child("pt") {
|
||||
cur = pt(g, q);
|
||||
start = cur;
|
||||
d.push_str("M ");
|
||||
num(&mut d, cur.0);
|
||||
d.push(' ');
|
||||
num(&mut d, cur.1);
|
||||
d.push(' ');
|
||||
}
|
||||
}
|
||||
"lnTo" => {
|
||||
if let Some(q) = c.child("pt") {
|
||||
cur = pt(g, q);
|
||||
d.push_str("L ");
|
||||
num(&mut d, cur.0);
|
||||
d.push(' ');
|
||||
num(&mut d, cur.1);
|
||||
d.push(' ');
|
||||
}
|
||||
}
|
||||
"cubicBezTo" => {
|
||||
let pts: Vec<(f64, f64)> = c.children_named("pt").map(|q| pt(g, q)).collect();
|
||||
if let [a, b, e] = pts.as_slice() {
|
||||
d.push_str("C ");
|
||||
for (x, y) in [a, b, e] {
|
||||
num(&mut d, *x);
|
||||
d.push(' ');
|
||||
num(&mut d, *y);
|
||||
d.push(' ');
|
||||
}
|
||||
cur = *e;
|
||||
}
|
||||
}
|
||||
"quadBezTo" => {
|
||||
let pts: Vec<(f64, f64)> = c.children_named("pt").map(|q| pt(g, q)).collect();
|
||||
if let [a, e] = pts.as_slice() {
|
||||
d.push_str("Q ");
|
||||
for (x, y) in [a, e] {
|
||||
num(&mut d, *x);
|
||||
d.push(' ');
|
||||
num(&mut d, *y);
|
||||
d.push(' ');
|
||||
}
|
||||
cur = *e;
|
||||
}
|
||||
}
|
||||
"arcTo" => {
|
||||
let wr = g.get(c.attr("wR").unwrap_or("0"));
|
||||
let hr = g.get(c.attr("hR").unwrap_or("0"));
|
||||
let st = g.get(c.attr("stAng").unwrap_or("0"));
|
||||
let sw = g.get(c.attr("swAng").unwrap_or("0"));
|
||||
cur = arc_to(&mut d, cur, wr, hr, st, sw);
|
||||
}
|
||||
"close" => {
|
||||
d.push_str("Z ");
|
||||
cur = start;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let fill = match p.attr("fill").unwrap_or("norm") {
|
||||
"none" => FillMode::None,
|
||||
"lighten" => FillMode::Lighten,
|
||||
"lightenLess" => FillMode::LightenLess,
|
||||
"darken" => FillMode::Darken,
|
||||
"darkenLess" => FillMode::DarkenLess,
|
||||
_ => FillMode::Norm,
|
||||
};
|
||||
let (ow, oh) = if pw > 0.0 || ph > 0.0 { (pw, ph) } else { (w_emu.max(1.0), h_emu.max(1.0)) };
|
||||
out.push(CustomPath { w: ow, h: oh, d: d.trim_end().to_string(), fill, stroke: p.bool("stroke").unwrap_or(true) });
|
||||
}
|
||||
if dropped.0 > 0 {
|
||||
log::warn!("pptx: a custom geometry uses more than {MAX_SPACES} distinct path coordinate spaces; {} later path(s) are not kept", dropped.0);
|
||||
}
|
||||
if dropped.1 > 0 {
|
||||
log::warn!(
|
||||
"pptx: a custom geometry's guide names pass {MAX_SPACE_NAME_BYTES} bytes across its coordinate spaces; {} later path(s) are not kept",
|
||||
dropped.1
|
||||
);
|
||||
}
|
||||
(out, dropped)
|
||||
}
|
||||
|
||||
/// Ellipse parametric angle for a visual angle `a` (radians).
|
||||
fn param(a: f64, wr: f64, hr: f64) -> f64 {
|
||||
(wr * a.sin()).atan2(hr * a.cos())
|
||||
}
|
||||
|
||||
/// Append an elliptical arc as cubic Béziers; returns the end point.
|
||||
fn arc_to(d: &mut String, cur: (f64, f64), wr: f64, hr: f64, st: f64, sw: f64) -> (f64, f64) {
|
||||
if wr.abs() < 1e-9 || hr.abs() < 1e-9 || sw == 0.0 {
|
||||
return cur;
|
||||
}
|
||||
let st_r = to_rad(st);
|
||||
let sw_r = to_rad(sw).clamp(-4.0 * PI, 4.0 * PI);
|
||||
let t0 = param(st_r, wr, hr);
|
||||
let mut t1 = param(st_r + sw_r, wr, hr);
|
||||
// Keep the sweep direction and size of the visual angle.
|
||||
let full = sw_r.abs() >= 2.0 * PI - 1e-9;
|
||||
if full {
|
||||
t1 = t0 + sw_r.signum() * 2.0 * PI;
|
||||
} else {
|
||||
while sw_r > 0.0 && t1 < t0 {
|
||||
t1 += 2.0 * PI;
|
||||
}
|
||||
while sw_r < 0.0 && t1 > t0 {
|
||||
t1 -= 2.0 * PI;
|
||||
}
|
||||
}
|
||||
let cx = cur.0 - wr * t0.cos();
|
||||
let cy = cur.1 - hr * t0.sin();
|
||||
let total = t1 - t0;
|
||||
let n = ((total.abs() / (PI / 2.0)).ceil() as usize).clamp(1, 16);
|
||||
let step = total / n as f64;
|
||||
let k = 4.0 / 3.0 * (step / 4.0).tan();
|
||||
let mut a = t0;
|
||||
let mut end = cur;
|
||||
for _ in 0..n {
|
||||
let b = a + step;
|
||||
let (ca, sa, cb, sb) = (a.cos(), a.sin(), b.cos(), b.sin());
|
||||
let p1 = (cx + wr * (ca - k * sa), cy + hr * (sa + k * ca));
|
||||
let p2 = (cx + wr * (cb + k * sb), cy + hr * (sb - k * cb));
|
||||
end = (cx + wr * cb, cy + hr * sb);
|
||||
d.push_str("C ");
|
||||
for (x, y) in [p1, p2, end] {
|
||||
num(d, x);
|
||||
d.push(' ');
|
||||
num(d, y);
|
||||
d.push(' ');
|
||||
}
|
||||
a = b;
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
/// Parse our path syntax into commands.
|
||||
pub use craft_drawingml::custgeom::parse_path;
|
||||
|
||||
/// Write custom paths as `a:custGeom`. Coordinates are integers in the file, so small path spaces
|
||||
/// are scaled up.
|
||||
pub fn write_cust_geom(w: &mut W, paths: &[CustomPath]) {
|
||||
w.open0("a:custGeom");
|
||||
w.empty0("a:avLst");
|
||||
w.empty0("a:gdLst");
|
||||
w.empty0("a:ahLst");
|
||||
w.empty0("a:cxnLst");
|
||||
w.empty("a:rect", A::new().a("l", "l").a("t", "t").a("r", "r").a("b", "b"));
|
||||
w.open0("a:pathLst");
|
||||
for p in paths {
|
||||
let (pw, ph) = (finite(p.w).abs(), finite(p.h).abs());
|
||||
let m = pw.max(ph);
|
||||
let k = if m > 0.0 && m < 20_000.0 { 100_000.0 / m } else { 1.0 };
|
||||
let r = |v: f64| (finite(v) * k).round().clamp(-2.0e9, 2.0e9) as i64;
|
||||
let fill = match p.fill {
|
||||
FillMode::Norm => None,
|
||||
FillMode::None => Some("none"),
|
||||
FillMode::Lighten => Some("lighten"),
|
||||
FillMode::LightenLess => Some("lightenLess"),
|
||||
FillMode::Darken => Some("darken"),
|
||||
FillMode::DarkenLess => Some("darkenLess"),
|
||||
};
|
||||
let a = A::new().a("w", r(pw).max(0)).a("h", r(ph).max(0)).o("fill", fill).o("stroke", (!p.stroke).then_some("0"));
|
||||
w.open("a:path", a);
|
||||
for (c, v) in parse_path(&p.d) {
|
||||
let pts: Vec<(i64, i64)> = v
|
||||
.chunks(2)
|
||||
.filter_map(|c| match c {
|
||||
[x, y] => Some((r(*x), r(*y))),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let tag = match c {
|
||||
'M' => "a:moveTo",
|
||||
'L' => "a:lnTo",
|
||||
'C' => "a:cubicBezTo",
|
||||
'Q' => "a:quadBezTo",
|
||||
'Z' => {
|
||||
w.empty0("a:close");
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
w.open0(tag);
|
||||
for (x, y) in pts {
|
||||
w.empty("a:pt", A::new().a("x", x).a("y", y));
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
w.close("a:path");
|
||||
}
|
||||
w.close("a:pathLst");
|
||||
w.close("a:custGeom");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::xml::parse;
|
||||
|
||||
#[test]
|
||||
fn formulas() {
|
||||
let mut g = Guides::new(1000.0, 500.0);
|
||||
assert_eq!(g.eval("*/ w 1 2"), 500.0);
|
||||
assert_eq!(g.eval("+- w h 100"), 1400.0);
|
||||
assert_eq!(g.eval("+/ w h 3"), 500.0);
|
||||
assert_eq!(g.eval("?: -1 5 7"), 7.0);
|
||||
assert_eq!(g.eval("?: 1 5 7"), 5.0);
|
||||
assert_eq!(g.eval("abs -42"), 42.0);
|
||||
assert_eq!(g.eval("max 3 9"), 9.0);
|
||||
assert_eq!(g.eval("min 3 9"), 3.0);
|
||||
assert_eq!(g.eval("mod 3 4 0"), 5.0);
|
||||
assert_eq!(g.eval("pin 0 150 100"), 100.0);
|
||||
assert_eq!(g.eval("pin 0 -5 100"), 0.0);
|
||||
assert_eq!(g.eval("sqrt 16"), 4.0);
|
||||
assert_eq!(g.eval("val ss"), 500.0);
|
||||
assert!((g.eval("at2 1 1") - 2_700_000.0).abs() < 1e-6);
|
||||
assert!((g.eval("cos 100 5400000")).abs() < 1e-9);
|
||||
assert!((g.eval("sin 100 5400000") - 100.0).abs() < 1e-9);
|
||||
assert!((g.eval("tan 100 2700000") - 100.0).abs() < 1e-6);
|
||||
assert!((g.eval("cat2 10 1 0") - 10.0).abs() < 1e-9);
|
||||
assert!((g.eval("sat2 10 0 1") - 10.0).abs() < 1e-9);
|
||||
assert_eq!(g.eval("*/ 1 1 0"), 0.0, "division by zero is 0");
|
||||
assert_eq!(g.eval("bogus 1 2"), 0.0);
|
||||
assert_eq!(g.eval(""), 0.0);
|
||||
g.set("x1", 7.0);
|
||||
assert_eq!(g.eval("+- x1 0 2"), 5.0);
|
||||
assert_eq!(g.get("hc"), 500.0);
|
||||
assert_eq!(g.get("cd4"), 5_400_000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custgeom_with_guides_and_arc() {
|
||||
let x = br#"<a:custGeom xmlns:a="x"><a:avLst/><a:gdLst><a:gd name="mid" fmla="*/ w 1 2"/></a:gdLst>
|
||||
<a:pathLst><a:path w="200" h="100"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="mid" y="h"/></a:lnTo>
|
||||
<a:arcTo wR="50" hR="50" stAng="0" swAng="5400000"/><a:close/></a:path>
|
||||
<a:path w="10" h="10" fill="none" stroke="0"><a:moveTo><a:pt x="1" y="1"/></a:moveTo><a:quadBezTo><a:pt x="2" y="2"/><a:pt x="3" y="1"/></a:quadBezTo></a:path></a:pathLst></a:custGeom>"#;
|
||||
let d = parse(x).unwrap();
|
||||
let paths = read_cust_geom(&d.root, 1000.0, 1000.0);
|
||||
assert_eq!(paths.len(), 2);
|
||||
assert!(paths[0].d.starts_with("M 0 0 L 100 100 C"), "{}", paths[0].d);
|
||||
assert!(paths[0].d.ends_with('Z'));
|
||||
// The quarter arc from (100,100) with centre (50,100) ends at (50,150).
|
||||
assert!(paths[0].d.contains("50 150"), "{}", paths[0].d);
|
||||
assert_eq!(paths[1].fill, FillMode::None);
|
||||
assert!(!paths[1].stroke);
|
||||
assert_eq!(paths[1].d, "M 1 1 Q 2 2 3 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_share_guides_and_distinct_spaces_are_capped() {
|
||||
let path = |w: usize| format!(r#"<a:path w="{w}" h="10"><a:moveTo><a:pt x="mid" y="1"/></a:moveTo></a:path>"#);
|
||||
let paths: String = (1..=40).map(|i| path(10 * i)).collect();
|
||||
let x = format!(
|
||||
r#"<a:custGeom xmlns:a="x"><a:gdLst><a:gd name="mid" fmla="*/ w 1 2"/></a:gdLst><a:pathLst>{paths}{}</a:pathLst></a:custGeom>"#,
|
||||
path(10)
|
||||
);
|
||||
let d = parse(x.as_bytes()).unwrap();
|
||||
let (out, dropped) = read_cust_geom_counting(&d.root, 1.0, 1.0);
|
||||
assert_eq!(out.len(), MAX_SPACES + 1, "16 spaces plus the repeat of the first");
|
||||
assert_eq!(dropped, (40 - MAX_SPACES, 0), "the paths of later spaces are counted, to be warned about");
|
||||
assert!(out[0].d.starts_with("M 5 1"), "{}", out[0].d);
|
||||
assert!(out[MAX_SPACES].d.starts_with("M 5 1"), "{}", out[MAX_SPACES].d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guide_name_bytes_across_spaces_are_budgeted() {
|
||||
let name = "n".repeat(3 << 20);
|
||||
let path = |w: usize| format!(r#"<a:path w="{w}" h="10"><a:moveTo><a:pt x="{name}" y="1"/></a:moveTo></a:path>"#);
|
||||
let x = format!(
|
||||
r#"<a:custGeom xmlns:a="x"><a:gdLst><a:gd name="{name}" fmla="*/ w 1 2"/></a:gdLst><a:pathLst>{}{}{}</a:pathLst></a:custGeom>"#,
|
||||
path(10),
|
||||
path(20),
|
||||
path(10)
|
||||
);
|
||||
let d = parse(x.as_bytes()).unwrap();
|
||||
let (out, dropped) = read_cust_geom_counting(&d.root, 1.0, 1.0);
|
||||
assert_eq!(out.len(), 2, "the second 3 MiB space is over budget and left out; the first space's repeat stays");
|
||||
assert_eq!(dropped, (0, 1), "the path left out is counted, to be warned about");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guide_free_geometries_are_not_capped_by_space() {
|
||||
let paths: String = (1..=40).map(|i| format!(r#"<a:path w="{}" h="10"><a:moveTo><a:pt x="1" y="1"/></a:moveTo></a:path>"#, 10 * i)).collect();
|
||||
let x = format!(r#"<a:custGeom xmlns:a="x"><a:avLst/><a:gdLst/><a:pathLst>{paths}</a:pathLst></a:custGeom>"#);
|
||||
let d = parse(x.as_bytes()).unwrap();
|
||||
assert_eq!(read_cust_geom(&d.root, 1.0, 1.0).len(), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_then_read_path() {
|
||||
let p = CustomPath { w: 100.0, h: 50.0, d: "M 0 0 L 100 0 C 100 10 90 50 50 50 Q 0 50 0 0 Z".into(), fill: FillMode::Norm, stroke: true };
|
||||
let mut w = W::frag();
|
||||
write_cust_geom(&mut w, std::slice::from_ref(&p));
|
||||
let d = parse(w.s.as_bytes()).unwrap();
|
||||
let back = read_cust_geom(&d.root, 1.0, 1.0);
|
||||
assert_eq!(back.len(), 1);
|
||||
// Scaled by 1000 (100 → 100000).
|
||||
assert_eq!(back[0].w, 100_000.0);
|
||||
assert_eq!(back[0].d, "M 0 0 L 100000 0 C 100000 10000 90000 50000 50000 50000 Q 0 50000 0 0 Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_path_uppercase_exponent() {
|
||||
assert_eq!(parse_path("M 1E-5 2 L 3 4"), vec![('M', vec![1e-5, 2.0]), ('L', vec![3.0, 4.0])]);
|
||||
assert_eq!(parse_path("M 1.5E3 2"), vec![('M', vec![1500.0, 2.0])]);
|
||||
assert_eq!(parse_path("M 1e-5 2"), vec![('M', vec![1e-5, 2.0])]);
|
||||
// An 'E' right after a number with no exponent digits is the end command.
|
||||
assert_eq!(parse_path("M 0 0E"), vec![('M', vec![0.0, 0.0]), ('E', vec![])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_path_tokens() {
|
||||
let v = parse_path("M0,0 L10-5 Z");
|
||||
assert_eq!(v.len(), 3);
|
||||
assert_eq!(v[1], ('L', vec![10.0, -5.0]));
|
||||
assert!(parse_path("garbage ### C 1").is_empty() || parse_path("garbage").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_path_tests {
|
||||
use super::parse_path;
|
||||
|
||||
#[test]
|
||||
fn shared_path_tokens_preserve_exponents_repeats_and_dropped_tails() {
|
||||
assert_eq!(
|
||||
parse_path("M1E2 -3E-1 4 5 L6-7 Q8 9 10 11 Z"),
|
||||
vec![('M', vec![100.0, -0.3]), ('L', vec![4.0, 5.0]), ('L', vec![6.0, -7.0]), ('Q', vec![8.0, 9.0, 10.0, 11.0]), ('Z', vec![]),]
|
||||
);
|
||||
assert_eq!(parse_path("M0 0 L1"), vec![('M', vec![0.0, 0.0])]);
|
||||
assert_eq!(parse_path("MNaN 0 1 2"), vec![('M', vec![0.0, 1.0])]);
|
||||
}
|
||||
}
|
||||
@@ -1,910 +0,0 @@
|
||||
//! SmartArt (DrawingML diagrams): the outline ⇄ the data model, and the layout, quick style and
|
||||
//! colour definitions DeckCraft writes for its own layouts.
|
||||
//!
|
||||
//! A diagram's data part holds its points (`dgm:pt`: the document, one per node, and the
|
||||
//! transitions PowerPoint pairs with each link) and its links (`dgm:cxn` of type `parOf`, parent →
|
||||
//! child, ordered by `srcOrd`). The outline is that tree flattened depth first.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use deckcraft_model::{Diagram, DiagramNode};
|
||||
|
||||
use crate::xml::{A, El, W};
|
||||
|
||||
pub const NS_DGM: &str = "http://schemas.openxmlformats.org/drawingml/2006/diagram";
|
||||
pub const NS_DSP: &str = "http://schemas.microsoft.com/office/drawing/2008/diagram";
|
||||
pub const CT_DATA: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml";
|
||||
pub const CT_LAYOUT: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml";
|
||||
pub const CT_STYLE: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml";
|
||||
pub const CT_COLORS: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml";
|
||||
pub const CT_DRAWING: &str = "application/vnd.ms-office.drawingml.diagramDrawing+xml";
|
||||
pub const RT_DRAWING: &str = "http://schemas.microsoft.com/office/2007/relationships/diagramDrawing";
|
||||
const QS_BASE: &str = "urn:microsoft.com/office/officeart/2005/8/quickstyle/";
|
||||
const CS_BASE: &str = "urn:microsoft.com/office/officeart/2005/8/colors/";
|
||||
|
||||
/// PowerPoint's quick style for a SmartArt Style.
|
||||
pub fn qs_id(style: &str) -> String {
|
||||
let s = match style {
|
||||
"subtle" => "simple3",
|
||||
"intense" => "simple5",
|
||||
"outline" => "simple4",
|
||||
"polished" => "3d1",
|
||||
"inset" => "3d2",
|
||||
"cartoon" => "3d3",
|
||||
"powder" => "3d4",
|
||||
"brick" => "3d5",
|
||||
_ => "simple1",
|
||||
};
|
||||
format!("{QS_BASE}{s}")
|
||||
}
|
||||
|
||||
/// The SmartArt Style closest to a quick style id.
|
||||
pub fn style_for(qs: &str) -> &'static str {
|
||||
match qs.rsplit('/').next().unwrap_or("") {
|
||||
"simple1" | "" => "",
|
||||
"simple4" => "outline",
|
||||
"3d1" => "polished",
|
||||
"3d2" => "inset",
|
||||
"3d3" => "cartoon",
|
||||
"3d4" => "powder",
|
||||
"3d5" => "brick",
|
||||
"simple2" | "simple3" => "subtle",
|
||||
_ => "intense",
|
||||
}
|
||||
}
|
||||
|
||||
/// PowerPoint's colour definition for Change Colors.
|
||||
pub fn cs_id(colors: &str) -> String {
|
||||
if let Some(a @ 2..=5) = colors.strip_prefix("range").and_then(|r| r.get(..1)).and_then(|n| n.parse::<u8>().ok()) {
|
||||
return format!("{CS_BASE}colorful{a}");
|
||||
}
|
||||
let grad = colors.ends_with("Grad");
|
||||
match colors.strip_prefix("accent").and_then(|r| r.get(..1)).and_then(|n| n.parse::<u8>().ok()) {
|
||||
Some(n @ 1..=6) => format!("{CS_BASE}accent{n}_{}", if grad { 3 } else { 2 }),
|
||||
_ => format!("{CS_BASE}colorful1"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The accents a Change Colors choice fills shapes with, in turn.
|
||||
fn fill_accents(colors: &str) -> Vec<String> {
|
||||
if let Some(a @ 2..=5) = colors.strip_prefix("range").and_then(|r| r.get(..1)).and_then(|n| n.parse::<u8>().ok()) {
|
||||
return vec![format!("accent{a}"), format!("accent{}", a + 1)];
|
||||
}
|
||||
match colors.strip_prefix("accent").and_then(|r| r.get(..1)).and_then(|n| n.parse::<u8>().ok()) {
|
||||
Some(n @ 1..=6) => vec![format!("accent{n}")],
|
||||
_ => (1..=6).map(|k| format!("accent{k}")).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change Colors from a colour definition id: `accentN_…` keeps accent N, anything else is colourful.
|
||||
pub fn colors_for(cs: &str) -> String {
|
||||
let last = cs.rsplit('/').next().unwrap_or("");
|
||||
if let Some(a @ 2..=5) = last.strip_prefix("colorful").and_then(|n| n.parse::<u8>().ok()) {
|
||||
return format!("range{a}{}", a + 1);
|
||||
}
|
||||
let mut parts = last.strip_prefix("accent").unwrap_or("").split('_');
|
||||
match (parts.next().and_then(|n| n.parse::<u8>().ok()), parts.next()) {
|
||||
(Some(n @ 1..=6), Some("3" | "4" | "5")) => format!("accent{n}Grad"),
|
||||
(Some(n @ 1..=6), _) => format!("accent{n}"),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
/// Most nodes read from one diagram.
|
||||
const MAX_NODES: usize = 2000;
|
||||
|
||||
/// PowerPoint's built-in layout DeckCraft's layout `kind` is written as.
|
||||
pub fn layout_id(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"blockList" => "urn:microsoft.com/office/officeart/2005/8/layout/default",
|
||||
"hBulletList" => "urn:microsoft.com/office/officeart/2005/8/layout/hList1",
|
||||
"process" => "urn:microsoft.com/office/officeart/2005/8/layout/process1",
|
||||
"chevron" => "urn:microsoft.com/office/officeart/2005/8/layout/chevron1",
|
||||
"verticalProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/process2",
|
||||
"stepUp" => "urn:microsoft.com/office/officeart/2009/3/layout/StepUpProcess",
|
||||
"cycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle2",
|
||||
"blockCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle5",
|
||||
"radial" => "urn:microsoft.com/office/officeart/2005/8/layout/radial1",
|
||||
"hierarchy" => "urn:microsoft.com/office/officeart/2005/8/layout/hierarchy1",
|
||||
"pyramid" => "urn:microsoft.com/office/officeart/2005/8/layout/pyramid1",
|
||||
"invertedPyramid" => "urn:microsoft.com/office/officeart/2005/8/layout/pyramid3",
|
||||
"matrix" => "urn:microsoft.com/office/officeart/2005/8/layout/matrix3",
|
||||
"titledMatrix" => "urn:microsoft.com/office/officeart/2005/8/layout/matrix1",
|
||||
"pictureList" => "urn:microsoft.com/office/officeart/2005/8/layout/vList4",
|
||||
"pictureCaption" => "urn:microsoft.com/office/officeart/2005/8/layout/pList1",
|
||||
"pictureProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/hProcess10",
|
||||
"pictureHList" => "urn:microsoft.com/office/officeart/2005/8/layout/pList2",
|
||||
"timeline" => "urn:microsoft.com/office/officeart/2005/8/layout/hProcess11",
|
||||
"venn" => "urn:microsoft.com/office/officeart/2005/8/layout/venn1",
|
||||
"target" => "urn:microsoft.com/office/officeart/2005/8/layout/target1",
|
||||
"textCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle1",
|
||||
"continuousCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle3",
|
||||
"horizontalHierarchy" => "urn:microsoft.com/office/officeart/2005/8/layout/hierarchy2",
|
||||
"gridMatrix" => "urn:microsoft.com/office/officeart/2005/8/layout/matrix2",
|
||||
"gear" => "urn:microsoft.com/office/officeart/2005/8/layout/gear1",
|
||||
"funnel" => "urn:microsoft.com/office/officeart/2005/8/layout/funnel1",
|
||||
"segmentedCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle8",
|
||||
"multidirectionalCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle7",
|
||||
"orgChart" => "urn:microsoft.com/office/officeart/2005/8/layout/orgChart1",
|
||||
"halfCircleOrgChart" => "urn:microsoft.com/office/officeart/2008/layout/HalfCircleOrganizationChart",
|
||||
"nameTitleOrgChart" => "urn:microsoft.com/office/officeart/2008/layout/NameandTitleOrganizationalChart",
|
||||
"verticalBoxList" => "urn:microsoft.com/office/officeart/2005/8/layout/list1",
|
||||
"trapezoidList" => "urn:microsoft.com/office/officeart/2005/8/layout/hList6",
|
||||
"tableList" => "urn:microsoft.com/office/officeart/2005/8/layout/hList3",
|
||||
"accentProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/process3",
|
||||
"continuousBlockProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/hProcess9",
|
||||
"bendingProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/process5",
|
||||
"linearVenn" => "urn:microsoft.com/office/officeart/2005/8/layout/venn3",
|
||||
"stackedVenn" => "urn:microsoft.com/office/officeart/2005/8/layout/venn2",
|
||||
"nestedTarget" => "urn:microsoft.com/office/officeart/2005/8/layout/target2",
|
||||
"cycleMatrix" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle4",
|
||||
"segmentedPyramid" => "urn:microsoft.com/office/officeart/2005/8/layout/pyramid4",
|
||||
"pie" => "urn:microsoft.com/office/officeart/2005/8/layout/chart3",
|
||||
_ => "urn:microsoft.com/office/officeart/2005/8/layout/vList2",
|
||||
}
|
||||
}
|
||||
|
||||
/// The DeckCraft layout closest to a PowerPoint layout (by its id and category).
|
||||
pub fn kind_for(layout_id: &str, category: &str) -> &'static str {
|
||||
let last = layout_id.rsplit('/').next().unwrap_or("").to_ascii_lowercase();
|
||||
// DeckCraft before Picture Accent Process got its own id wrote it as pList2 (Horizontal
|
||||
// Picture List) with its own layout part in the process category; PowerPoint's pList2 is a list.
|
||||
if last == "plist2" && category.eq_ignore_ascii_case("process") {
|
||||
return "pictureProcess";
|
||||
}
|
||||
// Exact ids first: the layouts DeckCraft writes, and their closest siblings.
|
||||
for k in [
|
||||
"blockList",
|
||||
"hBulletList",
|
||||
"process",
|
||||
"chevron",
|
||||
"verticalProcess",
|
||||
"stepUp",
|
||||
"cycle",
|
||||
"blockCycle",
|
||||
"radial",
|
||||
"hierarchy",
|
||||
"pyramid",
|
||||
"invertedPyramid",
|
||||
"matrix",
|
||||
"titledMatrix",
|
||||
"pictureList",
|
||||
"pictureCaption",
|
||||
"pictureProcess",
|
||||
"pictureHList",
|
||||
"timeline",
|
||||
"venn",
|
||||
"target",
|
||||
"textCycle",
|
||||
"continuousCycle",
|
||||
"horizontalHierarchy",
|
||||
"gridMatrix",
|
||||
"gear",
|
||||
"funnel",
|
||||
"segmentedCycle",
|
||||
"multidirectionalCycle",
|
||||
"orgChart",
|
||||
"halfCircleOrgChart",
|
||||
"nameTitleOrgChart",
|
||||
"verticalBoxList",
|
||||
"trapezoidList",
|
||||
"tableList",
|
||||
"accentProcess",
|
||||
"continuousBlockProcess",
|
||||
"bendingProcess",
|
||||
"linearVenn",
|
||||
"stackedVenn",
|
||||
"nestedTarget",
|
||||
"cycleMatrix",
|
||||
"segmentedPyramid",
|
||||
"pie",
|
||||
"list",
|
||||
] {
|
||||
if layout_id == layout_id_of(k) {
|
||||
return k;
|
||||
}
|
||||
}
|
||||
let s = format!("{last} {}", category.to_ascii_lowercase());
|
||||
if s.contains("gear") {
|
||||
"gear"
|
||||
} else if s.contains("funnel") {
|
||||
"funnel"
|
||||
} else if s.contains("venn") {
|
||||
"venn"
|
||||
} else if s.contains("target") {
|
||||
"target"
|
||||
} else if s.contains("timeline") {
|
||||
"timeline"
|
||||
} else if s.contains("nameandtitle") {
|
||||
"nameTitleOrgChart"
|
||||
} else if s.contains("orgchart") || s.contains("organizationchart") || s.contains("organizationalchart") {
|
||||
"orgChart"
|
||||
} else if s.contains("hierarchy") {
|
||||
"hierarchy"
|
||||
} else if s.contains("radial") {
|
||||
"radial"
|
||||
} else if s.contains("cycle") {
|
||||
"cycle"
|
||||
} else if s.contains("pyramid") {
|
||||
"pyramid"
|
||||
} else if s.contains("matrix") {
|
||||
"matrix"
|
||||
} else if s.contains("chevron") {
|
||||
"chevron"
|
||||
} else if s.contains("process") || s.contains("arrow") {
|
||||
"process"
|
||||
} else if last == "default" {
|
||||
"blockList"
|
||||
} else if last.starts_with("hlist") {
|
||||
"hBulletList"
|
||||
} else {
|
||||
"list"
|
||||
}
|
||||
}
|
||||
|
||||
fn layout_id_of(kind: &str) -> &'static str {
|
||||
layout_id(kind)
|
||||
}
|
||||
|
||||
fn category(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"process"
|
||||
| "chevron"
|
||||
| "verticalProcess"
|
||||
| "stepUp"
|
||||
| "pictureProcess"
|
||||
| "timeline"
|
||||
| "gear"
|
||||
| "funnel"
|
||||
| "accentProcess"
|
||||
| "continuousBlockProcess"
|
||||
| "bendingProcess" => "process",
|
||||
"venn" | "target" | "linearVenn" | "stackedVenn" | "nestedTarget" => "relationship",
|
||||
"cycle" | "blockCycle" | "radial" | "textCycle" | "continuousCycle" | "segmentedCycle" | "multidirectionalCycle" | "cycleMatrix" | "pie" => {
|
||||
"cycle"
|
||||
}
|
||||
"hierarchy" | "horizontalHierarchy" | "orgChart" | "halfCircleOrgChart" | "nameTitleOrgChart" => "hierarchy",
|
||||
"pyramid" | "invertedPyramid" | "segmentedPyramid" => "pyramid",
|
||||
"matrix" | "titledMatrix" | "gridMatrix" => "matrix",
|
||||
_ => "list",
|
||||
}
|
||||
}
|
||||
|
||||
/// A model id, stable for a given diagram (`seed`) and point number.
|
||||
fn guid(seed: u32, n: usize) -> String {
|
||||
format!("{{{seed:08X}-D1A6-4C0A-9E5B-{n:012X}}}")
|
||||
}
|
||||
|
||||
fn text(w: &mut W, t: &str) {
|
||||
w.open0("dgm:t");
|
||||
w.empty0("a:bodyPr");
|
||||
w.empty0("a:lstStyle");
|
||||
w.open0("a:p");
|
||||
if t.is_empty() {
|
||||
w.empty("a:endParaRPr", A::new().a("lang", "en-US"));
|
||||
} else {
|
||||
w.open0("a:r");
|
||||
w.empty("a:rPr", A::new().a("lang", "en-US"));
|
||||
w.elt("a:t", t);
|
||||
w.close("a:r");
|
||||
}
|
||||
w.close("a:p");
|
||||
w.close("dgm:t");
|
||||
}
|
||||
|
||||
/// `ppt/diagrams/dataN.xml` for the outline. `drawing_rel` is the slide's relationship id of the
|
||||
/// cached drawing; `pics` the data part's relationship ids of node pictures, by node index.
|
||||
pub fn data_xml(d: &Diagram, seed: u32, drawing_rel: &str, pics: &[(usize, String)]) -> Vec<u8> {
|
||||
let lo = if d.layout_id.is_empty() { layout_id(&d.kind).to_string() } else { d.layout_id.clone() };
|
||||
let mut w = W::new();
|
||||
w.open("dgm:dataModel", A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("xmlns:r", crate::opc::NS_R));
|
||||
w.open0("dgm:ptLst");
|
||||
let doc = guid(seed, 0);
|
||||
w.open("dgm:pt", A::new().a("modelId", &doc).a("type", "doc"));
|
||||
w.empty(
|
||||
"dgm:prSet",
|
||||
A::new()
|
||||
.a("loTypeId", &lo)
|
||||
.a("loCatId", category(&d.kind))
|
||||
.a("qsTypeId", qs_id(&d.style))
|
||||
.a("qsCatId", "simple")
|
||||
.a("csTypeId", cs_id(&d.colors))
|
||||
.a("csCatId", if d.colors.starts_with("accent") { d.colors.as_str() } else { "colorful" })
|
||||
.a("phldr", "1"),
|
||||
);
|
||||
w.empty0("dgm:spPr");
|
||||
text(&mut w, "");
|
||||
w.close("dgm:pt");
|
||||
// Node k: model id 1 + 3k; its link's parent and sibling transitions 2 + 3k and 3 + 3k.
|
||||
let node = |k: usize| guid(seed, 1 + 3 * k);
|
||||
for (k, n) in d.nodes.iter().enumerate() {
|
||||
let mut a = A::new().a("modelId", node(k));
|
||||
if n.assistant {
|
||||
a = a.a("type", "asst");
|
||||
}
|
||||
w.open("dgm:pt", a);
|
||||
w.empty("dgm:prSet", A::new().a("phldrT", "[Text]"));
|
||||
w.empty0("dgm:spPr");
|
||||
text(&mut w, &n.text);
|
||||
w.close("dgm:pt");
|
||||
let cxn = guid(seed, 0x10_0000 + k);
|
||||
for (i, ty) in [(2, "parTrans"), (3, "sibTrans")] {
|
||||
w.open("dgm:pt", A::new().a("modelId", guid(seed, i + 3 * k)).a("type", ty).a("cxnId", &cxn));
|
||||
w.empty0("dgm:prSet");
|
||||
w.empty0("dgm:spPr");
|
||||
text(&mut w, "");
|
||||
w.close("dgm:pt");
|
||||
}
|
||||
}
|
||||
// A node's picture sits on the presentation point of its picture placeholder, as PowerPoint
|
||||
// stores it (`presAssocID` names the node, the blip is a relationship of the data part).
|
||||
// Name and Title: a node's title is the text of its title box's presentation point.
|
||||
for (k, n) in d.nodes.iter().enumerate() {
|
||||
if n.title.is_empty() {
|
||||
continue;
|
||||
}
|
||||
w.open("dgm:pt", A::new().a("modelId", guid(seed, 0x30_0000 + k)).a("type", "pres"));
|
||||
w.empty("dgm:prSet", A::new().a("presAssocID", node(k)).a("presName", "titleText1").a("presStyleLbl", "fgAcc1").a("custT", "1"));
|
||||
w.empty0("dgm:spPr");
|
||||
text(&mut w, &n.title);
|
||||
w.close("dgm:pt");
|
||||
}
|
||||
for (k, rid) in pics {
|
||||
if *k >= d.nodes.len() {
|
||||
continue;
|
||||
}
|
||||
w.open("dgm:pt", A::new().a("modelId", guid(seed, 0x20_0000 + k)).a("type", "pres"));
|
||||
w.empty("dgm:prSet", A::new().a("presAssocID", node(*k)).a("presName", "Image").a("presStyleLbl", "fgImgPlace1"));
|
||||
w.open0("dgm:spPr");
|
||||
w.open0("a:blipFill");
|
||||
w.empty("a:blip", A::new().a("r:embed", rid.as_str()));
|
||||
w.open0("a:stretch");
|
||||
w.empty0("a:fillRect");
|
||||
w.close("a:stretch");
|
||||
w.close("a:blipFill");
|
||||
w.close("dgm:spPr");
|
||||
w.close("dgm:pt");
|
||||
}
|
||||
w.close("dgm:ptLst");
|
||||
w.open0("dgm:cxnLst");
|
||||
let mut stack: Vec<(u8, String)> = vec![];
|
||||
let mut ords: HashMap<String, usize> = HashMap::new();
|
||||
for (k, n) in d.nodes.iter().enumerate() {
|
||||
while stack.last().is_some_and(|(l, _)| *l >= n.level) {
|
||||
stack.pop();
|
||||
}
|
||||
let parent = stack.last().map(|(_, id)| id.clone()).unwrap_or_else(|| doc.clone());
|
||||
let ord = ords.entry(parent.clone()).or_insert(0);
|
||||
w.empty(
|
||||
"dgm:cxn",
|
||||
A::new()
|
||||
.a("modelId", guid(seed, 0x10_0000 + k))
|
||||
.a("srcId", &parent)
|
||||
.a("destId", node(k))
|
||||
.a("srcOrd", *ord)
|
||||
.a("destOrd", 0)
|
||||
.a("parTransId", guid(seed, 2 + 3 * k))
|
||||
.a("sibTransId", guid(seed, 3 + 3 * k)),
|
||||
);
|
||||
*ord += 1;
|
||||
stack.push((n.level, node(k)));
|
||||
}
|
||||
w.close("dgm:cxnLst");
|
||||
w.empty0("dgm:bg");
|
||||
w.empty0("dgm:whole");
|
||||
w.open0("dgm:extLst");
|
||||
w.open("a:ext", A::new().a("uri", "http://schemas.microsoft.com/office/drawing/2008/diagram"));
|
||||
w.empty(
|
||||
"dsp:dataModelExt",
|
||||
A::new().a("xmlns:dsp", NS_DSP).a("relId", drawing_rel).a("minVer", "http://schemas.openxmlformats.org/drawingml/2006/diagram"),
|
||||
);
|
||||
w.close("a:ext");
|
||||
w.close("dgm:extLst");
|
||||
w.close("dgm:dataModel");
|
||||
w.finish()
|
||||
}
|
||||
|
||||
/// The outline of a data part: the `parOf` tree under the document point, depth first, or the data points in `ptLst` order when no `parOf` connections exist.
|
||||
pub fn outline(data: &El) -> Vec<DiagramNode> {
|
||||
outline_ids(data).into_iter().map(|(_, n)| n).collect()
|
||||
}
|
||||
|
||||
/// The relationship ids (of the data part) of node pictures, by node index in [`outline`]: the
|
||||
/// blip fill of a presentation point associated with the node.
|
||||
pub fn node_pictures(data: &El) -> Vec<(usize, String)> {
|
||||
let ids: HashMap<String, usize> = outline_ids(data).into_iter().enumerate().map(|(k, (id, _))| (id, k)).collect();
|
||||
let Some(pts) = data.child("ptLst") else { return vec![] };
|
||||
let mut out: Vec<(usize, String)> = vec![];
|
||||
for pt in pts.children_named("pt").take(MAX_NODES * 8) {
|
||||
if pt.attr("type") != Some("pres") {
|
||||
continue;
|
||||
}
|
||||
let Some(k) = pt.child("prSet").and_then(|p| p.attr("presAssocID")).and_then(|a| ids.get(a)) else { continue };
|
||||
let Some(rid) = pt.child("spPr").and_then(|s| s.child("blipFill")).and_then(|b| b.child("blip")).and_then(|b| b.attr("r:embed")) else {
|
||||
continue;
|
||||
};
|
||||
if !out.iter().any(|(j, _)| j == k) {
|
||||
out.push((*k, rid.to_string()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Extracts diagram outline `(modelId, DiagramNode)` pairs in tree order from a `dgm:dataModel` element.
|
||||
fn outline_ids(data: &El) -> Vec<(String, DiagramNode)> {
|
||||
let Some(pts) = data.child("ptLst") else { return vec![] };
|
||||
let mut texts: HashMap<&str, String> = HashMap::new();
|
||||
let mut assistants: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
let mut titles: HashMap<&str, String> = HashMap::new();
|
||||
let mut pt_order: Vec<&str> = Vec::new();
|
||||
let mut doc: Option<&str> = None;
|
||||
for pt in pts.children_named("pt").take(MAX_NODES * 4) {
|
||||
let Some(id) = pt.attr("modelId") else { continue };
|
||||
match pt.attr("type").unwrap_or("node") {
|
||||
"doc" => doc = doc.or(Some(id)),
|
||||
ty @ ("node" | "asst") => {
|
||||
let t = pt.child("t").map(paragraphs).unwrap_or_default();
|
||||
texts.insert(id, t);
|
||||
pt_order.push(id);
|
||||
if ty == "asst" {
|
||||
assistants.insert(id);
|
||||
}
|
||||
}
|
||||
"pres" => {
|
||||
// Name and Title: the title box's own text, on its presentation point.
|
||||
let pr = pt.child("prSet");
|
||||
if pr.and_then(|p| p.attr("presName")).is_some_and(|n| n.starts_with("titleText"))
|
||||
&& let Some(node) = pr.and_then(|p| p.attr("presAssocID"))
|
||||
&& let Some(t) = pt.child("t").map(paragraphs).filter(|t| !t.is_empty())
|
||||
{
|
||||
titles.insert(node, t);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut kids: HashMap<&str, Vec<(i64, &str)>> = HashMap::new();
|
||||
if let Some(cx) = data.child("cxnLst") {
|
||||
for c in cx.children_named("cxn").take(MAX_NODES * 4) {
|
||||
if c.attr("type").unwrap_or("parOf") != "parOf" {
|
||||
continue;
|
||||
}
|
||||
let (Some(src), Some(dst)) = (c.attr("srcId"), c.attr("destId")) else { continue };
|
||||
if texts.contains_key(dst) {
|
||||
kids.entry(src).or_default().push((c.i64("srcOrd").unwrap_or(0), dst));
|
||||
}
|
||||
}
|
||||
}
|
||||
for v in kids.values_mut() {
|
||||
v.sort_by_key(|(o, _)| *o);
|
||||
}
|
||||
let mut out = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
// Depth first, iteratively; a node reached twice (a cycle in a hostile file) is skipped.
|
||||
let mut stack: Vec<(&str, u8)> = doc.and_then(|d| kids.get(d)).map(|v| v.iter().rev().map(|(_, id)| (*id, 0u8)).collect()).unwrap_or_default();
|
||||
while let Some((id, level)) = stack.pop() {
|
||||
if out.len() >= MAX_NODES || !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
out.push((
|
||||
id.to_string(),
|
||||
DiagramNode {
|
||||
text: texts.get(id).cloned().unwrap_or_default(),
|
||||
level: level.min(8),
|
||||
picture: None,
|
||||
assistant: assistants.contains(id),
|
||||
title: titles.get(id).cloned().unwrap_or_default(),
|
||||
},
|
||||
));
|
||||
if let Some(v) = kids.get(id) {
|
||||
stack.extend(v.iter().rev().map(|(_, c)| (*c, level.saturating_add(1))));
|
||||
}
|
||||
}
|
||||
if out.is_empty() && kids.is_empty() {
|
||||
for id in pt_order {
|
||||
if out.len() >= MAX_NODES || !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
out.push((
|
||||
id.to_string(),
|
||||
DiagramNode {
|
||||
text: texts.get(id).cloned().unwrap_or_default(),
|
||||
level: 0,
|
||||
picture: None,
|
||||
assistant: assistants.contains(id),
|
||||
title: titles.get(id).cloned().unwrap_or_default(),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A text body's paragraphs joined by spaces.
|
||||
fn paragraphs(t: &El) -> String {
|
||||
t.children_named("p")
|
||||
.map(|p| {
|
||||
let mut v = vec![];
|
||||
p.find_all("t", &mut v);
|
||||
v.iter().map(|e| e.text()).collect::<String>()
|
||||
})
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// The layout algorithm and node shape of a DeckCraft layout.
|
||||
fn alg(kind: &str) -> (&'static str, Vec<(&'static str, &'static str)>, &'static str) {
|
||||
match kind {
|
||||
"process" | "stepUp" | "pictureProcess" | "pictureCaption" | "pictureHList" | "timeline" => {
|
||||
("lin", vec![("linDir", "fromL"), ("nodeVertAlign", "mid")], "roundRect")
|
||||
}
|
||||
"chevron" => ("lin", vec![("linDir", "fromL"), ("nodeVertAlign", "mid")], "chevron"),
|
||||
"verticalProcess" => ("lin", vec![("linDir", "fromT"), ("nodeHorzAlign", "ctr")], "roundRect"),
|
||||
"cycle"
|
||||
| "radial"
|
||||
| "venn"
|
||||
| "target"
|
||||
| "textCycle"
|
||||
| "continuousCycle"
|
||||
| "gear"
|
||||
| "segmentedCycle"
|
||||
| "multidirectionalCycle"
|
||||
| "cycleMatrix"
|
||||
| "pie" => ("cycle", vec![("stAng", "0"), ("spanAng", "360")], "ellipse"),
|
||||
"blockCycle" => ("cycle", vec![("stAng", "0"), ("spanAng", "360")], "roundRect"),
|
||||
"pyramid" | "invertedPyramid" | "segmentedPyramid" => {
|
||||
("pyra", vec![("linDir", if kind == "pyramid" { "fromT" } else { "fromB" }), ("txDir", "fromT"), ("pyraAcctPos", "bef")], "trapezoid")
|
||||
}
|
||||
"matrix" | "titledMatrix" | "gridMatrix" | "blockList" => (
|
||||
"snake",
|
||||
vec![("grDir", "tL"), ("flowDir", "row"), ("contDir", "sameDir"), ("off", "ctr")],
|
||||
if kind == "blockList" { "rect" } else { "roundRect" },
|
||||
),
|
||||
"hBulletList" => ("lin", vec![("linDir", "fromL"), ("nodeVertAlign", "t")], "roundRect"),
|
||||
_ => ("lin", vec![("linDir", "fromT"), ("vertAlign", "mid")], "roundRect"),
|
||||
}
|
||||
}
|
||||
|
||||
fn node_layout(w: &mut W, shape: &str, bullets: bool) {
|
||||
w.open("dgm:layoutNode", A::new().a("name", "node"));
|
||||
w.open0("dgm:varLst");
|
||||
w.empty("dgm:bulletEnabled", A::new().a("val", if bullets { "1" } else { "0" }));
|
||||
w.close("dgm:varLst");
|
||||
w.empty("dgm:alg", A::new().a("type", "tx"));
|
||||
w.open("dgm:shape", A::new().a("type", shape).a("r:blip", ""));
|
||||
w.empty0("dgm:adjLst");
|
||||
w.close("dgm:shape");
|
||||
w.empty("dgm:presOf", A::new().a("axis", if bullets { "desOrSelf" } else { "self" }).a("ptType", "node"));
|
||||
w.open0("dgm:constrLst");
|
||||
for side in ["tMarg", "bMarg", "lMarg", "rMarg"] {
|
||||
w.empty("dgm:constr", A::new().a("type", side).a("refType", "primFontSz").a("fact", "0.3"));
|
||||
}
|
||||
w.close("dgm:constrLst");
|
||||
w.open0("dgm:ruleLst");
|
||||
w.empty("dgm:rule", A::new().a("type", "primFontSz").a("val", "5").a("fact", "NaN").a("max", "NaN"));
|
||||
w.close("dgm:ruleLst");
|
||||
w.close("dgm:layoutNode");
|
||||
}
|
||||
|
||||
fn space(w: &mut W) {
|
||||
w.open("dgm:forEach", A::new().a("name", "sibling").a("axis", "followSib").a("ptType", "sibTrans").a("cnt", "1"));
|
||||
w.open("dgm:layoutNode", A::new().a("name", "space"));
|
||||
w.empty("dgm:alg", A::new().a("type", "sp"));
|
||||
w.open("dgm:shape", A::new().a("r:blip", ""));
|
||||
w.empty0("dgm:adjLst");
|
||||
w.close("dgm:shape");
|
||||
w.empty0("dgm:presOf");
|
||||
w.empty0("dgm:constrLst");
|
||||
w.empty0("dgm:ruleLst");
|
||||
w.close("dgm:layoutNode");
|
||||
w.close("dgm:forEach");
|
||||
}
|
||||
|
||||
/// `ppt/diagrams/layoutN.xml`: a layout definition for DeckCraft's layout `kind`, under the id of
|
||||
/// the closest built-in PowerPoint layout.
|
||||
pub fn layout_xml(kind: &str) -> Vec<u8> {
|
||||
let mut w = W::new();
|
||||
w.open(
|
||||
"dgm:layoutDef",
|
||||
A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("xmlns:r", crate::opc::NS_R).a("uniqueId", layout_id(kind)),
|
||||
);
|
||||
w.empty("dgm:title", A::new().a("val", ""));
|
||||
w.empty("dgm:desc", A::new().a("val", ""));
|
||||
w.open0("dgm:catLst");
|
||||
w.empty("dgm:cat", A::new().a("type", category(kind)).a("pri", "1000"));
|
||||
w.close("dgm:catLst");
|
||||
w.open("dgm:layoutNode", A::new().a("name", "diagram"));
|
||||
w.open0("dgm:varLst");
|
||||
w.empty0("dgm:dir");
|
||||
w.empty("dgm:resizeHandles", A::new().a("val", "exact"));
|
||||
w.close("dgm:varLst");
|
||||
if matches!(kind, "hierarchy" | "horizontalHierarchy" | "orgChart" | "halfCircleOrgChart" | "nameTitleOrgChart") {
|
||||
// Each node over the row of its children, recursively.
|
||||
w.empty("dgm:alg", A::new().a("type", "hierChild"));
|
||||
w.open("dgm:shape", A::new().a("r:blip", ""));
|
||||
w.empty0("dgm:adjLst");
|
||||
w.close("dgm:shape");
|
||||
w.empty0("dgm:presOf");
|
||||
w.empty0("dgm:constrLst");
|
||||
w.empty0("dgm:ruleLst");
|
||||
w.open("dgm:forEach", A::new().a("name", "level").a("axis", "ch").a("ptType", "node"));
|
||||
w.open("dgm:layoutNode", A::new().a("name", "hierRoot"));
|
||||
w.empty("dgm:alg", A::new().a("type", "hierRoot"));
|
||||
w.open("dgm:shape", A::new().a("r:blip", ""));
|
||||
w.empty0("dgm:adjLst");
|
||||
w.close("dgm:shape");
|
||||
w.empty0("dgm:presOf");
|
||||
w.empty0("dgm:constrLst");
|
||||
w.empty0("dgm:ruleLst");
|
||||
node_layout(&mut w, "roundRect", false);
|
||||
w.open("dgm:layoutNode", A::new().a("name", "hierChild"));
|
||||
w.empty("dgm:alg", A::new().a("type", "hierChild"));
|
||||
w.open("dgm:shape", A::new().a("r:blip", ""));
|
||||
w.empty0("dgm:adjLst");
|
||||
w.close("dgm:shape");
|
||||
w.empty0("dgm:presOf");
|
||||
w.empty0("dgm:constrLst");
|
||||
w.empty0("dgm:ruleLst");
|
||||
w.empty("dgm:forEach", A::new().a("name", "repeat").a("ref", "level"));
|
||||
w.close("dgm:layoutNode");
|
||||
w.close("dgm:layoutNode");
|
||||
w.close("dgm:forEach");
|
||||
} else {
|
||||
let (ty, params, shape) = alg(kind);
|
||||
w.open("dgm:alg", A::new().a("type", ty));
|
||||
for (k, v) in params {
|
||||
w.empty("dgm:param", A::new().a("type", k).a("val", v));
|
||||
}
|
||||
w.close("dgm:alg");
|
||||
w.open("dgm:shape", A::new().a("r:blip", ""));
|
||||
w.empty0("dgm:adjLst");
|
||||
w.close("dgm:shape");
|
||||
w.empty0("dgm:presOf");
|
||||
w.open0("dgm:constrLst");
|
||||
w.empty("dgm:constr", A::new().a("type", "w").a("for", "ch").a("forName", "node").a("refType", "w"));
|
||||
w.empty(
|
||||
"dgm:constr",
|
||||
A::new().a("type", "h").a("for", "ch").a("forName", "node").a("refType", "w").a("refFor", "ch").a("refForName", "node").a("fact", "0.6"),
|
||||
);
|
||||
w.empty(
|
||||
"dgm:constr",
|
||||
A::new().a("type", "w").a("for", "ch").a("forName", "space").a("refType", "w").a("refFor", "ch").a("refForName", "node").a("fact", "0.1"),
|
||||
);
|
||||
w.empty("dgm:constr", A::new().a("type", "primFontSz").a("for", "ch").a("forName", "node").a("op", "equ").a("val", "65"));
|
||||
w.close("dgm:constrLst");
|
||||
w.empty0("dgm:ruleLst");
|
||||
w.open("dgm:forEach", A::new().a("name", "nodes").a("axis", "ch").a("ptType", "node"));
|
||||
node_layout(&mut w, shape, true);
|
||||
if !matches!(kind, "cycle" | "blockCycle" | "radial") {
|
||||
space(&mut w);
|
||||
}
|
||||
w.close("dgm:forEach");
|
||||
}
|
||||
w.close("dgm:layoutNode");
|
||||
w.close("dgm:layoutDef");
|
||||
w.finish()
|
||||
}
|
||||
|
||||
/// The top bevel (preset, width in EMU) of a 3-D SmartArt Style.
|
||||
fn bevel(style: &str) -> Option<(&'static str, i64)> {
|
||||
Some(match style {
|
||||
"polished" => ("circle", 76200),
|
||||
"inset" => ("relaxedInset", 63500),
|
||||
"cartoon" => ("softRound", 50800),
|
||||
"powder" => ("convex", 101600),
|
||||
"brick" => ("slope", 50800),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `ppt/diagrams/quickStyleN.xml`: flat shapes drawn from the theme's first styles.
|
||||
pub fn style_xml(style: &str) -> Vec<u8> {
|
||||
// Brick Scene looks at the diagram from above and to the side.
|
||||
let camera = if style == "brick" { "isometricOffAxis2Top" } else { "orthographicFront" };
|
||||
let mut w = W::new();
|
||||
w.open("dgm:styleDef", A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("uniqueId", qs_id(style)));
|
||||
w.empty("dgm:title", A::new().a("val", ""));
|
||||
w.empty("dgm:desc", A::new().a("val", ""));
|
||||
w.open0("dgm:catLst");
|
||||
w.empty("dgm:cat", A::new().a("type", if bevel(style).is_some() { "3D" } else { "simple" }).a("pri", "10100"));
|
||||
w.close("dgm:catLst");
|
||||
w.open0("dgm:scene3d");
|
||||
w.empty("a:camera", A::new().a("prst", camera));
|
||||
w.empty("a:lightRig", A::new().a("rig", "threePt").a("dir", "t"));
|
||||
w.close("dgm:scene3d");
|
||||
w.open("dgm:styleLbl", A::new().a("name", "node1"));
|
||||
w.open0("dgm:scene3d");
|
||||
w.empty("a:camera", A::new().a("prst", camera));
|
||||
w.empty("a:lightRig", A::new().a("rig", "threePt").a("dir", "t"));
|
||||
w.close("dgm:scene3d");
|
||||
match bevel(style) {
|
||||
Some((prst, w_emu)) => {
|
||||
w.open0("dgm:sp3d");
|
||||
w.empty("a:bevelT", A::new().a("w", w_emu.to_string()).a("h", (w_emu * 3 / 5).to_string()).a("prst", prst));
|
||||
w.close("dgm:sp3d");
|
||||
}
|
||||
None => w.empty0("dgm:sp3d"),
|
||||
}
|
||||
w.empty("dgm:txPr", A::new());
|
||||
w.open0("dgm:style");
|
||||
for (tag, idx) in [("a:lnRef", "2"), ("a:fillRef", "1"), ("a:effectRef", "0")] {
|
||||
w.open(tag, A::new().a("idx", idx));
|
||||
w.empty("a:scrgbClr", A::new().a("r", "0").a("g", "0").a("b", "0"));
|
||||
w.close(tag);
|
||||
}
|
||||
w.open("a:fontRef", A::new().a("idx", "minor"));
|
||||
w.empty("a:schemeClr", A::new().a("val", "lt1"));
|
||||
w.close("a:fontRef");
|
||||
w.close("dgm:style");
|
||||
w.close("dgm:styleLbl");
|
||||
w.close("dgm:styleDef");
|
||||
w.finish()
|
||||
}
|
||||
|
||||
/// `ppt/diagrams/colorsN.xml`: accent 1 fills with light text.
|
||||
pub fn colors_xml(colors: &str) -> Vec<u8> {
|
||||
let mut w = W::new();
|
||||
w.open("dgm:colorsDef", A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("uniqueId", cs_id(colors)));
|
||||
w.empty("dgm:title", A::new().a("val", ""));
|
||||
w.empty("dgm:desc", A::new().a("val", ""));
|
||||
let accents = fill_accents(colors);
|
||||
let single = accents.len() == 1;
|
||||
let cat = if single { accents.first().map(String::as_str).unwrap_or("accent1") } else { "colorful" };
|
||||
w.open0("dgm:catLst");
|
||||
w.empty("dgm:cat", A::new().a("type", cat).a("pri", "11200"));
|
||||
w.close("dgm:catLst");
|
||||
w.open("dgm:styleLbl", A::new().a("name", "node1"));
|
||||
if colors.ends_with("Grad") {
|
||||
// Gradient Range: the accent shaded darker across the shapes.
|
||||
w.open("dgm:fillClrLst", A::new().a("meth", "repeat"));
|
||||
for k in 0..4 {
|
||||
w.open("a:schemeClr", A::new().a("val", cat));
|
||||
w.empty("a:lumMod", A::new().a("val", (100_000 - k * 15_000).to_string()));
|
||||
w.close("a:schemeClr");
|
||||
}
|
||||
w.close("dgm:fillClrLst");
|
||||
} else {
|
||||
w.open("dgm:fillClrLst", A::new().a("meth", "repeat"));
|
||||
for a in &accents {
|
||||
w.empty("a:schemeClr", A::new().a("val", a.as_str()));
|
||||
}
|
||||
w.close("dgm:fillClrLst");
|
||||
}
|
||||
w.open("dgm:linClrLst", A::new().a("meth", "repeat"));
|
||||
w.empty("a:schemeClr", A::new().a("val", "lt1"));
|
||||
w.close("dgm:linClrLst");
|
||||
w.empty0("dgm:effectClrLst");
|
||||
w.empty0("dgm:txLinClrLst");
|
||||
w.empty0("dgm:txFillClrLst");
|
||||
w.empty0("dgm:txEffectClrLst");
|
||||
w.close("dgm:styleLbl");
|
||||
w.close("dgm:colorsDef");
|
||||
w.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn nodes(v: &[(&str, u8)]) -> Vec<DiagramNode> {
|
||||
v.iter().map(|(t, l)| DiagramNode { text: (*t).into(), level: *l, picture: None, assistant: false, title: String::new() }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_survives_the_data_model() {
|
||||
let d =
|
||||
Diagram { kind: "hierarchy".into(), nodes: nodes(&[("CEO", 0), ("CTO", 1), ("Dev", 2), ("CFO", 1), ("Board", 0)]), ..Default::default() };
|
||||
let xml = data_xml(&d, 7, "rId9", &[]);
|
||||
let doc = crate::xml::parse(&xml).unwrap();
|
||||
assert_eq!(outline(&doc.root), d.nodes);
|
||||
let s = String::from_utf8(xml).unwrap();
|
||||
assert!(s.contains("hierarchy1") && s.contains("relId=\"rId9\""));
|
||||
for x in [
|
||||
layout_xml("hierarchy"),
|
||||
layout_xml("cycle"),
|
||||
style_xml("subtle"),
|
||||
colors_xml(""),
|
||||
colors_xml("accent3"),
|
||||
style_xml("polished"),
|
||||
colors_xml("range23"),
|
||||
colors_xml("accent6Grad"),
|
||||
layout_xml("pictureList"),
|
||||
] {
|
||||
assert!(crate::xml::parse(&x).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assistants_survive_the_data_model() {
|
||||
let mut v = nodes(&[("CEO", 0), ("Aide", 1), ("CTO", 1)]);
|
||||
v[1].assistant = true;
|
||||
v[0].title = "Chief Executive".into();
|
||||
let d = Diagram { kind: "orgChart".into(), nodes: v, ..Default::default() };
|
||||
let xml = data_xml(&d, 5, "rId1", &[]);
|
||||
assert!(String::from_utf8(xml.clone()).unwrap().contains("type=\"asst\""));
|
||||
let doc = crate::xml::parse(&xml).unwrap();
|
||||
assert_eq!(outline(&doc.root), d.nodes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_pictures_come_from_presentation_points() {
|
||||
let d = Diagram { kind: "pictureList".into(), nodes: nodes(&[("A", 0), ("a", 1), ("B", 0)]), ..Default::default() };
|
||||
let xml = data_xml(&d, 3, "rId1", &[(2, "rId7".into()), (9, "rId8".into())]);
|
||||
let doc = crate::xml::parse(&xml).unwrap();
|
||||
assert_eq!(node_pictures(&doc.root), vec![(2, "rId7".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_and_colour_ids_round_trip() {
|
||||
for st in ["", "subtle", "intense", "outline", "polished", "inset", "cartoon", "powder", "brick"] {
|
||||
assert_eq!(style_for(&qs_id(st)), st);
|
||||
}
|
||||
for c in ["", "range23", "range56", "accent1", "accent4Grad"] {
|
||||
assert_eq!(colors_for(&cs_id(c)), c);
|
||||
}
|
||||
assert!(String::from_utf8(style_xml("cartoon")).unwrap().contains("bevelT"));
|
||||
assert!(layout_id("pictureProcess").ends_with("/hProcess10"), "Picture Accent Process");
|
||||
assert!(layout_id("pictureHList").ends_with("/pList2"), "Horizontal Picture List");
|
||||
// Picture Accent Process as an earlier DeckCraft wrote it (pList2, process category).
|
||||
assert_eq!(kind_for("urn:microsoft.com/office/officeart/2005/8/layout/pList2", "process"), "pictureProcess");
|
||||
assert_eq!(kind_for("urn:microsoft.com/office/officeart/2005/8/layout/pList2", "list"), "pictureHList");
|
||||
for k in [
|
||||
"pictureList",
|
||||
"pictureCaption",
|
||||
"pictureProcess",
|
||||
"pictureHList",
|
||||
"timeline",
|
||||
"venn",
|
||||
"target",
|
||||
"textCycle",
|
||||
"continuousCycle",
|
||||
"horizontalHierarchy",
|
||||
"gridMatrix",
|
||||
"gear",
|
||||
"funnel",
|
||||
"segmentedCycle",
|
||||
"multidirectionalCycle",
|
||||
"orgChart",
|
||||
"halfCircleOrgChart",
|
||||
"cycleMatrix",
|
||||
"segmentedPyramid",
|
||||
"pie",
|
||||
"nameTitleOrgChart",
|
||||
"verticalBoxList",
|
||||
"trapezoidList",
|
||||
"tableList",
|
||||
"accentProcess",
|
||||
"continuousBlockProcess",
|
||||
"bendingProcess",
|
||||
"linearVenn",
|
||||
"stackedVenn",
|
||||
"nestedTarget",
|
||||
] {
|
||||
assert_eq!(kind_for(layout_id(k), ""), k);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_links_are_bounded() {
|
||||
let xml = br#"<dgm:dataModel xmlns:dgm="d"><dgm:ptLst><dgm:pt modelId="0" type="doc"/><dgm:pt modelId="1"><dgm:t><a:p xmlns:a="a"><a:r><a:t>A</a:t></a:r></a:p></dgm:t></dgm:pt><dgm:pt modelId="2"/></dgm:ptLst><dgm:cxnLst><dgm:cxn srcId="0" destId="1"/><dgm:cxn srcId="1" destId="2"/><dgm:cxn srcId="2" destId="1"/><dgm:cxn type="presOf" srcId="0" destId="2"/></dgm:cxnLst></dgm:dataModel>"#;
|
||||
let doc = crate::xml::parse(xml).unwrap();
|
||||
assert_eq!(outline(&doc.root), nodes(&[("A", 0), ("", 1)]));
|
||||
assert_eq!(kind_for("urn:microsoft.com/office/officeart/2005/8/layout/orgChart1", ""), "orgChart");
|
||||
assert_eq!(kind_for("urn:x/layout/NameandTitleOrganizationalChart", ""), "nameTitleOrgChart");
|
||||
assert_eq!(kind_for("urn:x/layout/chevron2", "process"), "chevron");
|
||||
assert_eq!(kind_for("urn:x/layout/hProcess9", "process"), "process");
|
||||
assert_eq!(kind_for("urn:x/layout/default", "list"), "blockList");
|
||||
assert_eq!(colors_for(&cs_id("accent4")), "accent4");
|
||||
assert_eq!(colors_for(&cs_id("")), "");
|
||||
assert_eq!(style_for(&qs_id("outline")), "outline");
|
||||
|
||||
let unconnected = br#"<dgm:dataModel xmlns:dgm="d"><dgm:ptLst><dgm:pt modelId="0" type="doc"/><dgm:pt modelId="1" type="node"><dgm:t><a:p xmlns:a="a"><a:r><a:t>Alpha</a:t></a:r></a:p></dgm:t></dgm:pt><dgm:pt modelId="2" type="node"><dgm:t><a:p xmlns:a="a"><a:r><a:t>Beta</a:t></a:r></a:p></dgm:t></dgm:pt></dgm:ptLst><dgm:cxnLst/></dgm:dataModel>"#;
|
||||
let unconnected_doc = crate::xml::parse(unconnected).unwrap();
|
||||
assert_eq!(outline(&unconnected_doc.root), nodes(&[("Alpha", 0), ("Beta", 0)]));
|
||||
|
||||
// When parOf connections exist but no root (type="doc") reaches them, do not flatten the hierarchy to level 0.
|
||||
let unrooted_hierarchy = br#"<dgm:dataModel xmlns:dgm="d"><dgm:ptLst><dgm:pt modelId="1" type="node"><dgm:t><a:p xmlns:a="a"><a:r><a:t>Parent</a:t></a:r></a:p></dgm:t></dgm:pt><dgm:pt modelId="2" type="node"><dgm:t><a:p xmlns:a="a"><a:r><a:t>Child</a:t></a:r></a:p></dgm:t></dgm:pt></dgm:ptLst><dgm:cxnLst><dgm:cxn srcId="1" destId="2"/></dgm:cxnLst></dgm:dataModel>"#;
|
||||
let unrooted_doc = crate::xml::parse(unrooted_hierarchy).unwrap();
|
||||
assert!(outline(&unrooted_doc.root).is_empty());
|
||||
}
|
||||
}
|
||||
+859
-66
@@ -1,5 +1,5 @@
|
||||
//! PPTX import and export: Office Open XML PresentationML / DrawingML, written from the public
|
||||
//! ECMA-376 standard.
|
||||
//! PPTX import and export: Office Open XML PresentationML / DrawingML, delegated to the shared
|
||||
//! `craft-pptx` crate.
|
||||
//!
|
||||
//! [`import`] reads a package leniently (unknown parts are skipped, malformed parts are logged and
|
||||
//! ignored, every size and depth is bounded) into the DeckCraft model; [`export`] writes a valid
|
||||
@@ -8,28 +8,15 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod cfb;
|
||||
mod custgeom;
|
||||
mod dgm;
|
||||
mod maps;
|
||||
mod opc;
|
||||
mod png;
|
||||
pub(crate) mod read;
|
||||
pub use read::MAX_TAG_BYTES;
|
||||
mod tables;
|
||||
mod write;
|
||||
mod convert;
|
||||
mod xml;
|
||||
|
||||
pub use craft_pptx::MAX_TAG_BYTES;
|
||||
/// The bounded XML reader the importer uses, for callers that read kept fragments (a shape's
|
||||
/// 3-D settings) instead of scanning strings.
|
||||
pub use xml::{Doc as XmlDoc, El as XmlEl, parse as parse_xml};
|
||||
|
||||
use deckcraft_model::Presentation;
|
||||
|
||||
/// Extension URI of the PowerPoint 2010 section list in `presentation.xml`.
|
||||
pub(crate) const SECTION_EXT_URI: &str = "{521415D9-36F7-43E2-AB2F-B90AF26B5E84}";
|
||||
|
||||
/// Extension URI of the modern-comments anchor in a slide (names the threaded comment part).
|
||||
pub(crate) const COMMENTS_EXT_URI: &str = "{6950BFC3-D8DA-4A85-94F7-54DA5524770B}";
|
||||
use deckcraft_model::{Presentation, Shape, ShapeKind, defaults};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PptxError {
|
||||
@@ -43,15 +30,50 @@ pub enum PptxError {
|
||||
Xml(String),
|
||||
}
|
||||
|
||||
impl From<craft_pptx::Error> for PptxError {
|
||||
fn from(e: craft_pptx::Error) -> Self {
|
||||
match e {
|
||||
craft_pptx::Error::NotPptx(m) => PptxError::NotPptx(m),
|
||||
craft_pptx::Error::Unsupported(m) => PptxError::Unsupported(m),
|
||||
craft_pptx::Error::Write(m) => PptxError::Write(m),
|
||||
craft_pptx::Error::Xml(m) => PptxError::Xml(m),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DeckDefaults;
|
||||
|
||||
impl craft_pptx::Defaults for DeckDefaults {
|
||||
fn master(&self, size: deckcraft_geom::Size, after: u32) -> (craft_pptx::Master, u32) {
|
||||
let (m, last) = defaults::build_master(size, Default::default(), after);
|
||||
(convert::master_to_craft(&m), last)
|
||||
}
|
||||
|
||||
fn theme(&self) -> craft_drawingml::theme::Theme {
|
||||
convert::theme_to_craft(&deckcraft_model::theme::Theme::default())
|
||||
}
|
||||
|
||||
fn master_styles(&self) -> (craft_drawingml::text::ListStyle, craft_drawingml::text::ListStyle, craft_drawingml::text::ListStyle) {
|
||||
// An imported empty master style must stay empty on save; new decks already carry their
|
||||
// populated master styles in the model.
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn default_text_style(&self) -> craft_drawingml::text::ListStyle {
|
||||
convert::list_style_to_craft(&defaults::default_text_style())
|
||||
}
|
||||
|
||||
fn application(&self) -> &str {
|
||||
"DeckCraft"
|
||||
}
|
||||
}
|
||||
|
||||
/// Does this look like an OOXML package (zip with `[Content_Types].xml`)?
|
||||
///
|
||||
/// The part is looked up in the zip's central directory, not in the leading bytes: writers may
|
||||
/// The part is looked up in the archive's central directory, not in the leading bytes: writers may
|
||||
/// store it anywhere in the archive (recent PowerPoint builds put it last, megabytes in).
|
||||
pub fn sniff(bytes: &[u8]) -> bool {
|
||||
if !bytes.starts_with(b"PK") {
|
||||
return false;
|
||||
}
|
||||
zip::ZipArchive::new(std::io::Cursor::new(bytes)).map(|z| z.index_for_name("[Content_Types].xml").is_some()).unwrap_or(false)
|
||||
craft_pptx::sniff(bytes)
|
||||
}
|
||||
|
||||
/// Is this a password-protected presentation (an encrypted package inside a compound file)?
|
||||
@@ -59,81 +81,787 @@ pub fn is_encrypted(bytes: &[u8]) -> bool {
|
||||
cfb::is_encrypted(bytes)
|
||||
}
|
||||
|
||||
const MAX_SLIDE_ENTRIES: usize = 10_000;
|
||||
|
||||
/// Checks `ppt/presentation.xml` for > 10,000 slide-list entries (refused instead of truncated)
|
||||
/// and collects any `sldId` entries whose relationship is missing so `import_checked` /
|
||||
/// `import_report` report them as lost slides.
|
||||
fn preflight_slides(bytes: &[u8]) -> Result<Vec<String>, PptxError> {
|
||||
let Ok(mut pkg) = craft_opc::LazyPackage::open(bytes, &craft_pptx::LIMITS) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
let root_rels = pkg.rels("").unwrap_or_default();
|
||||
let pres_path = root_rels.first("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into());
|
||||
let Ok(Some(pres_bytes)) = pkg.read_limited(&pres_path, craft_pptx::MAX_XML_PART as u64) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
let Ok(pres_el) = craft_drawingml::xmlx::parse(&pres_bytes) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
let pres_rels = pkg.rels(&pres_path).unwrap_or_default();
|
||||
let mut lost = Vec::new();
|
||||
if let Some(list) = pres_el.child(craft_xml::Local("sldIdLst")) {
|
||||
let mut count = 0usize;
|
||||
for s in list.children(craft_xml::Local("sldId")) {
|
||||
count += 1;
|
||||
if count > MAX_SLIDE_ENTRIES {
|
||||
return Err(PptxError::Unsupported(format!("presentation has more than {MAX_SLIDE_ENTRIES} slides")));
|
||||
}
|
||||
let rid = s.attr_local("r:id").unwrap_or("");
|
||||
if pres_rels.target(rid).is_none() {
|
||||
let id = s.attr_local("id").and_then(craft_xml::value::to_u32_lossy).unwrap_or(0);
|
||||
lost.push(format!("slide {id} (missing relationship {rid})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(lost)
|
||||
}
|
||||
|
||||
fn has_unfolded_paragraph_builds(p: &Presentation) -> bool {
|
||||
p.slides.iter().any(|s| s.animations.windows(2).any(|w| w[0].paragraph.is_some() && w[1].paragraph.is_some() && w[0].shape == w[1].shape))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SlideTimingInfo {
|
||||
opt_out: std::collections::HashSet<u32>,
|
||||
offsets: std::collections::HashMap<(u32, u32), u32>,
|
||||
}
|
||||
|
||||
fn timing_ms(e: &craft_xml::El, name: &str) -> Option<u32> {
|
||||
let v = e.attr_local(name)?.trim();
|
||||
if v == "indefinite" {
|
||||
return None;
|
||||
}
|
||||
v.parse::<f64>().ok().filter(|n| n.is_finite() && *n >= 0.0).map(|n| n.min(u32::MAX as f64) as u32)
|
||||
}
|
||||
|
||||
fn collect_timing_offsets(e: &craft_xml::El, offset: u32, out: &mut std::collections::HashMap<(u32, u32), u32>, depth: usize) {
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
for c in e.elements() {
|
||||
if c.is(craft_xml::Local("cTn")) && c.attr_local("presetClass").is_some() {
|
||||
if let Some(sp) = c.find(craft_xml::Local("spTgt"))
|
||||
&& let Some(spid) = sp.attr_local("spid").and_then(craft_xml::value::to_u32_lossy)
|
||||
&& let Some(p) = sp
|
||||
.path(&[craft_xml::Local("txEl"), craft_xml::Local("pRg")])
|
||||
.and_then(|r| r.attr_local("st"))
|
||||
.and_then(craft_xml::value::to_u32_lossy)
|
||||
{
|
||||
out.entry((spid, p)).or_insert(offset);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut next_offset = offset;
|
||||
if c.is(craft_xml::Local("cTn"))
|
||||
&& let Some(cond) = c.path(&[craft_xml::Local("stCondLst"), craft_xml::Local("cond")])
|
||||
{
|
||||
if cond.attr_local("delay").map(str::trim) == Some("indefinite") {
|
||||
next_offset = 0;
|
||||
} else {
|
||||
next_offset = next_offset.saturating_add(timing_ms(cond, "delay").unwrap_or(0));
|
||||
}
|
||||
}
|
||||
collect_timing_offsets(c, next_offset, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn defers_start(st: &craft_xml::El) -> bool {
|
||||
let is_auto_begin = |c: &craft_xml::El| {
|
||||
c.attr_local("evt") == Some("onBegin")
|
||||
&& c.attr_local("delay").map(str::trim) == Some("0")
|
||||
&& c.child(craft_xml::Local("tgtEl")).is_none()
|
||||
&& c.child(craft_xml::Local("tn")).is_none()
|
||||
&& c.child(craft_xml::Local("rtn")).is_none()
|
||||
};
|
||||
let has_on_begin = st.children(craft_xml::Local("cond")).any(is_auto_begin);
|
||||
st.children(craft_xml::Local("cond"))
|
||||
.any(|c| (c.attr_local("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr_local("delay").map(str::trim) != Some("0")))
|
||||
}
|
||||
|
||||
fn is_main_seq_auto(st: &craft_xml::El, main_seq_id: Option<u32>) -> bool {
|
||||
let Some(ms_id) = main_seq_id else {
|
||||
return false;
|
||||
};
|
||||
let is_indefinite = |d: &craft_xml::El| {
|
||||
d.attr_local("evt").is_none()
|
||||
&& d.attr_local("delay").map(str::trim) == Some("indefinite")
|
||||
&& d.child(craft_xml::Local("tgtEl")).is_none()
|
||||
&& d.child(craft_xml::Local("tn")).is_none()
|
||||
&& d.child(craft_xml::Local("rtn")).is_none()
|
||||
};
|
||||
let is_main_seq_on_begin = |d: &craft_xml::El| {
|
||||
d.attr_local("evt") == Some("onBegin")
|
||||
&& d.attr_local("delay").map(str::trim) == Some("0")
|
||||
&& d.child(craft_xml::Local("tgtEl")).is_none()
|
||||
&& d.child(craft_xml::Local("rtn")).is_none()
|
||||
&& d.child(craft_xml::Local("tn")).and_then(|tn| tn.attr_local("val")).and_then(craft_xml::value::to_u32_lossy) == Some(ms_id)
|
||||
};
|
||||
st.children(craft_xml::Local("cond")).any(is_indefinite)
|
||||
&& st.children(craft_xml::Local("cond")).any(is_main_seq_on_begin)
|
||||
&& st.children(craft_xml::Local("cond")).all(|d| is_indefinite(d) || is_main_seq_on_begin(d))
|
||||
}
|
||||
|
||||
fn collect_media_nodes<'a>(e: &'a craft_xml::El, deferred: bool, out: &mut Vec<(&'a craft_xml::El, bool)>, depth: usize) {
|
||||
if depth > 64 || out.len() >= 10_000 {
|
||||
return;
|
||||
}
|
||||
let mut deferred = deferred;
|
||||
if e.is(craft_xml::Local("cTn"))
|
||||
&& let Some(st) = e.child(craft_xml::Local("stCondLst"))
|
||||
&& defers_start(st)
|
||||
{
|
||||
deferred = true;
|
||||
}
|
||||
if e.is(craft_xml::Local("video")) || e.is(craft_xml::Local("audio")) {
|
||||
out.push((e, deferred));
|
||||
return;
|
||||
}
|
||||
for c in e.elements() {
|
||||
collect_media_nodes(c, deferred, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct MediaPlayAt {
|
||||
trigger: Option<u32>,
|
||||
main_seq_id: Option<u32>,
|
||||
offset: u32,
|
||||
deferred: bool,
|
||||
}
|
||||
|
||||
fn collect_media_plays<'a>(e: &'a craft_xml::El, at: MediaPlayAt, out: &mut Vec<(&'a craft_xml::El, MediaPlayAt)>, depth: usize) {
|
||||
if depth > 64 || out.len() > 10_000 {
|
||||
return;
|
||||
}
|
||||
for c in e.elements() {
|
||||
if c.is(craft_xml::Local("cTn")) && c.attr_local("presetClass").is_some() {
|
||||
let deferred = at.deferred || c.child(craft_xml::Local("stCondLst")).is_some_and(defers_start);
|
||||
out.push((c, MediaPlayAt { deferred, ..at }));
|
||||
continue;
|
||||
}
|
||||
let mut next = at;
|
||||
if c.is(craft_xml::Local("seq"))
|
||||
&& let Some(ctn) = c.child(craft_xml::Local("cTn"))
|
||||
&& ctn.attr_local("nodeType") == Some("interactiveSeq")
|
||||
{
|
||||
next.trigger = ctn
|
||||
.path(&[craft_xml::Local("stCondLst"), craft_xml::Local("cond"), craft_xml::Local("tgtEl"), craft_xml::Local("spTgt")])
|
||||
.and_then(|s| s.attr_local("spid"))
|
||||
.and_then(craft_xml::value::to_u32_lossy);
|
||||
next.main_seq_id = None;
|
||||
}
|
||||
if c.is(craft_xml::Local("cTn")) {
|
||||
let is_main_seq = c.attr_local("nodeType") == Some("mainSeq");
|
||||
if let Some(st) = c.child(craft_xml::Local("stCondLst")) {
|
||||
if !(!is_main_seq && !next.deferred && is_main_seq_auto(st, next.main_seq_id)) && defers_start(st) {
|
||||
next.deferred = true;
|
||||
}
|
||||
if let Some(cond) = st.child(craft_xml::Local("cond")) {
|
||||
if cond.attr_local("delay").map(str::trim) == Some("indefinite") {
|
||||
next.offset = 0;
|
||||
} else {
|
||||
next.offset = next.offset.saturating_add(timing_ms(cond, "delay").unwrap_or(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
next.main_seq_id = if is_main_seq && !next.deferred { c.attr_local("id").and_then(craft_xml::value::to_u32_lossy) } else { None };
|
||||
}
|
||||
collect_media_plays(c, next, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_media_timing(timing: &craft_xml::El, shapes: &mut [Shape]) {
|
||||
let mut nodes = Vec::new();
|
||||
collect_media_nodes(timing, false, &mut nodes, 0);
|
||||
for (node, deferred) in nodes {
|
||||
let Some(cm) = node.child(craft_xml::Local("cMediaNode")) else { continue };
|
||||
let Some(spid) = cm
|
||||
.path(&[craft_xml::Local("tgtEl"), craft_xml::Local("spTgt")])
|
||||
.and_then(|t| t.attr_local("spid"))
|
||||
.and_then(craft_xml::value::to_u32_lossy)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(ShapeKind::Media(clip)) = deckcraft_model::find_shape_mut(shapes, deckcraft_model::ShapeId(spid)).map(|s| &mut s.kind) else {
|
||||
continue;
|
||||
};
|
||||
if cm.child(craft_xml::Local("cTn")).and_then(|c| c.attr_local("fill")) == Some("remove") {
|
||||
clip.rewind = true;
|
||||
}
|
||||
if cm.attr_local("numSld").and_then(craft_xml::value::to_u32_lossy).is_some_and(|n| n > 1) {
|
||||
clip.play_across_slides = true;
|
||||
}
|
||||
if !deferred
|
||||
&& cm
|
||||
.path(&[craft_xml::Local("cTn"), craft_xml::Local("stCondLst"), craft_xml::Local("cond")])
|
||||
.is_some_and(|c| c.attr_local("evt").is_none() && c.attr_local("delay").map(str::trim) == Some("0"))
|
||||
{
|
||||
clip.autoplay = true;
|
||||
}
|
||||
}
|
||||
let root_deferred = timing
|
||||
.path(&[craft_xml::Local("tnLst"), craft_xml::Local("par"), craft_xml::Local("cTn"), craft_xml::Local("stCondLst")])
|
||||
.is_some_and(defers_start);
|
||||
if !root_deferred && let Some(tn) = timing.child(craft_xml::Local("tnLst")) {
|
||||
let mut found = Vec::new();
|
||||
collect_media_plays(tn, MediaPlayAt { trigger: None, main_seq_id: None, offset: 0, deferred: false }, &mut found, 0);
|
||||
for (c, f) in found.into_iter().filter(|(_, f)| f.trigger.is_none()) {
|
||||
if c.attr_local("nodeType") == Some("clickEffect") || f.deferred {
|
||||
break;
|
||||
}
|
||||
let delay = c.path(&[craft_xml::Local("stCondLst"), craft_xml::Local("cond")]).and_then(|d| timing_ms(d, "delay")).unwrap_or(0);
|
||||
if c.attr_local("presetClass") == Some("mediacall")
|
||||
&& c.attr_local("presetID").and_then(craft_xml::value::to_u32_lossy) == Some(1)
|
||||
&& f.offset == 0
|
||||
&& delay == 0
|
||||
&& let Some(spid) = c.find(craft_xml::Local("spTgt")).and_then(|t| t.attr_local("spid")).and_then(craft_xml::value::to_u32_lossy)
|
||||
&& let Some(ShapeKind::Media(clip)) = deckcraft_model::find_shape_mut(shapes, deckcraft_model::ShapeId(spid)).map(|s| &mut s.kind)
|
||||
{
|
||||
clip.autoplay = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_media_shapes(shapes: &[Shape]) -> bool {
|
||||
shapes.iter().any(|s| match &s.kind {
|
||||
ShapeKind::Media(_) => true,
|
||||
ShapeKind::Group { children, .. } => has_media_shapes(children),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn post_import_timing(bytes: &[u8], pres: &mut Presentation) {
|
||||
let need_builds = has_unfolded_paragraph_builds(pres);
|
||||
let need_media = pres.slides.iter().any(|s| has_media_shapes(&s.shapes));
|
||||
if !need_builds && !need_media {
|
||||
return;
|
||||
}
|
||||
let Ok(mut pkg) = craft_opc::LazyPackage::open(bytes, &craft_pptx::LIMITS) else {
|
||||
return;
|
||||
};
|
||||
let root_rels = pkg.rels("").unwrap_or_default();
|
||||
let pres_path = root_rels.first("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into());
|
||||
let Ok(Some(pres_bytes)) = pkg.read_limited(&pres_path, craft_pptx::MAX_XML_PART as u64) else {
|
||||
return;
|
||||
};
|
||||
let Ok(pres_el) = craft_drawingml::xmlx::parse(&pres_bytes) else {
|
||||
return;
|
||||
};
|
||||
let pres_rels = pkg.rels(&pres_path).unwrap_or_default();
|
||||
let Some(list) = pres_el.child(craft_xml::Local("sldIdLst")) else {
|
||||
return;
|
||||
};
|
||||
for (i, s) in list.children(craft_xml::Local("sldId")).take(MAX_SLIDE_ENTRIES).enumerate() {
|
||||
let Some(slide_arc) = pres.slides.get_mut(i) else { break };
|
||||
let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid)) else { continue };
|
||||
let Ok(Some(sb)) = pkg.read_limited(target, craft_pptx::MAX_XML_PART as u64) else { continue };
|
||||
let Ok(se) = craft_drawingml::xmlx::parse(&sb) else { continue };
|
||||
let Some(timing) = se.child(craft_xml::Local("timing")) else { continue };
|
||||
if need_media && has_media_shapes(&slide_arc.shapes) {
|
||||
apply_media_timing(timing, &mut std::sync::Arc::make_mut(slide_arc).shapes);
|
||||
}
|
||||
if need_builds {
|
||||
let mut info = SlideTimingInfo::default();
|
||||
collect_timing_offsets(timing, 0, &mut info.offsets, 0);
|
||||
if let Some(bld_lst) = timing.child(craft_xml::Local("bldLst")) {
|
||||
for b in bld_lst.children(craft_xml::Local("bldP")) {
|
||||
if b.attr_local("build").unwrap_or("") != "p"
|
||||
&& let Some(spid) = b.attr_local("spid").and_then(craft_xml::value::to_u32_lossy)
|
||||
{
|
||||
info.opt_out.insert(spid);
|
||||
}
|
||||
}
|
||||
}
|
||||
fold_slide_paragraph_builds(std::sync::Arc::make_mut(slide_arc), &info);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn span_ms(a: &deckcraft_model::anim::Animation) -> u32 {
|
||||
let iterations = if a.repeat == u32::MAX || a.repeat <= 1 { 1 } else { a.repeat.min(1_000) };
|
||||
a.duration_ms.saturating_mul(if a.auto_reverse { 2 } else { 1 }).saturating_mul(iterations)
|
||||
}
|
||||
|
||||
fn flat_starts(anims: &[&deckcraft_model::anim::Animation]) -> Vec<u32> {
|
||||
let (mut begin, mut end) = (0u32, 0u32);
|
||||
anims
|
||||
.iter()
|
||||
.map(|a| {
|
||||
if a.start == deckcraft_model::anim::AnimStart::AfterPrevious {
|
||||
begin = end;
|
||||
}
|
||||
let start = begin.saturating_add(a.delay_ms);
|
||||
end = end.max(start.saturating_add(span_ms(a)));
|
||||
start
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plays_as_build(effects: &[&deckcraft_model::anim::Animation], offsets: &[u32], text: &deckcraft_model::text::TextBody) -> bool {
|
||||
use deckcraft_model::anim::{AnimStart, Animation, BuildRole, build_filled, paragraph_build_roles};
|
||||
let Some(first) = effects.first() else { return false };
|
||||
let off0 = offsets.first().copied().unwrap_or(0);
|
||||
let flat = flat_starts(effects);
|
||||
let parent_starts_match = offsets
|
||||
.iter()
|
||||
.zip(effects.iter())
|
||||
.zip(flat.iter())
|
||||
.all(|((&off, a), &ft)| off == off0 || off.saturating_add(a.delay_ms) == off0.saturating_add(ft));
|
||||
if !parent_starts_match || (first.start != AnimStart::OnClick && (span_ms(first) != 500 || first.delay_ms != 0 || off0 != 0)) {
|
||||
return false;
|
||||
}
|
||||
let roles = paragraph_build_roles(text);
|
||||
let expected = roles.iter().enumerate().filter(|(i, r)| match r {
|
||||
BuildRole::Top => true,
|
||||
BuildRole::Member(_) => text.paragraphs.get(*i).is_some_and(build_filled),
|
||||
BuildRole::Unowned => false,
|
||||
});
|
||||
let settings = |a: &Animation| Animation { start: AnimStart::OnClick, paragraph: None, ..a.clone() };
|
||||
let base = settings(first);
|
||||
let mut matched = 0;
|
||||
for (k, (i, role)) in expected.enumerate() {
|
||||
let Some(a) = effects.get(k) else { return false };
|
||||
let start_ok = match role {
|
||||
BuildRole::Top if k == 0 => true,
|
||||
BuildRole::Top if first.start == AnimStart::OnClick => a.start == AnimStart::OnClick,
|
||||
BuildRole::Top => a.start == AnimStart::AfterPrevious,
|
||||
_ => a.start == AnimStart::WithPrevious,
|
||||
};
|
||||
if a.paragraph != u32::try_from(i).ok() || !start_ok || settings(a) != base {
|
||||
return false;
|
||||
}
|
||||
matched = k + 1;
|
||||
}
|
||||
matched == effects.len()
|
||||
}
|
||||
|
||||
fn fold_slide_paragraph_builds(slide: &mut deckcraft_model::Slide, info: &SlideTimingInfo) {
|
||||
use deckcraft_model::anim::{Animation, TextBuild};
|
||||
let same = |x: &Animation, y: &Animation| {
|
||||
x.paragraph.is_some()
|
||||
&& y.paragraph.is_some()
|
||||
&& x.text_build == TextBuild::AsOne
|
||||
&& y.text_build == TextBuild::AsOne
|
||||
&& x.shape == y.shape
|
||||
&& x.trigger == y.trigger
|
||||
&& !info.opt_out.contains(&x.shape.0)
|
||||
};
|
||||
let mut folded = Vec::with_capacity(slide.animations.len());
|
||||
for run in slide.animations.chunk_by(same) {
|
||||
let effects: Vec<&Animation> = run.iter().collect();
|
||||
let offsets: Vec<u32> = run.iter().map(|a| a.paragraph.and_then(|p| info.offsets.get(&(a.shape.0, p)).copied()).unwrap_or(0)).collect();
|
||||
let text = effects.first().and_then(|a| deckcraft_model::find_shape(&slide.shapes, a.shape)).and_then(|s| s.text.as_ref());
|
||||
if run.len() > 1
|
||||
&& let (Some(first), Some(text)) = (effects.first(), text)
|
||||
&& !info.opt_out.contains(&first.shape.0)
|
||||
&& plays_as_build(&effects, &offsets, text)
|
||||
{
|
||||
folded.push(Animation { text_build: TextBuild::ByParagraph, paragraph: None, ..(*first).clone() });
|
||||
} else {
|
||||
folded.extend(run.iter().cloned());
|
||||
}
|
||||
}
|
||||
slide.animations = folded;
|
||||
}
|
||||
|
||||
/// Read a `.pptx` / `.potx` / `.ppsx` package.
|
||||
pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
|
||||
read::import(bytes)
|
||||
preflight_slides(bytes)?;
|
||||
let mut pres = craft_pptx::import(bytes, &DeckDefaults).map(convert::pres_from_craft)?;
|
||||
post_import_timing(bytes, &mut pres);
|
||||
Ok(pres)
|
||||
}
|
||||
|
||||
/// [`import`], plus the part names of slides the file lists but that couldn't be read and were
|
||||
/// left out.
|
||||
/// Files with more than 10,000 slide-list entries return [`PptxError::Unsupported`] instead of a truncated presentation.
|
||||
pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxError> {
|
||||
read::import_checked(bytes)
|
||||
let (p, lost, _) = import_report(bytes)?;
|
||||
Ok((p, lost))
|
||||
}
|
||||
|
||||
/// [`import_checked`], plus warnings for content cut to fit a limit (a table past the cell cap
|
||||
/// keeps its leading rows); the file still opens.
|
||||
pub fn import_report(bytes: &[u8]) -> Result<(Presentation, Vec<String>, Vec<String>), PptxError> {
|
||||
read::import_report(bytes)
|
||||
let mut missing = preflight_slides(bytes)?;
|
||||
let (p, lost, warnings) = craft_pptx::import_report(bytes, &DeckDefaults)?;
|
||||
missing.extend(lost);
|
||||
let mut pres = convert::pres_from_craft(p);
|
||||
post_import_timing(bytes, &mut pres);
|
||||
Ok((pres, missing, warnings))
|
||||
}
|
||||
|
||||
/// [`import`] with a lower presentation-wide chart point budget, so tests reach the over-budget
|
||||
/// path without a multi-million-point chart.
|
||||
#[doc(hidden)]
|
||||
pub fn import_with_chart_budget(bytes: &[u8], points: usize) -> Result<Presentation, PptxError> {
|
||||
read::import_with_chart_points(bytes, points).map(|(p, _)| p)
|
||||
preflight_slides(bytes)?;
|
||||
let mut pres = craft_pptx::import_with_chart_budget(bytes, &DeckDefaults, points).map(convert::pres_from_craft)?;
|
||||
post_import_timing(bytes, &mut pres);
|
||||
Ok(pres)
|
||||
}
|
||||
|
||||
/// Read the theme of a `.thmx` file, or of a `.pptx` / `.potx`'s first master, with its media.
|
||||
pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec<deckcraft_model::MediaItem>), PptxError> {
|
||||
read::import_theme(bytes)
|
||||
let (theme, media) = craft_pptx::import_theme(bytes)?;
|
||||
Ok((convert::theme_from_craft(theme), media.into_iter().map(convert::media_item_from_craft).collect()))
|
||||
}
|
||||
|
||||
fn shapes_have_over_cap_table(shapes: &[Shape]) -> bool {
|
||||
shapes.iter().any(|s| match &s.kind {
|
||||
ShapeKind::Table(t) => t.over_cap(),
|
||||
ShapeKind::Group { children, .. } => shapes_have_over_cap_table(children),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn check_table_caps(p: &Presentation) -> Result<(), PptxError> {
|
||||
let over = p.slides.iter().any(|s| shapes_have_over_cap_table(&s.shapes))
|
||||
|| p.masters.iter().any(|m| shapes_have_over_cap_table(&m.shapes) || m.layouts.iter().any(|l| shapes_have_over_cap_table(&l.shapes)))
|
||||
|| p.notes_master.as_ref().is_some_and(|m| shapes_have_over_cap_table(&m.shapes))
|
||||
|| p.handout_master.as_ref().is_some_and(|m| shapes_have_over_cap_table(&m.shapes));
|
||||
if over {
|
||||
return Err(PptxError::Unsupported(format!(
|
||||
"a table has more than {} cells; export refused rather than drop rows",
|
||||
deckcraft_model::table::MAX_CELLS
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn media_needs_timing(clip: &deckcraft_model::MediaClip) -> bool {
|
||||
clip.autoplay
|
||||
|| (clip.volume - 1.0).abs() > 1e-6
|
||||
|| clip.hide_while_not_playing
|
||||
|| clip.loop_play
|
||||
|| clip.rewind
|
||||
|| clip.play_across_slides
|
||||
|| (clip.video && clip.full_screen)
|
||||
}
|
||||
|
||||
fn assign_spids<'a>(shapes: &'a [Shape], mut visit: impl FnMut(u32, &'a Shape)) {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
let mut max = 1u32;
|
||||
deckcraft_model::walk(shapes, &mut |s, _| {
|
||||
if s.id.0 >= 2 && s.id.0 < i32::MAX as u32 {
|
||||
max = max.max(s.id.0);
|
||||
}
|
||||
});
|
||||
let mut next = max;
|
||||
deckcraft_model::walk(shapes, &mut |s, _| {
|
||||
let spid = if s.id.0 >= 2 && s.id.0 < i32::MAX as u32 && !used.contains(&s.id.0) {
|
||||
s.id.0
|
||||
} else {
|
||||
next = next.saturating_add(1);
|
||||
next
|
||||
};
|
||||
used.insert(spid);
|
||||
visit(spid, s);
|
||||
});
|
||||
}
|
||||
|
||||
fn collect_export_media(shapes: &[Shape]) -> Vec<(u32, &deckcraft_model::MediaClip)> {
|
||||
let mut media = Vec::new();
|
||||
assign_spids(shapes, |spid, s| {
|
||||
if let ShapeKind::Media(clip) = &s.kind
|
||||
&& media_needs_timing(clip)
|
||||
{
|
||||
media.push((spid, clip));
|
||||
}
|
||||
});
|
||||
media
|
||||
}
|
||||
|
||||
fn collect_grp_fill_pic_spids(shapes: &[Shape]) -> std::collections::HashSet<u32> {
|
||||
let mut spids = std::collections::HashSet::new();
|
||||
assign_spids(shapes, |spid, s| {
|
||||
if s.fill == Some(deckcraft_model::style::Fill::Group)
|
||||
&& matches!(s.kind, ShapeKind::Picture { .. } | ShapeKind::Opaque { preview: Some(_), .. })
|
||||
{
|
||||
spids.insert(spid);
|
||||
}
|
||||
});
|
||||
spids
|
||||
}
|
||||
|
||||
fn write_media_node(w: &mut craft_xml::Writer, id: &mut u32, spid: u32, clip: &deckcraft_model::MediaClip) {
|
||||
let tag = if clip.video { "p:video" } else { "p:audio" };
|
||||
let mut t = w.tag(tag);
|
||||
if clip.video && clip.full_screen {
|
||||
t = t.attr("fullScrn", "1");
|
||||
}
|
||||
t.open();
|
||||
let vol = (clip.volume.clamp(0.0, 1.0) * 100_000.0).round() as u32;
|
||||
let mut cm = w.tag("p:cMediaNode").attr("vol", vol);
|
||||
if clip.volume <= 1e-6 {
|
||||
cm = cm.attr("mute", "1");
|
||||
}
|
||||
if clip.hide_while_not_playing {
|
||||
cm = cm.attr("showWhenStopped", "0");
|
||||
}
|
||||
if clip.play_across_slides {
|
||||
cm = cm.attr("numSld", "999");
|
||||
}
|
||||
cm.open();
|
||||
*id = id.saturating_add(1);
|
||||
let mut ctn = w.tag("p:cTn").attr("id", *id).attr("fill", if clip.rewind { "remove" } else { "hold" }).attr("display", "0");
|
||||
if clip.loop_play {
|
||||
ctn = ctn.attr("repeatCount", "indefinite");
|
||||
}
|
||||
ctn.open();
|
||||
w.open("p:stCondLst", &[]);
|
||||
w.tag("p:cond").attr("delay", if clip.autoplay { "0" } else { "indefinite" }).empty();
|
||||
w.close();
|
||||
w.close();
|
||||
w.open("p:tgtEl", &[]);
|
||||
w.tag("p:spTgt").attr("spid", spid).empty();
|
||||
w.close();
|
||||
w.close();
|
||||
w.close();
|
||||
}
|
||||
|
||||
fn max_ctn_id(e: &craft_xml::El, max_id: &mut u32, depth: usize) {
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
if e.is(craft_xml::Local("cTn"))
|
||||
&& let Some(id) = e.attr_local("id").and_then(craft_xml::value::to_u32_lossy)
|
||||
{
|
||||
*max_id = (*max_id).max(id);
|
||||
}
|
||||
for c in e.elements() {
|
||||
max_ctn_id(c, max_id, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn patch_slide_media_timing(xml_bytes: &[u8], media: &[(u32, &deckcraft_model::MediaClip)]) -> Vec<u8> {
|
||||
let Ok(mut xml) = String::from_utf8(xml_bytes.to_vec()) else {
|
||||
return xml_bytes.to_vec();
|
||||
};
|
||||
let mut next_id = 1u32;
|
||||
if let Ok(el) = craft_drawingml::xmlx::parse(xml_bytes) {
|
||||
max_ctn_id(&el, &mut next_id, 0);
|
||||
}
|
||||
let mut w = craft_xml::Writer::new();
|
||||
for &(spid, clip) in media {
|
||||
write_media_node(&mut w, &mut next_id, spid, clip);
|
||||
}
|
||||
let nodes = w.finish();
|
||||
if let Some(tn_end) = xml.rfind("</p:tnLst>")
|
||||
&& let Some(pos) = xml[..tn_end].rfind("</p:childTnLst>")
|
||||
{
|
||||
xml.insert_str(pos, &nodes);
|
||||
} else if let Some(pos) = xml.rfind("</p:sld>") {
|
||||
let timing = format!(
|
||||
r#"<p:timing><p:tnLst><p:par><p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot"><p:childTnLst>{nodes}</p:childTnLst></p:cTn></p:par></p:tnLst></p:timing>"#
|
||||
);
|
||||
xml.insert_str(pos, &timing);
|
||||
}
|
||||
xml.into_bytes()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ShapeOwner {
|
||||
Sp,
|
||||
CxnSp,
|
||||
Pic,
|
||||
}
|
||||
|
||||
/// Returns the owning shape kind and closing-tag byte offset for a `<p:cNvPr id="…">` at
|
||||
/// `start..after`, or `None` if it belongs to a non-shape container (`<p:grpSp>`,
|
||||
/// `<p:graphicFrame>`) or would cross into another shape.
|
||||
fn owning_shape_end(xml: &str, start: usize, after: usize) -> Option<(ShapeOwner, usize)> {
|
||||
let before = &xml[..start];
|
||||
let (nv_pos, owner) = [(ShapeOwner::Sp, "<p:nvSpPr>"), (ShapeOwner::CxnSp, "<p:nvCxnSpPr>"), (ShapeOwner::Pic, "<p:nvPicPr>")]
|
||||
.into_iter()
|
||||
.filter_map(|(owner, tag)| before.rfind(tag).map(|pos| (pos, owner)))
|
||||
.max_by_key(|(pos, _)| *pos)?;
|
||||
let between = &before[nv_pos..];
|
||||
if ["<p:nvGrpSpPr>", "<p:nvGraphicFramePr>", "</p:nvSpPr>", "</p:nvCxnSpPr>", "</p:nvPicPr>"].iter().any(|t| between.contains(t)) {
|
||||
return None;
|
||||
}
|
||||
let close_tag = match owner {
|
||||
ShapeOwner::Sp => "</p:sp>",
|
||||
ShapeOwner::CxnSp => "</p:cxnSp>",
|
||||
ShapeOwner::Pic => "</p:pic>",
|
||||
};
|
||||
let end_rel = xml[after..].find(close_tag)?;
|
||||
let span = &xml[after..after + end_rel];
|
||||
if ["<p:sp>", "<p:sp ", "<p:cxnSp>", "<p:cxnSp ", "<p:pic>", "<p:pic ", "<p:grpSp>", "<p:grpSp ", "<p:graphicFrame>", "<p:graphicFrame "]
|
||||
.iter()
|
||||
.any(|t| span.contains(t))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((owner, after + end_rel))
|
||||
}
|
||||
|
||||
fn patch_pic_grp_fill(xml_bytes: &[u8], spids: &std::collections::HashSet<u32>) -> Vec<u8> {
|
||||
let Ok(mut xml) = String::from_utf8(xml_bytes.to_vec()) else {
|
||||
return xml_bytes.to_vec();
|
||||
};
|
||||
for &spid in spids {
|
||||
let needle = format!(r#"<p:cNvPr id="{spid}""#);
|
||||
let mut search_from = 0;
|
||||
while let Some(rel) = xml[search_from..].find(&needle) {
|
||||
let start = search_from + rel;
|
||||
let after = start + needle.len();
|
||||
let boundary_ok = xml.as_bytes().get(after).is_some_and(|b| matches!(b, b' ' | b'/' | b'>'));
|
||||
if boundary_ok
|
||||
&& let Some((ShapeOwner::Pic, pic_end)) = owning_shape_end(&xml, start, after)
|
||||
&& let Some(sp_pr_rel) = xml[after..pic_end].find("<p:spPr>")
|
||||
{
|
||||
let sp_pr_start = after + sp_pr_rel + "<p:spPr>".len();
|
||||
if let Some(sp_pr_end_rel) = xml[sp_pr_start..pic_end].find("</p:spPr>") {
|
||||
let sp_pr_end = sp_pr_start + sp_pr_end_rel;
|
||||
let inner = &xml[sp_pr_start..sp_pr_end];
|
||||
if !inner.contains("<a:grpFill") {
|
||||
let insert_rel = ["<a:ln", "<a:effectLst", "<a:effectDag", "<a:scene3d", "<a:sp3d", "<a:extLst"]
|
||||
.iter()
|
||||
.filter_map(|tag| inner.find(tag))
|
||||
.min()
|
||||
.unwrap_or(sp_pr_end_rel);
|
||||
xml.insert_str(sp_pr_start + insert_rel, "<a:grpFill/>");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
search_from = after;
|
||||
}
|
||||
}
|
||||
xml.into_bytes()
|
||||
}
|
||||
|
||||
fn collect_large_geom_adjs(shapes: &[Shape]) -> Vec<(u32, &[f64])> {
|
||||
let mut out = Vec::new();
|
||||
assign_spids(shapes, |spid, s| {
|
||||
if let deckcraft_model::Geom::Preset { adj, .. } = &s.geom
|
||||
&& adj.iter().any(|v| v.is_finite() && (v.round() < -2.0e9 || v.round() > 2.0e9))
|
||||
{
|
||||
out.push((spid, adj.as_slice()));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn patch_shape_av_lst(xml: &mut String, after: usize, shape_end: usize, adj: &[f64]) {
|
||||
let Some(av_rel) = xml[after..shape_end].find("<a:avLst>") else { return };
|
||||
let av_start = after + av_rel + "<a:avLst>".len();
|
||||
let Some(av_end_rel) = xml[av_start..shape_end].find("</a:avLst>") else { return };
|
||||
let mut av_end = av_start + av_end_rel;
|
||||
for (i, &v) in adj.iter().take(16).enumerate() {
|
||||
if !v.is_finite() || (v.round() >= -2.0e9 && v.round() <= 2.0e9) {
|
||||
continue;
|
||||
}
|
||||
let clamped = v.round().clamp(-2.0e9, 2.0e9) as i64;
|
||||
let actual = v.round() as i64;
|
||||
let single_name = format!(r#"<a:gd name="adj" fmla="val {clamped}"/>"#);
|
||||
let idx_name = format!(r#"<a:gd name="adj{}" fmla="val {clamped}"/>"#, i + 1);
|
||||
let (target, repl) = if i == 0 && xml[av_start..av_end].contains(&single_name) {
|
||||
(single_name, format!(r#"<a:gd name="adj" fmla="val {actual}"/>"#))
|
||||
} else {
|
||||
(idx_name, format!(r#"<a:gd name="adj{}" fmla="val {actual}"/>"#, i + 1))
|
||||
};
|
||||
if let Some(rel) = xml[av_start..av_end].find(&target) {
|
||||
let pos = av_start + rel;
|
||||
xml.replace_range(pos..pos + target.len(), &repl);
|
||||
av_end = av_end + repl.len() - target.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn patch_large_geom_adjs(xml_bytes: &[u8], adjs: &[(u32, &[f64])]) -> Vec<u8> {
|
||||
let Ok(mut xml) = String::from_utf8(xml_bytes.to_vec()) else {
|
||||
return xml_bytes.to_vec();
|
||||
};
|
||||
for &(spid, adj) in adjs {
|
||||
let needle = format!(r#"<p:cNvPr id="{spid}""#);
|
||||
let mut search_from = 0;
|
||||
while let Some(rel) = xml[search_from..].find(&needle) {
|
||||
let start = search_from + rel;
|
||||
let after = start + needle.len();
|
||||
if xml.as_bytes().get(after).is_some_and(|b| matches!(b, b' ' | b'/' | b'>'))
|
||||
&& let Some((_, shape_end)) = owning_shape_end(&xml, start, after)
|
||||
{
|
||||
patch_shape_av_lst(&mut xml, after, shape_end, adj);
|
||||
break;
|
||||
}
|
||||
search_from = after;
|
||||
}
|
||||
}
|
||||
xml.into_bytes()
|
||||
}
|
||||
|
||||
fn patch_exported_slides(p: &Presentation, bytes: Vec<u8>) -> Result<Vec<u8>, PptxError> {
|
||||
let slide_media: Vec<Vec<(u32, &deckcraft_model::MediaClip)>> = p.slides.iter().map(|s| collect_export_media(&s.shapes)).collect();
|
||||
let slide_grp_pics: Vec<std::collections::HashSet<u32>> = p.slides.iter().map(|s| collect_grp_fill_pic_spids(&s.shapes)).collect();
|
||||
let slide_adjs: Vec<Vec<(u32, &[f64])>> = p.slides.iter().map(|s| collect_large_geom_adjs(&s.shapes)).collect();
|
||||
if slide_media.iter().all(Vec::is_empty) && slide_grp_pics.iter().all(std::collections::HashSet::is_empty) && slide_adjs.iter().all(Vec::is_empty)
|
||||
{
|
||||
return Ok(bytes);
|
||||
}
|
||||
let pkg = craft_opc::Package::open(&bytes, &craft_pptx::LIMITS).map_err(|e| PptxError::Write(e.to_string()))?;
|
||||
let root_rels = pkg.rels("");
|
||||
let pres_path = root_rels.first("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into());
|
||||
let pres_rels = pkg.rels(&pres_path);
|
||||
let mut patches: std::collections::HashMap<String, Vec<u8>> = std::collections::HashMap::new();
|
||||
if let Some(pres_bytes) = pkg.get(&pres_path)
|
||||
&& let Ok(pres_el) = craft_drawingml::xmlx::parse(pres_bytes)
|
||||
&& let Some(list) = pres_el.child(craft_xml::Local("sldIdLst"))
|
||||
{
|
||||
for (i, s) in list.children(craft_xml::Local("sldId")).enumerate() {
|
||||
let media = slide_media.get(i).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let grp_pics = slide_grp_pics.get(i);
|
||||
let adjs = slide_adjs.get(i).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let need_grp = grp_pics.is_some_and(|g| !g.is_empty());
|
||||
if media.is_empty() && !need_grp && adjs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid))
|
||||
&& let Some(sb) = pkg.get(target)
|
||||
{
|
||||
let mut patched = if media.is_empty() { sb.to_vec() } else { patch_slide_media_timing(sb, media) };
|
||||
if let Some(g) = grp_pics
|
||||
&& !g.is_empty()
|
||||
{
|
||||
patched = patch_pic_grp_fill(&patched, g);
|
||||
}
|
||||
if !adjs.is_empty() {
|
||||
patched = patch_large_geom_adjs(&patched, adjs);
|
||||
}
|
||||
patches.insert(target.to_string(), patched);
|
||||
}
|
||||
}
|
||||
}
|
||||
if patches.is_empty() {
|
||||
return Ok(bytes);
|
||||
}
|
||||
let entries: Vec<(String, Vec<u8>)> = pkg
|
||||
.names()
|
||||
.filter_map(|name| {
|
||||
let data = patches.remove(name).or_else(|| pkg.get(name).map(<[u8]>::to_vec))?;
|
||||
Some((name.to_string(), data))
|
||||
})
|
||||
.collect();
|
||||
craft_opc::zip_entries(&entries).map_err(|e| PptxError::Write(e.to_string()))
|
||||
}
|
||||
|
||||
/// Write a `.pptx` package.
|
||||
pub fn export(p: &Presentation) -> Result<Vec<u8>, PptxError> {
|
||||
write::export(p, write::CT_PRES)
|
||||
check_table_caps(p)?;
|
||||
let bytes = craft_pptx::export(&convert::pres_to_craft(p), &DeckDefaults)?;
|
||||
patch_exported_slides(p, bytes)
|
||||
}
|
||||
|
||||
/// Write a package for `ext`: `potx` (template) and `ppsx` (slide show) differ from `pptx` only in
|
||||
/// the main part's content type.
|
||||
pub fn export_as(p: &Presentation, ext: &str) -> Result<Vec<u8>, PptxError> {
|
||||
let ct = match ext {
|
||||
"potx" => write::CT_TEMPLATE,
|
||||
"ppsx" => write::CT_SHOW,
|
||||
_ => write::CT_PRES,
|
||||
};
|
||||
write::export(p, ct)
|
||||
}
|
||||
|
||||
/// Content type for a file name's extension.
|
||||
pub(crate) fn mime_for(name: &str) -> &'static str {
|
||||
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
|
||||
match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" | "jpe" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"bmp" => "image/bmp",
|
||||
"tif" | "tiff" => "image/tiff",
|
||||
"svg" => "image/svg+xml",
|
||||
"emf" => "image/x-emf",
|
||||
"wmf" => "image/x-wmf",
|
||||
"webp" => "image/webp",
|
||||
"mp4" | "m4v" => "video/mp4",
|
||||
"mov" => "video/quicktime",
|
||||
"wmv" => "video/x-ms-wmv",
|
||||
"avi" => "video/x-msvideo",
|
||||
"webm" => "video/webm",
|
||||
"mp3" => "audio/mpeg",
|
||||
"wav" => "audio/wav",
|
||||
"m4a" => "audio/mp4",
|
||||
"wma" => "audio/x-ms-wma",
|
||||
"ogg" => "audio/ogg",
|
||||
"flac" => "audio/flac",
|
||||
"glb" => "model/gltf-binary",
|
||||
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"fntdata" => "application/x-fontdata",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
check_table_caps(p)?;
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let bytes = craft_pptx::export_as(&convert::pres_to_craft(p), &DeckDefaults, &ext)?;
|
||||
patch_exported_slides(p, bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -228,4 +956,69 @@ mod table_direction_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_cap_table_export_is_refused() {
|
||||
let mut p = defaults::new_presentation(None);
|
||||
let mut t = Table::new(1, 2, 200.0, 30.0);
|
||||
t.rows.resize_with(deckcraft_model::table::MAX_CELLS / 2 + 1, || deckcraft_model::table::Row {
|
||||
height: 20.0,
|
||||
cells: vec![Cell::new("x"), Cell::new("y")],
|
||||
});
|
||||
let shape = Shape { id: ShapeId(p.alloc_id().expect("id")), kind: ShapeKind::Table(t), ..Default::default() };
|
||||
Arc::make_mut(&mut p.slides[0]).shapes.push(shape);
|
||||
let err = crate::export(&p).expect_err("over-cap table must be refused");
|
||||
assert!(matches!(err, crate::PptxError::Unsupported(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_cap_table_on_notes_and_handout_master_is_refused() {
|
||||
let mut t = Table::new(1, 2, 200.0, 30.0);
|
||||
t.rows.resize_with(deckcraft_model::table::MAX_CELLS / 2 + 1, || deckcraft_model::table::Row {
|
||||
height: 20.0,
|
||||
cells: vec![Cell::new("x"), Cell::new("y")],
|
||||
});
|
||||
let mut p_notes = defaults::new_presentation(None);
|
||||
let shape = Shape { id: ShapeId(p_notes.alloc_id().expect("id")), kind: ShapeKind::Table(t.clone()), ..Default::default() };
|
||||
p_notes.notes_master = Some(Arc::new(deckcraft_model::Master { name: "Notes".into(), shapes: vec![shape], ..Default::default() }));
|
||||
assert!(matches!(crate::export(&p_notes), Err(crate::PptxError::Unsupported(_))));
|
||||
|
||||
let mut p_handout = defaults::new_presentation(None);
|
||||
let shape = Shape { id: ShapeId(p_handout.alloc_id().expect("id")), kind: ShapeKind::Table(t), ..Default::default() };
|
||||
p_handout.handout_master = Some(Arc::new(deckcraft_model::Master { name: "Handout".into(), shapes: vec![shape], ..Default::default() }));
|
||||
assert!(matches!(crate::export(&p_handout), Err(crate::PptxError::Unsupported(_))));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shape_owner_scoping_tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn patch_pic_grp_fill_does_not_cross_into_following_pic() {
|
||||
let xml = concat!(
|
||||
r#"<p:sp><p:nvSpPr><p:cNvPr id="5" name="Box"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr/></p:sp>"#,
|
||||
r#"<p:pic><p:nvPicPr><p:cNvPr id="6" name="Pic"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr><p:spPr><a:ln/></p:spPr></p:pic>"#,
|
||||
);
|
||||
let spids = HashSet::from([5]);
|
||||
let out = String::from_utf8(super::patch_pic_grp_fill(xml.as_bytes(), &spids)).expect("utf8");
|
||||
assert!(!out.contains("<a:grpFill/>"), "non-pic owner id=5 must not patch pic id=6: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_large_geom_adjs_does_not_leak_from_group_into_child_shape() {
|
||||
let xml = concat!(
|
||||
r#"<p:grpSp><p:nvGrpSpPr><p:cNvPr id="10" name="Group"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>"#,
|
||||
r#"<p:sp><p:nvSpPr><p:cNvPr id="11" name="Child"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>"#,
|
||||
r#"<p:spPr><a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 2000000000"/></a:avLst></a:prstGeom></p:spPr></p:sp>"#,
|
||||
r#"</p:grpSp>"#,
|
||||
);
|
||||
let adjs = [(10_u32, &[3_000_000_000.0_f64][..])];
|
||||
let out = String::from_utf8(super::patch_large_geom_adjs(xml.as_bytes(), &adjs)).expect("utf8");
|
||||
assert!(out.contains(r#"fmla="val 2000000000""#), "group id=10 must not patch child id=11: {out}");
|
||||
|
||||
let child_adjs = [(11_u32, &[3_000_000_000.0_f64][..])];
|
||||
let patched = String::from_utf8(super::patch_large_geom_adjs(xml.as_bytes(), &child_adjs)).expect("utf8");
|
||||
assert!(patched.contains(r#"fmla="val 3000000000""#), "child id=11 should be patched: {patched}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,449 +0,0 @@
|
||||
//! Mappings between our transition / animation ids and PresentationML elements and preset
|
||||
//! numbers, shared by the reader and the writer.
|
||||
|
||||
use deckcraft_model::anim::{ANIMATIONS, AnimClass};
|
||||
|
||||
use crate::xml::{A, El, W};
|
||||
|
||||
/// (our kind, namespace prefix, element) for transitions that map one-to-one.
|
||||
const SIMPLE: &[(&str, &str, &str)] =
|
||||
&[("dissolve", "p", "dissolve"), ("random", "p", "random"), ("honeycomb", "p14", "honeycomb"), ("flash", "p14", "flash")];
|
||||
|
||||
/// Read a transition effect element → (kind, option). `None` for effects we don't model.
|
||||
pub fn transition_from_xml(e: &El) -> Option<(String, String)> {
|
||||
let (k, o) = transition_from_xml_raw(e)?;
|
||||
// Kinds without options keep none.
|
||||
let has_opts = deckcraft_model::anim::TRANSITIONS.iter().find(|t| t.0 == k).is_none_or(|t| !t.4.is_empty());
|
||||
Some((k, if has_opts { o } else { String::new() }))
|
||||
}
|
||||
|
||||
/// Preset transitions (`p15:prstTrans`) whose "Left" option PowerPoint writes with `invX="1"`
|
||||
/// (the others write it for "Right"), as observed on PowerPoint's own files.
|
||||
const INVX_LEFT: &[&str] = &["wind", "airplane", "origami"];
|
||||
|
||||
fn transition_from_xml_raw(e: &El) -> Option<(String, String)> {
|
||||
// Defaults are what PowerPoint leaves out: e.g. it writes Push Left as `<p:push/>`.
|
||||
let dir = |d: &str| e.attr("dir").unwrap_or(d).to_string();
|
||||
let k = |s: &str| s.to_string();
|
||||
Some(match e.local() {
|
||||
"fade" => (k("fade"), if e.bool("thruBlk") == Some(true) { k("throughBlack") } else { k("smoothly") }),
|
||||
"cut" => (k("cut"), if e.bool("thruBlk") == Some(true) { k("throughBlack") } else { String::new() }),
|
||||
"push" => (k("push"), dir("l")),
|
||||
"wipe" => (k("wipe"), dir("l")),
|
||||
// Diagonal wipes.
|
||||
"strips" => (k("wipe"), dir("lu")),
|
||||
"split" => {
|
||||
let o = e.attr("orient").unwrap_or("horz");
|
||||
let d = e.attr("dir").unwrap_or("out");
|
||||
(k("split"), format!("{o}{}", if d == "in" { "In" } else { "Out" }))
|
||||
}
|
||||
"randomBar" => (k("randomBar"), dir("horz")),
|
||||
"circle" => (k("shape"), k("circle")),
|
||||
"diamond" => (k("shape"), k("diamond")),
|
||||
"plus" => (k("shape"), k("plus")),
|
||||
// Shape In / Out (the slide zooming in a box).
|
||||
"zoom" => (k("shape"), if e.attr("dir") == Some("in") { k("in") } else { k("out") }),
|
||||
// The Zoom transition, and its Zoom and Rotate option.
|
||||
"warp" => (k("zoom"), if e.attr("dir") == Some("in") { k("in") } else { k("out") }),
|
||||
"newsflash" => (k("zoom"), k("rotate")),
|
||||
"pull" => (k("uncover"), dir("l")),
|
||||
"cover" => (k("cover"), dir("l")),
|
||||
"checker" => (k("checker"), dir("horz")),
|
||||
"blinds" => (k("blinds"), dir("horz")),
|
||||
"comb" => (k("comb"), dir("horz")),
|
||||
"wheel" => (k("clock"), k("clockwise")),
|
||||
"wheelReverse" => (k("clock"), k("counterClockwise")),
|
||||
"wedge" => (k("clock"), k("wedge")),
|
||||
"vortex" => (k("vortex"), dir("l")),
|
||||
"switch" => (k("switch"), dir("r")),
|
||||
"flip" => (k("flip"), dir("r")),
|
||||
"ripple" => (k("ripple"), dir("center")),
|
||||
"doors" => (k("doors"), dir("horz")),
|
||||
"window" => (k("window"), dir("horz")),
|
||||
"ferris" => (k("ferris"), dir("l")),
|
||||
"gallery" => (k("gallery"), dir("l")),
|
||||
"conveyor" => (k("conveyor"), dir("l")),
|
||||
"pan" => (k("pan"), dir("l")),
|
||||
"glitter" => {
|
||||
let d = dir("l");
|
||||
if e.attr("pattern") == Some("hexagon") { (k("glitter"), format!("hex{}", d.to_ascii_uppercase())) } else { (k("glitter"), d) }
|
||||
}
|
||||
"shred" => {
|
||||
// `crush` is what DeckCraft wrote before it knew PowerPoint's `rectangle`.
|
||||
let particles = matches!(e.attr("pattern"), Some("rectangle" | "crush"));
|
||||
let out = e.attr("dir") == Some("out");
|
||||
(k("shred"), format!("{}{}", if particles { "particles" } else { "strips" }, if out { "Out" } else { "In" }))
|
||||
}
|
||||
"reveal" => {
|
||||
let black = e.bool("thruBlk") == Some(true);
|
||||
let right = e.attr("dir") == Some("r");
|
||||
(k("reveal"), format!("{}{}", if black { "black" } else { "smoothly" }, if right { "Right" } else { "Left" }))
|
||||
}
|
||||
"flythrough" => {
|
||||
let out = e.attr("dir") == Some("out");
|
||||
let b = e.bool("hasBounce") == Some(true);
|
||||
(k("flythrough"), format!("{}{}", if out { "out" } else { "in" }, if b { "Bounce" } else { "" }))
|
||||
}
|
||||
"prism" => {
|
||||
let content = e.bool("isContent") == Some(true);
|
||||
let inv = e.bool("isInverted") == Some(true);
|
||||
let kind = match (content, inv) {
|
||||
(false, false) => "cube",
|
||||
(false, true) => "box",
|
||||
(true, false) => "rotate",
|
||||
(true, true) => "orbit",
|
||||
};
|
||||
(k(kind), dir("l"))
|
||||
}
|
||||
"prstTrans" => {
|
||||
let prst = e.attr("prst").unwrap_or("fallOver");
|
||||
let inv = e.bool("invX") == Some(true);
|
||||
if prst == "pageCurlSingle" {
|
||||
return Some((k("pageCurlDouble"), if inv { k("singleR") } else { k("singleL") }));
|
||||
}
|
||||
let known = deckcraft_model::anim::TRANSITIONS.iter().any(|t| t.0 == prst);
|
||||
if !known {
|
||||
return None;
|
||||
}
|
||||
let left = if INVX_LEFT.contains(&prst) { inv } else { !inv };
|
||||
(k(prst), if left { k("l") } else { k("r") })
|
||||
}
|
||||
"morph" => (
|
||||
k("morph"),
|
||||
match e.attr("option") {
|
||||
Some("byWord") => k("words"),
|
||||
Some("byChar") => k("characters"),
|
||||
_ => k("objects"),
|
||||
},
|
||||
),
|
||||
other => (k(SIMPLE.iter().find(|s| s.2 == other)?.0), String::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Write the effect element for a transition. Returns the namespace prefix it needs
|
||||
/// (`p`, `p14`, `p15`, `p159`), or `None` when the kind is unknown.
|
||||
pub fn transition_to_xml(w: &mut W, kind: &str, option: &str) -> Option<&'static str> {
|
||||
let lr = |d: &'static str| match option {
|
||||
"l" | "r" => option.to_string(),
|
||||
_ => d.to_string(),
|
||||
};
|
||||
let lrud = |d: &'static str| match option {
|
||||
"l" | "r" | "u" | "d" => option.to_string(),
|
||||
_ => d.to_string(),
|
||||
};
|
||||
let hv = |d: &'static str| match option {
|
||||
"horz" | "vert" => option.to_string(),
|
||||
_ => d.to_string(),
|
||||
};
|
||||
let eight = |d: &'static str| match option {
|
||||
"l" | "r" | "u" | "d" | "lu" | "ru" | "ld" | "rd" => option.to_string(),
|
||||
_ => d.to_string(),
|
||||
};
|
||||
match kind {
|
||||
"fade" => w.empty("p:fade", A::new().t("thruBlk", option == "throughBlack")),
|
||||
"cut" => w.empty("p:cut", A::new().t("thruBlk", option == "throughBlack")),
|
||||
"push" => w.empty("p:push", A::new().a("dir", lrud("u"))),
|
||||
"wipe" => match option {
|
||||
"lu" | "ru" | "ld" | "rd" => w.empty("p:strips", A::new().a("dir", option)),
|
||||
_ => w.empty("p:wipe", A::new().a("dir", lrud("r"))),
|
||||
},
|
||||
"split" => {
|
||||
let (o, d) = match option {
|
||||
"vertIn" => ("vert", "in"),
|
||||
"vertOut" => ("vert", "out"),
|
||||
"horzIn" => ("horz", "in"),
|
||||
_ => ("horz", "out"),
|
||||
};
|
||||
w.empty("p:split", A::new().a("orient", o).a("dir", d));
|
||||
}
|
||||
"randomBar" => w.empty("p:randomBar", A::new().a("dir", hv("vert"))),
|
||||
"shape" => match option {
|
||||
"diamond" => w.empty0("p:diamond"),
|
||||
"plus" => w.empty0("p:plus"),
|
||||
"in" | "out" => w.empty("p:zoom", A::new().a("dir", option)),
|
||||
_ => w.empty0("p:circle"),
|
||||
},
|
||||
"zoom" => match option {
|
||||
"rotate" => w.empty0("p:newsflash"),
|
||||
_ => {
|
||||
w.empty("p14:warp", A::new().a("dir", if option == "out" { "out" } else { "in" }));
|
||||
return Some("p14");
|
||||
}
|
||||
},
|
||||
"uncover" => w.empty("p:pull", A::new().a("dir", eight("l"))),
|
||||
"cover" => w.empty("p:cover", A::new().a("dir", eight("l"))),
|
||||
"checker" => w.empty("p:checker", A::new().a("dir", hv("horz"))),
|
||||
"blinds" => w.empty("p:blinds", A::new().a("dir", hv("horz"))),
|
||||
"comb" => w.empty("p:comb", A::new().a("dir", hv("horz"))),
|
||||
"clock" => match option {
|
||||
"counterClockwise" => {
|
||||
w.empty("p14:wheelReverse", A::new().a("spokes", 1));
|
||||
return Some("p14");
|
||||
}
|
||||
"wedge" => w.empty0("p:wedge"),
|
||||
_ => w.empty("p:wheel", A::new().a("spokes", 1)),
|
||||
},
|
||||
"dissolve" => w.empty0("p:dissolve"),
|
||||
"random" => w.empty0("p:random"),
|
||||
"honeycomb" => {
|
||||
w.empty0("p14:honeycomb");
|
||||
return Some("p14");
|
||||
}
|
||||
"flash" => {
|
||||
w.empty0("p14:flash");
|
||||
return Some("p14");
|
||||
}
|
||||
"vortex" => {
|
||||
w.empty("p14:vortex", A::new().a("dir", lrud("l")));
|
||||
return Some("p14");
|
||||
}
|
||||
"glitter" => {
|
||||
let hex = option.starts_with("hex");
|
||||
let d = option.trim_start_matches("hex").to_ascii_lowercase();
|
||||
let d = if matches!(d.as_str(), "l" | "r" | "u" | "d") { d } else { "l".to_string() };
|
||||
w.empty("p14:glitter", A::new().a("dir", d).o("pattern", hex.then_some("hexagon")));
|
||||
return Some("p14");
|
||||
}
|
||||
"switch" | "flip" | "gallery" | "conveyor" | "ferris" => {
|
||||
let name = match kind {
|
||||
"switch" => "p14:switch",
|
||||
"flip" => "p14:flip",
|
||||
"gallery" => "p14:gallery",
|
||||
"conveyor" => "p14:conveyor",
|
||||
_ => "p14:ferris",
|
||||
};
|
||||
w.empty(name, A::new().a("dir", lr("l")));
|
||||
return Some("p14");
|
||||
}
|
||||
"ripple" => {
|
||||
let d = match option {
|
||||
"lu" | "ru" | "ld" | "rd" => option,
|
||||
_ => "center",
|
||||
};
|
||||
w.empty("p14:ripple", A::new().a("dir", d));
|
||||
return Some("p14");
|
||||
}
|
||||
"doors" | "window" => {
|
||||
let name = if kind == "doors" { "p14:doors" } else { "p14:window" };
|
||||
w.empty(name, A::new().a("dir", hv("vert")));
|
||||
return Some("p14");
|
||||
}
|
||||
"pan" => {
|
||||
w.empty("p14:pan", A::new().a("dir", lrud("d")));
|
||||
return Some("p14");
|
||||
}
|
||||
"shred" => {
|
||||
let particles = option.starts_with("particles");
|
||||
w.empty(
|
||||
"p14:shred",
|
||||
A::new().a("pattern", if particles { "rectangle" } else { "strip" }).a("dir", if option.ends_with("Out") { "out" } else { "in" }),
|
||||
);
|
||||
return Some("p14");
|
||||
}
|
||||
"reveal" => {
|
||||
w.empty("p14:reveal", A::new().t("thruBlk", option.starts_with("black")).a("dir", if option.ends_with("Right") { "r" } else { "l" }));
|
||||
return Some("p14");
|
||||
}
|
||||
"flythrough" => {
|
||||
w.empty(
|
||||
"p14:flythrough",
|
||||
A::new().a("dir", if option.starts_with("out") { "out" } else { "in" }).t("hasBounce", option.ends_with("Bounce")),
|
||||
);
|
||||
return Some("p14");
|
||||
}
|
||||
"cube" | "box" | "rotate" | "orbit" => {
|
||||
w.empty(
|
||||
"p14:prism",
|
||||
A::new().a("dir", lrud("l")).t("isContent", matches!(kind, "rotate" | "orbit")).t("isInverted", matches!(kind, "box" | "orbit")),
|
||||
);
|
||||
return Some("p14");
|
||||
}
|
||||
"pageCurlDouble" if option.starts_with("single") => {
|
||||
w.empty("p15:prstTrans", A::new().a("prst", "pageCurlSingle").t("invX", option == "singleR"));
|
||||
return Some("p15");
|
||||
}
|
||||
"fallOver" | "drape" | "curtains" | "wind" | "prestige" | "fracture" | "crush" | "peelOff" | "pageCurlDouble" | "airplane" | "origami" => {
|
||||
let inv = if INVX_LEFT.contains(&kind) { option == "l" } else { option == "r" };
|
||||
w.empty("p15:prstTrans", A::new().a("prst", kind).t("invX", inv));
|
||||
return Some("p15");
|
||||
}
|
||||
"morph" => {
|
||||
let o = match option {
|
||||
"words" => "byWord",
|
||||
"characters" => "byChar",
|
||||
_ => "byObject",
|
||||
};
|
||||
w.empty("p159:morph", A::new().a("option", o));
|
||||
return Some("p159");
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some("p")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Animations
|
||||
|
||||
/// Effect options ↔ preset subtypes.
|
||||
const SUBTYPES: &[(&str, &[(&str, u32)])] = &[
|
||||
("fly", DIR8),
|
||||
("flyOut", DIR8),
|
||||
("peek", DIR4),
|
||||
("wipe", DIR4),
|
||||
("wipeOut", DIR4),
|
||||
("strips", &[("lu", 9), ("ru", 3), ("ld", 12), ("rd", 6)]),
|
||||
("split", SPLIT),
|
||||
("splitOut", SPLIT),
|
||||
("zoom", INOUT),
|
||||
("zoomOut", INOUT),
|
||||
("box", INOUT),
|
||||
("circle", INOUT),
|
||||
("diamond", INOUT),
|
||||
("randomBars", HV),
|
||||
("randomBarsOut", HV),
|
||||
("blinds", HV),
|
||||
("swivel", HV),
|
||||
("swivelOut", HV),
|
||||
("blindsOut", HV),
|
||||
("boxOut", INOUT),
|
||||
("checkerboardOut", &[("across", 10), ("down", 5)]),
|
||||
("diamondOut", INOUT),
|
||||
("peekOut", DIR4),
|
||||
("stripsOut", &[("lu", 9), ("ru", 3), ("ld", 12), ("rd", 6)]),
|
||||
("checkerboard", &[("across", 10), ("down", 5)]),
|
||||
("wheel", WHEEL),
|
||||
("wheelOut", WHEEL),
|
||||
("float", &[("u", 0), ("d", 4)]),
|
||||
("floatOut", &[("u", 0), ("d", 4)]),
|
||||
(
|
||||
"shape",
|
||||
&[("circleIn", 16), ("circleOut", 32), ("boxIn", 16), ("boxOut", 32), ("diamondIn", 16), ("diamondOut", 32), ("plusIn", 16), ("plusOut", 32)],
|
||||
),
|
||||
("shapeOut", INOUT_SHAPE),
|
||||
("lines", &[("down", 4), ("up", 1), ("right", 2), ("left", 8)]),
|
||||
("arcs", &[("down", 4), ("up", 1), ("right", 2), ("left", 8)]),
|
||||
("turns", &[("down", 4), ("up", 1), ("right", 2), ("left", 8)]),
|
||||
];
|
||||
const DIR8: &[(&str, u32)] = &[("b", 4), ("lb", 12), ("l", 8), ("lt", 9), ("t", 1), ("rt", 3), ("r", 2), ("rb", 6)];
|
||||
const DIR4: &[(&str, u32)] = &[("b", 4), ("l", 8), ("t", 1), ("r", 2)];
|
||||
const SPLIT: &[(&str, u32)] = &[("horzIn", 21), ("horzOut", 42), ("vertIn", 26), ("vertOut", 37)];
|
||||
const INOUT: &[(&str, u32)] = &[("in", 16), ("out", 32)];
|
||||
const INOUT_SHAPE: &[(&str, u32)] = &[("circleIn", 16), ("circleOut", 32)];
|
||||
const HV: &[(&str, u32)] = &[("horz", 10), ("vert", 5)];
|
||||
const WHEEL: &[(&str, u32)] = &[("1", 1), ("2", 2), ("3", 3), ("4", 4), ("8", 8)];
|
||||
|
||||
pub fn option_from_subtype(effect: &str, sub: u32) -> String {
|
||||
SUBTYPES.iter().find(|(e, _)| *e == effect).and_then(|(_, m)| m.iter().find(|(_, s)| *s == sub)).map(|(o, _)| o.to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn subtype_from_option(effect: &str, option: &str) -> Option<u32> {
|
||||
SUBTYPES.iter().find(|(e, _)| *e == effect).and_then(|(_, m)| m.iter().find(|(o, _)| *o == option)).map(|(_, s)| *s)
|
||||
}
|
||||
|
||||
/// Our effect id for a preset (first match in [`ANIMATIONS`]).
|
||||
pub fn effect_for_preset(class: AnimClass, preset: u32) -> Option<&'static str> {
|
||||
ANIMATIONS.iter().find(|a| a.2 == class && a.3 == preset && a.0 != "customPath").map(|a| a.0)
|
||||
}
|
||||
|
||||
/// Effect used for presets we don't know.
|
||||
pub fn fallback_effect(class: AnimClass) -> &'static str {
|
||||
match class {
|
||||
AnimClass::Entrance => "fade",
|
||||
AnimClass::Exit => "fadeOut",
|
||||
AnimClass::Emphasis => "pulse",
|
||||
AnimClass::Path => "customPath",
|
||||
AnimClass::Media => "play",
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset id to write for an animation.
|
||||
pub fn preset_for(a: &deckcraft_model::Animation) -> u32 {
|
||||
// Float Down is PowerPoint's preset 47 (Float Up is 42).
|
||||
if matches!(a.effect.as_str(), "float" | "floatOut") && a.option == "d" {
|
||||
return 47;
|
||||
}
|
||||
if let Some(p) = a.preset_id {
|
||||
let consistent = match effect_for_preset(a.class, p) {
|
||||
Some(e) => e == a.effect,
|
||||
None => a.effect == fallback_effect(a.class),
|
||||
};
|
||||
if consistent {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
match deckcraft_model::anim::animation_info(&a.effect, a.class) {
|
||||
Some(info) if info.2 == a.class => info.3,
|
||||
_ => match a.class {
|
||||
AnimClass::Entrance | AnimClass::Exit => 10,
|
||||
AnimClass::Emphasis => 26,
|
||||
AnimClass::Path => 0,
|
||||
AnimClass::Media => 1,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::xml::parse;
|
||||
|
||||
/// #147: these exits, with their directions, fell back to a plain fade (PowerPoint's ids).
|
||||
#[test]
|
||||
fn exit_presets_import_as_their_own_effects() {
|
||||
for (preset, sub, effect, option) in [
|
||||
(3, 10, "blindsOut", "horz"),
|
||||
(4, 32, "boxOut", "out"),
|
||||
(5, 5, "checkerboardOut", "down"),
|
||||
(8, 16, "diamondOut", "in"),
|
||||
(12, 4, "peekOut", "b"),
|
||||
(18, 6, "stripsOut", "rd"),
|
||||
(37, 0, "sinkDown", ""),
|
||||
(49, 0, "spinnerOut", ""),
|
||||
(55, 0, "contract", ""),
|
||||
] {
|
||||
let e = effect_for_preset(AnimClass::Exit, preset).expect("known exit");
|
||||
assert_eq!((e, option_from_subtype(e, sub).as_str()), (effect, option), "preset {preset}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_transition_kind_round_trips() {
|
||||
for (kind, _, _, _, opts) in deckcraft_model::anim::TRANSITIONS {
|
||||
if *kind == "none" {
|
||||
continue;
|
||||
}
|
||||
let opts: Vec<&str> = if opts.is_empty() { vec![""] } else { opts.to_vec() };
|
||||
for o in opts {
|
||||
let mut w = W::frag();
|
||||
let ns = transition_to_xml(&mut w, kind, o).unwrap_or_else(|| panic!("no xml for {kind}"));
|
||||
assert!(!ns.is_empty());
|
||||
let d = parse(w.s.as_bytes()).unwrap();
|
||||
let (k, opt) = transition_from_xml(&d.root).unwrap_or_else(|| panic!("no read for {kind}"));
|
||||
assert_eq!(k, *kind, "kind for {kind}/{o}");
|
||||
if !o.is_empty() {
|
||||
assert_eq!(opt, o, "option for {kind}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtypes() {
|
||||
assert_eq!(subtype_from_option("fly", "b"), Some(4));
|
||||
assert_eq!(option_from_subtype("fly", 8), "l");
|
||||
assert_eq!(option_from_subtype("fade", 0), "");
|
||||
assert_eq!(effect_for_preset(AnimClass::Entrance, 2), Some("fly"));
|
||||
assert_eq!(effect_for_preset(AnimClass::Emphasis, 8), Some("spin"));
|
||||
}
|
||||
|
||||
/// PowerPoint's own ids: Darken is 24 and Desaturate 25 (read back from its saved file).
|
||||
#[test]
|
||||
fn darken_and_desaturate_use_powerpoints_ids() {
|
||||
assert_eq!(effect_for_preset(AnimClass::Emphasis, 24), Some("darken"));
|
||||
assert_eq!(effect_for_preset(AnimClass::Emphasis, 25), Some("desaturate"));
|
||||
for (effect, id) in [("darken", 24), ("desaturate", 25)] {
|
||||
let a = deckcraft_model::Animation { class: AnimClass::Emphasis, effect: effect.into(), ..Default::default() };
|
||||
assert_eq!(preset_for(&a), id, "{effect}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,563 +0,0 @@
|
||||
//! Open Packaging Conventions: the zip container, part names, relationships and content types.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
use crate::PptxError;
|
||||
use crate::xml::{self, A, W};
|
||||
|
||||
/// Largest single part we decompress (media included).
|
||||
pub const MAX_PART: u64 = 512 * 1024 * 1024;
|
||||
/// Largest XML part we parse.
|
||||
pub const MAX_XML_PART: usize = 96 * 1024 * 1024;
|
||||
/// Total decompressed bytes accepted for one package.
|
||||
pub const MAX_TOTAL: u64 = 2 * 1024 * 1024 * 1024;
|
||||
/// Total bytes we are willing to decompress for one package, counting parts we then discard
|
||||
/// (too large, or failing part-way): bounds inflate work, not just what is kept.
|
||||
pub const MAX_INFLATE_WORK: u64 = 2 * MAX_TOTAL;
|
||||
/// Maximum number of zip entries.
|
||||
pub const MAX_ENTRIES: usize = 50_000;
|
||||
|
||||
pub const NS_A: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";
|
||||
pub const NS_R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
pub const NS_P: &str = "http://schemas.openxmlformats.org/presentationml/2006/main";
|
||||
pub const NS_C: &str = "http://schemas.openxmlformats.org/drawingml/2006/chart";
|
||||
pub const NS_MC: &str = "http://schemas.openxmlformats.org/markup-compatibility/2006";
|
||||
pub const NS_P14: &str = "http://schemas.microsoft.com/office/powerpoint/2010/main";
|
||||
pub const NS_P15: &str = "http://schemas.microsoft.com/office/powerpoint/2012/main";
|
||||
pub const NS_P159: &str = "http://schemas.microsoft.com/office/powerpoint/2015/09/main";
|
||||
pub const NS_A14: &str = "http://schemas.microsoft.com/office/drawing/2010/main";
|
||||
/// Modern (threaded) comments, Office 2018/8 schema.
|
||||
pub const NS_P188: &str = "http://schemas.microsoft.com/office/powerpoint/2018/8/main";
|
||||
|
||||
pub const RT_BASE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
|
||||
pub const RT_MEDIA: &str = "http://schemas.microsoft.com/office/2007/relationships/media";
|
||||
/// A 3-D model part (`.glb`). Office relationship, not an ECMA-376 base type.
|
||||
pub const RT_MODEL3D: &str = "http://schemas.microsoft.com/office/2017/06/relationships/model3d";
|
||||
pub const RT_CORE: &str = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
|
||||
|
||||
/// The files of a package, keyed by normalised part name (no leading slash, lowercase).
|
||||
pub struct Package {
|
||||
parts: HashMap<String, (String, Vec<u8>)>,
|
||||
ct_cache: std::sync::OnceLock<(HashMap<String, String>, HashMap<String, String>)>,
|
||||
}
|
||||
|
||||
impl Package {
|
||||
pub fn open(bytes: &[u8]) -> Result<Self, PptxError> {
|
||||
Self::open_within(bytes, MAX_PART, MAX_TOTAL, MAX_INFLATE_WORK)
|
||||
}
|
||||
/// [`Package::open`] with explicit limits: per part, kept in total, and inflated in total.
|
||||
fn open_within(bytes: &[u8], max_part: u64, max_total: u64, max_work: u64) -> Result<Self, PptxError> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| PptxError::NotPptx(format!("{e}")))?;
|
||||
if zip.len() > MAX_ENTRIES {
|
||||
return Err(PptxError::NotPptx(format!("too many entries ({})", zip.len())));
|
||||
}
|
||||
let mut parts = HashMap::new();
|
||||
let mut total: u64 = 0;
|
||||
let mut work: u64 = 0;
|
||||
for i in 0..zip.len() {
|
||||
if work >= max_work {
|
||||
log::warn!("pptx: decompression budget spent; skipping the remaining {} entries", zip.len() - i);
|
||||
break;
|
||||
}
|
||||
let mut f = match zip.by_index(i) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
log::warn!("pptx: skipping unreadable zip entry {i}: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if f.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = f.name().trim_start_matches('/').to_string();
|
||||
let declared = f.size();
|
||||
if declared > max_part {
|
||||
log::warn!("pptx: skipping oversized part {name} ({declared} bytes)");
|
||||
continue;
|
||||
}
|
||||
let mut data = Vec::with_capacity(declared.min(16 * 1024 * 1024) as usize);
|
||||
let cap = max_part.min(max_total.saturating_sub(total)).min(max_work.saturating_sub(work));
|
||||
let read = (&mut f).take(cap.saturating_add(1)).read_to_end(&mut data);
|
||||
// Charge what was inflated whether or not the part is kept.
|
||||
work = work.saturating_add(data.len() as u64);
|
||||
match read {
|
||||
Ok(_) if data.len() as u64 > cap => {
|
||||
log::warn!("pptx: part {name} exceeds size limits; skipped");
|
||||
continue;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("pptx: could not read {name}: {e}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
total = total.saturating_add(data.len() as u64);
|
||||
// A name kept with `\` would reach code that splits paths on `/`.
|
||||
parts.insert(norm(&name), (name.replace('\\', "/"), data));
|
||||
}
|
||||
Ok(Package { parts, ct_cache: std::sync::OnceLock::new() })
|
||||
}
|
||||
pub fn get(&self, name: &str) -> Option<&[u8]> {
|
||||
self.parts.get(&norm(name)).map(|(_, d)| d.as_slice())
|
||||
}
|
||||
/// An XML part's bytes, when it is within the XML size limit.
|
||||
pub fn xml_bytes(&self, name: &str) -> Option<&[u8]> {
|
||||
let b = self.get(name)?;
|
||||
if b.len() > MAX_XML_PART {
|
||||
log::warn!("pptx: XML part {name} too large");
|
||||
return None;
|
||||
}
|
||||
Some(b)
|
||||
}
|
||||
/// Parse an XML part.
|
||||
pub fn xml(&self, name: &str) -> Option<xml::Doc> {
|
||||
let b = self.get(name)?;
|
||||
if b.len() > MAX_XML_PART {
|
||||
log::warn!("pptx: XML part {name} too large");
|
||||
return None;
|
||||
}
|
||||
match xml::parse(b) {
|
||||
Ok(d) => Some(d),
|
||||
Err(e) => {
|
||||
log::warn!("pptx: {name}: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Relationships of a part (`ppt/slides/slide1.xml` → `ppt/slides/_rels/slide1.xml.rels`).
|
||||
pub fn rels(&self, part: &str) -> Rels {
|
||||
let rp = rels_path(part);
|
||||
let Some(doc) = self.xml(&rp) else { return Rels::default() };
|
||||
rels_of(&doc, part)
|
||||
}
|
||||
/// Content types: (extension defaults, part overrides).
|
||||
pub fn content_type(&self, part: &str) -> Option<String> {
|
||||
let (overrides, defaults) = self.ct_cache.get_or_init(|| {
|
||||
let mut ov = HashMap::new();
|
||||
let mut def = HashMap::new();
|
||||
if let Some(doc) = self.xml("[Content_Types].xml") {
|
||||
for o in doc.root.children_named("Override") {
|
||||
if let (Some(n), Some(ct)) = (o.attr("PartName"), o.attr("ContentType")) {
|
||||
ov.insert(n.to_ascii_lowercase(), ct.to_string());
|
||||
}
|
||||
}
|
||||
for d in doc.root.children_named("Default") {
|
||||
if let (Some(e), Some(ct)) = (d.attr("Extension"), d.attr("ContentType")) {
|
||||
def.insert(e.to_ascii_lowercase(), ct.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
(ov, def)
|
||||
});
|
||||
let p = format!("/{}", norm(part));
|
||||
if let Some(ct) = overrides.get(&p) {
|
||||
return Some(ct.clone());
|
||||
}
|
||||
let ext = part.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
|
||||
defaults.get(&ext).cloned()
|
||||
}
|
||||
pub fn original_name(&self, name: &str) -> Option<&str> {
|
||||
self.parts.get(&norm(name)).map(|(n, _)| n.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// The relationships in a parsed rels part, with internal targets resolved against `part`'s folder.
|
||||
fn rels_of(doc: &xml::Doc, part: &str) -> Rels {
|
||||
let base = dir_of(part);
|
||||
let mut out = Rels::default();
|
||||
for r in doc.root.children_named("Relationship") {
|
||||
let (Some(id), Some(ty), Some(target)) = (r.attr("Id"), r.attr("Type"), r.attr("Target")) else { continue };
|
||||
let external = r.attr("TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("external"));
|
||||
let target_raw = target.to_string();
|
||||
let target = if external { target_raw.clone() } else { resolve(&base, target) };
|
||||
out.by_id.entry(id.to_string()).or_insert(out.items.len());
|
||||
out.items.push(Rel {
|
||||
id: id.to_string(),
|
||||
kind: ty.rsplit('/').next().unwrap_or(ty).to_string(),
|
||||
ty: ty.to_string(),
|
||||
target_raw,
|
||||
target,
|
||||
external,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The relationships of `part` from the bytes of its rels part (kept parts carried by a chart).
|
||||
pub fn rels_from_bytes(bytes: &[u8], part: &str) -> Rels {
|
||||
match xml::parse(bytes) {
|
||||
Ok(doc) => rels_of(&doc, part),
|
||||
Err(e) => {
|
||||
log::warn!("pptx: relationships of {part}: {e}");
|
||||
Rels::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Rel {
|
||||
pub id: String,
|
||||
/// Last segment of the relationship type (`slide`, `image`, `media`…).
|
||||
pub kind: String,
|
||||
/// Full relationship type URI.
|
||||
pub ty: String,
|
||||
/// `Target` as written in the rels part (relative path or URL).
|
||||
pub target_raw: String,
|
||||
/// Absolute part name for internal targets; the URL for external ones.
|
||||
pub target: String,
|
||||
pub external: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Rels {
|
||||
pub items: Vec<Rel>,
|
||||
/// Id → index of its first relationship in `items`.
|
||||
by_id: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl Rels {
|
||||
pub fn get(&self, id: &str) -> Option<&Rel> {
|
||||
self.by_id.get(id).and_then(|&i| self.items.get(i))
|
||||
}
|
||||
pub fn target(&self, id: &str) -> Option<&str> {
|
||||
self.get(id).map(|r| r.target.as_str())
|
||||
}
|
||||
pub fn first_of(&self, kind: &str) -> Option<&Rel> {
|
||||
self.items.iter().find(|r| r.kind == kind)
|
||||
}
|
||||
pub fn all_of<'a>(&'a self, kind: &'a str) -> impl Iterator<Item = &'a Rel> + 'a {
|
||||
self.items.iter().filter(move |r| r.kind == kind)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn norm(name: &str) -> String {
|
||||
name.trim_start_matches('/').replace('\\', "/").to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// A part a chart may carry along beside its own `chartN.xml` (workbook, style, drawing, picture).
|
||||
/// Chart documents themselves are rewritten, and nothing outside these folders is copied: a relationship
|
||||
/// must not be able to replace `ppt/slides/slide1.xml` on save.
|
||||
pub fn sidecar_part(name: &str) -> bool {
|
||||
let n = norm(name);
|
||||
let segs: Vec<&str> = n.split('/').filter(|s| !s.is_empty()).collect();
|
||||
if segs.iter().any(|s| *s == "." || *s == "..") {
|
||||
return false;
|
||||
}
|
||||
let (Some(root), Some(area)) = (segs.first().copied(), segs.get(1).copied()) else { return false };
|
||||
if root != "ppt" || !matches!(area, "embeddings" | "charts" | "drawings" | "media") {
|
||||
return false;
|
||||
}
|
||||
let file = segs.last().copied().unwrap_or("");
|
||||
let stem = file.strip_prefix("chart").unwrap_or("");
|
||||
let num = stem.strip_suffix(".xml.rels").or_else(|| stem.strip_suffix(".xml")).unwrap_or("");
|
||||
!(stem != file && !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()))
|
||||
}
|
||||
|
||||
pub fn dir_of(part: &str) -> String {
|
||||
craft_opc::dir_of(part).to_owned()
|
||||
}
|
||||
|
||||
use craft_opc::percent_decode;
|
||||
pub use craft_opc::{file_of, rels_path};
|
||||
|
||||
/// Resolve a relative target against a base directory into a part name.
|
||||
pub fn resolve(base: &str, target: &str) -> String {
|
||||
let target = percent_decode(target.split('#').next().unwrap_or("")).replace('\\', "/");
|
||||
let target = target.as_str();
|
||||
let mut segs: Vec<&str> = if target.starts_with('/') { vec![] } else { base.split('/').filter(|s| !s.is_empty()).collect() };
|
||||
for s in target.split('/') {
|
||||
match s {
|
||||
"" | "." => {}
|
||||
".." => {
|
||||
segs.pop();
|
||||
}
|
||||
s => segs.push(s),
|
||||
}
|
||||
}
|
||||
segs.join("/")
|
||||
}
|
||||
|
||||
/// Relative target from the directory of `from` to part `to` (both absolute part names).
|
||||
pub fn relative(from: &str, to: &str) -> String {
|
||||
let fd_s = dir_of(from);
|
||||
let fd: Vec<&str> = fd_s.split('/').filter(|s| !s.is_empty()).collect();
|
||||
let td_s = dir_of(to);
|
||||
let td: Vec<&str> = td_s.split('/').filter(|s| !s.is_empty()).collect();
|
||||
let common = fd.iter().zip(td.iter()).take_while(|(a, b)| a == b).count();
|
||||
let mut out = String::new();
|
||||
for _ in common..fd.len() {
|
||||
out.push_str("../");
|
||||
}
|
||||
for s in td.iter().skip(common) {
|
||||
out.push_str(s);
|
||||
out.push('/');
|
||||
}
|
||||
out.push_str(file_of(to));
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Writing
|
||||
|
||||
/// Relationships being built for one part.
|
||||
#[derive(Default)]
|
||||
pub struct RelsOut {
|
||||
pub items: Vec<(String, String, String, bool)>,
|
||||
/// (type, target, external) → id of the relationship [`RelsOut::add`] made for it.
|
||||
added: HashMap<(String, String, bool), String>,
|
||||
}
|
||||
|
||||
impl RelsOut {
|
||||
/// Add (or reuse) a relationship; `kind` is a full type URI or a suffix of the standard base.
|
||||
pub fn add(&mut self, kind: &str, target: &str, external: bool) -> String {
|
||||
let ty = if kind.starts_with("http") { kind.to_string() } else { format!("{RT_BASE}{kind}") };
|
||||
let key = (ty, target.to_string(), external);
|
||||
if let Some(id) = self.added.get(&key) {
|
||||
return id.clone();
|
||||
}
|
||||
let id = format!("rId{}", self.items.len() + 1);
|
||||
self.items.push((id.clone(), key.0.clone(), key.1.clone(), external));
|
||||
self.added.insert(key, id.clone());
|
||||
id
|
||||
}
|
||||
/// Always add a new relationship even if an identical one exists.
|
||||
pub fn add_new(&mut self, kind: &str, target: &str, external: bool) -> String {
|
||||
let ty = if kind.starts_with("http") { kind.to_string() } else { format!("{RT_BASE}{kind}") };
|
||||
let id = format!("rId{}", self.items.len() + 1);
|
||||
// `add` reuses the first relationship for a target, whichever call made it.
|
||||
self.added.entry((ty.clone(), target.to_string(), external)).or_insert_with(|| id.clone());
|
||||
self.items.push((id.clone(), ty, target.to_string(), external));
|
||||
id
|
||||
}
|
||||
pub fn to_xml(&self) -> Vec<u8> {
|
||||
let mut w = W::new();
|
||||
w.open("Relationships", A::new().a("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships"));
|
||||
for (id, ty, target, ext) in &self.items {
|
||||
let mut a = A::new().a("Id", id).a("Type", ty).a("Target", target);
|
||||
if *ext {
|
||||
a = a.a("TargetMode", "External");
|
||||
}
|
||||
w.empty("Relationship", a);
|
||||
}
|
||||
w.close("Relationships");
|
||||
w.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A package being written.
|
||||
pub struct PackageOut {
|
||||
files: Vec<(String, Vec<u8>, bool)>,
|
||||
defaults: Vec<(String, String)>,
|
||||
overrides: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Default for PackageOut {
|
||||
fn default() -> Self {
|
||||
PackageOut {
|
||||
files: vec![],
|
||||
defaults: vec![
|
||||
("rels".into(), "application/vnd.openxmlformats-package.relationships+xml".into()),
|
||||
("xml".into(), "application/xml".into()),
|
||||
],
|
||||
overrides: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PackageOut {
|
||||
/// Add an XML part with its content type override.
|
||||
pub fn xml_part(&mut self, name: &str, content_type: &str, data: Vec<u8>) {
|
||||
self.overrides.push((format!("/{name}"), content_type.to_string()));
|
||||
self.files.push((name.to_string(), data, true));
|
||||
}
|
||||
pub fn rels(&mut self, part: &str, rels: &RelsOut) {
|
||||
if rels.items.is_empty() {
|
||||
return;
|
||||
}
|
||||
let path = rels_path(part);
|
||||
if let Some(existing) = self.files.iter_mut().find(|(name, ..)| *name == path) {
|
||||
existing.1 = rels.to_xml();
|
||||
} else {
|
||||
self.files.push((path, rels.to_xml(), true));
|
||||
}
|
||||
}
|
||||
/// Add a part with no content type of its own (a relationships part).
|
||||
pub fn raw(&mut self, name: &str, data: Vec<u8>) {
|
||||
self.files.push((name.to_string(), data, true));
|
||||
}
|
||||
/// Add a binary part; its extension gets a Default content type.
|
||||
pub fn binary(&mut self, name: &str, content_type: &str, data: Vec<u8>) {
|
||||
let ext = name.rsplit('.').next().unwrap_or("bin").to_ascii_lowercase();
|
||||
if !self.defaults.iter().any(|(e, _)| *e == ext) {
|
||||
self.defaults.push((ext, content_type.to_string()));
|
||||
} else if !self.defaults.iter().any(|(e, c)| *e == ext && c == content_type) {
|
||||
self.overrides.push((format!("/{name}"), content_type.to_string()));
|
||||
}
|
||||
self.files.push((name.to_string(), data, false));
|
||||
}
|
||||
pub fn finish(self) -> Result<Vec<u8>, PptxError> {
|
||||
let mut ct = W::new();
|
||||
ct.open("Types", A::new().a("xmlns", "http://schemas.openxmlformats.org/package/2006/content-types"));
|
||||
for (e, c) in &self.defaults {
|
||||
ct.empty("Default", A::new().a("Extension", e).a("ContentType", c));
|
||||
}
|
||||
for (p, c) in &self.overrides {
|
||||
ct.empty("Override", A::new().a("PartName", p).a("ContentType", c));
|
||||
}
|
||||
ct.close("Types");
|
||||
let mut zw = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
let err = |e: &dyn std::fmt::Display| PptxError::Write(e.to_string());
|
||||
zw.start_file("[Content_Types].xml", deflate).map_err(|e| err(&e))?;
|
||||
zw.write_all(&ct.finish()).map_err(|e| err(&e))?;
|
||||
let mut written = std::collections::HashSet::new();
|
||||
for (name, data, compress) in &self.files {
|
||||
// Zip entry names must be unique: a second part under a name already written is
|
||||
// dropped rather than producing a package readers reject or resolve differently.
|
||||
if !written.insert(norm(name)) {
|
||||
log::warn!("pptx: part {name} written twice; keeping the first");
|
||||
continue;
|
||||
}
|
||||
let large = data.len() as u64 >= u32::MAX as u64 / 2;
|
||||
let opts = if *compress { deflate } else { stored }.large_file(large);
|
||||
zw.start_file(name.as_str(), opts).map_err(|e| err(&e))?;
|
||||
zw.write_all(data).map_err(|e| err(&e))?;
|
||||
}
|
||||
let cur = zw.finish().map_err(|e| err(&e))?;
|
||||
Ok(cur.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_names_preserve_relationship_wire_policy() {
|
||||
for (part, dir, file, rels) in [
|
||||
("", "", "", "_rels/.rels"),
|
||||
("/", "", "", "_rels/.rels"),
|
||||
("///ppt/slides/slide1.xml", "ppt/slides", "slide1.xml", "ppt/slides/_rels/slide1.xml.rels"),
|
||||
("ppt/", "ppt", "", "ppt/_rels/.rels"),
|
||||
("é/😀.xml", "é", "😀.xml", "é/_rels/😀.xml.rels"),
|
||||
] {
|
||||
assert_eq!(dir_of(part), dir);
|
||||
assert_eq!(file_of(part), file);
|
||||
assert_eq!(rels_path(part), rels);
|
||||
}
|
||||
assert_eq!(percent_decode("a+b%20c%2Fd%23e"), "a+b c/d#e");
|
||||
assert_eq!(percent_decode("% %1 %zz %+1 %ff"), "% %1 %zz %+1 �");
|
||||
// Keep Deck's policy: strip the raw fragment first, then decode percent escapes once.
|
||||
assert_eq!(resolve("ppt/slides", "../media/a%23b.png#ignored"), "ppt/media/a#b.png");
|
||||
assert_eq!(resolve("ppt/slides", "%252e%252e/a"), "ppt/slides/%2e%2e/a");
|
||||
assert_eq!(resolve("ppt/slides", "%2e%2e/%2e%2e/%2e%2e/a"), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_keeps_encoded_hash_and_strips_fragment() {
|
||||
assert_eq!(resolve("ppt/slides", "../media/a%23b.png"), "ppt/media/a#b.png");
|
||||
assert_eq!(resolve("ppt/slides", "../media/a.png#frag"), "ppt/media/a.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_percent_decode_requires_two_hex_digits() {
|
||||
assert_eq!(resolve("ppt/slides", "../media/a%+5b.png"), "ppt/media/a%+5b.png");
|
||||
assert_eq!(resolve("ppt/slides", "../media/a%20b.png"), "ppt/media/a b.png");
|
||||
}
|
||||
|
||||
fn zip_of(entries: &[(&str, usize)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
for (name, len) in entries {
|
||||
zw.start_file(*name, o).unwrap();
|
||||
zw.write_all(&vec![b'x'; *len]).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarded_parts_count_against_the_inflate_budget() {
|
||||
// Kept bytes cap at 100: b, c and d are inflated past what's left and discarded. That
|
||||
// work is charged, so after d the budget (130) is spent and e is not read, although it
|
||||
// would have fit.
|
||||
let z = zip_of(&[("a", 80), ("b", 80), ("c", 80), ("d", 80), ("e", 5)]);
|
||||
let p = Package::open_within(&z, 1000, 100, 130).unwrap();
|
||||
assert!(p.get("a").is_some());
|
||||
assert!(p.get("b").is_none() && p.get("d").is_none());
|
||||
assert!(p.get("e").is_none(), "the inflate budget stops reading");
|
||||
// With room to spare the same small part is kept.
|
||||
let p = Package::open_within(&z, 1000, 100, 10_000).unwrap();
|
||||
assert!(p.get("e").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_relationships_are_found_by_index_and_first_id_wins() {
|
||||
let n = 50_000;
|
||||
let mut x = String::from(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
|
||||
for i in 0..n {
|
||||
x.push_str(&format!(r#"<Relationship Id="rId{i}" Type="{RT_BASE}image" Target="../media/image{i}.png"/>"#));
|
||||
}
|
||||
x.push_str(&format!(r#"<Relationship Id="rId0" Type="{RT_BASE}image" Target="../media/dup.png"/></Relationships>"#));
|
||||
let rels = rels_from_bytes(x.as_bytes(), "ppt/slides/slide1.xml");
|
||||
assert_eq!(rels.target("rId0"), Some("ppt/media/image0.png"), "the first of a repeated id wins");
|
||||
assert!((0..n).all(|i| rels.target(&format!("rId{i}")) == Some(&*format!("ppt/media/image{i}.png"))));
|
||||
|
||||
let mut out = RelsOut::default();
|
||||
let ids: Vec<String> = (0..n).map(|i| out.add("hyperlink", &format!("https://example.com/{i}"), true)).collect();
|
||||
assert_eq!(out.add("hyperlink", "https://example.com/7", true), ids[7], "an identical target reuses its id");
|
||||
assert_eq!(out.add("hyperlink", "https://example.com/7", false), format!("rId{}", n + 1), "internal is distinct");
|
||||
let fresh = out.add_new("image", "../media/a.png", false);
|
||||
assert_ne!(out.add_new("image", "../media/a.png", false), fresh);
|
||||
assert_eq!(out.add("image", "../media/a.png", false), fresh, "add reuses the first add_new made");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backslash_zip_entry_names_are_found() {
|
||||
let z = zip_of(&[("PPT\\Slides\\Slide1.xml", 3)]);
|
||||
let p = Package::open(&z).unwrap();
|
||||
assert!(p.get("ppt/slides/slide1.xml").is_some());
|
||||
assert_eq!(p.original_name("ppt/slides/slide1.xml"), Some("PPT/Slides/Slide1.xml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_bytes_applies_the_xml_limit() {
|
||||
let z = zip_of(&[("small.xml", 10)]);
|
||||
let p = Package::open(&z).unwrap();
|
||||
assert_eq!(p.xml_bytes("small.xml").map(<[u8]>::len), Some(10));
|
||||
assert!(p.xml_bytes("missing.xml").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_backslash_target() {
|
||||
assert_eq!(resolve("ppt/slides", "..\\media\\image1.png"), "ppt/media/image1.png");
|
||||
assert_eq!(resolve("ppt/slides", "\\ppt\\media\\a.png"), "ppt/media/a.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_resolution() {
|
||||
assert_eq!(resolve("ppt/slides", "../media/image1.png"), "ppt/media/image1.png");
|
||||
assert_eq!(resolve("ppt", "slides/slide1.xml"), "ppt/slides/slide1.xml");
|
||||
assert_eq!(resolve("ppt/slides", "/ppt/media/a%20b.png"), "ppt/media/a b.png");
|
||||
assert_eq!(resolve("", "../../../x.xml"), "x.xml");
|
||||
assert_eq!(rels_path("ppt/presentation.xml"), "ppt/_rels/presentation.xml.rels");
|
||||
assert_eq!(rels_path("[Content_Types].xml"), "_rels/[Content_Types].xml.rels");
|
||||
assert_eq!(relative("ppt/slides/slide1.xml", "ppt/media/image1.png"), "../media/image1.png");
|
||||
assert_eq!(relative("ppt/presentation.xml", "ppt/slides/slide1.xml"), "slides/slide1.xml");
|
||||
assert_eq!(relative("ppt/slides/slide1.xml", "ppt/slides/slide2.xml"), "slide2.xml");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidecar_parts_stay_inside_chart_folders() {
|
||||
assert!(sidecar_part("ppt/embeddings/Microsoft_Excel_Worksheet1.xlsx"));
|
||||
assert!(sidecar_part("ppt/charts/style1.xml"));
|
||||
assert!(sidecar_part("ppt/drawings/chartDrawing1.xml"));
|
||||
assert!(sidecar_part("ppt/media/image1.png"));
|
||||
assert!(!sidecar_part("ppt/charts/chart1.xml"));
|
||||
assert!(!sidecar_part("ppt/charts/_rels/chart1.xml.rels"));
|
||||
assert!(!sidecar_part("ppt/slides/slide1.xml"));
|
||||
assert!(!sidecar_part("ppt/embeddings/../../ppt/slides/slide1.xml"));
|
||||
assert!(!sidecar_part("/etc/passwd"));
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
//! The placeholder image written when a picture's media is missing: a 1×1 fully transparent RGBA
|
||||
//! PNG, kept as its fixed bytes (signature, IHDR, one stored-deflate IDAT scanline, IEND) so the
|
||||
//! app carries no PNG encoder of its own.
|
||||
|
||||
/// The PNG file, byte for byte what the former local encoder produced.
|
||||
const TRANSPARENT_1X1: [u8; 73] = [
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
|
||||
0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x01, 0x05, 0x00, 0xFA, 0xFF,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x64, 0x78, 0x95, 0x38, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60,
|
||||
0x82,
|
||||
];
|
||||
|
||||
/// A 1×1 fully transparent RGBA PNG.
|
||||
pub fn transparent_1x1() -> Vec<u8> {
|
||||
TRANSPARENT_1X1.to_vec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
#[test]
|
||||
fn placeholder_is_a_transparent_1x1_png() {
|
||||
let png = super::transparent_1x1();
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
// IHDR: 1×1, 8-bit RGBA, no interlace.
|
||||
assert_eq!(&png[12..16], b"IHDR");
|
||||
assert_eq!(&png[16..29], &[0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]);
|
||||
assert!(png.ends_with(b"IEND\xAE\x42\x60\x82"));
|
||||
// The stored scanline: filter byte 0, then one pixel with zero alpha.
|
||||
assert_eq!(&png[49..54], &[0, 0, 0, 0, 0]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,177 +0,0 @@
|
||||
//! Office 2016 charts (`cx:chartSpace`, the `chartEx` part): waterfall, funnel, treemap,
|
||||
//! sunburst, histogram, Pareto and box & whisker. Their data sits in `cx:chartData` as levels of
|
||||
//! points, and each series names its layout (`layoutId`).
|
||||
|
||||
use super::chart::rich_text;
|
||||
use crate::xml::El;
|
||||
use deckcraft_model::chart::{Chart, ChartType, Series};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Points per level and levels per dimension we keep (guards against hostile parts).
|
||||
const MAX_POINTS: usize = 100_000;
|
||||
const MAX_CHARTEX_POINTS: usize = 1_000_000;
|
||||
|
||||
/// One `cx:data`: its categories (the innermost level) and named numeric dimensions.
|
||||
#[derive(Default)]
|
||||
struct Data {
|
||||
categories: Vec<String>,
|
||||
/// Outer category levels, innermost first.
|
||||
levels: Vec<Vec<String>>,
|
||||
numbers: HashMap<String, (Vec<Option<f64>>, Option<String>)>,
|
||||
}
|
||||
|
||||
/// A level's points, by `idx`.
|
||||
fn points(lvl: &El, budget: &mut usize) -> Vec<String> {
|
||||
if *budget == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let cap = MAX_POINTS.min(*budget);
|
||||
let mut pts = Vec::new();
|
||||
let mut max_idx = 0;
|
||||
for pt in lvl.children_named("pt").take(cap) {
|
||||
let i = pt.u32("idx").unwrap_or(0) as usize;
|
||||
if i >= cap {
|
||||
continue;
|
||||
}
|
||||
max_idx = max_idx.max(i + 1);
|
||||
pts.push((i, pt.text()));
|
||||
}
|
||||
if pts.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let n = max_idx.min(cap);
|
||||
let mut out = vec![String::new(); n];
|
||||
for (i, s) in pts {
|
||||
if let Some(target) = out.get_mut(i) {
|
||||
*target = s;
|
||||
}
|
||||
}
|
||||
*budget = budget.saturating_sub(out.len());
|
||||
out
|
||||
}
|
||||
|
||||
fn data(d: &El, budget: &mut usize) -> Data {
|
||||
let mut out = Data::default();
|
||||
for dim in d.elements().take(64) {
|
||||
if *budget == 0 {
|
||||
break;
|
||||
}
|
||||
// The first level is the innermost: a treemap's leaves, a waterfall's categories.
|
||||
let Some(lvl) = dim.child("lvl") else { continue };
|
||||
let ty = dim.attr("type").unwrap_or("");
|
||||
if dim.is("strDim") || (dim.is("numDim") && ty == "cat") {
|
||||
if ty == "cat" || out.categories.is_empty() {
|
||||
out.categories = points(lvl, budget);
|
||||
// Further levels are the hierarchy's parents, innermost first.
|
||||
out.levels = dim.children_named("lvl").skip(1).take(deckcraft_model::chart::MAX_LEVELS).map(|l| points(l, budget)).collect();
|
||||
}
|
||||
} else if dim.is("numDim") {
|
||||
let vals = points(lvl, budget).into_iter().map(|s| s.trim().parse::<f64>().ok().filter(|v| v.is_finite())).collect();
|
||||
out.numbers.insert(ty.to_string(), (vals, lvl.attr("formatCode").map(str::to_string)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn kind_of(layout: &str) -> Option<ChartType> {
|
||||
Some(match layout {
|
||||
"waterfall" => ChartType::Waterfall,
|
||||
"funnel" => ChartType::Funnel,
|
||||
"treemap" => ChartType::Treemap,
|
||||
"sunburst" => ChartType::Sunburst,
|
||||
"clusteredColumn" => ChartType::Histogram,
|
||||
"boxWhisker" => ChartType::BoxWhisker,
|
||||
"regionMap" => ChartType::RegionMap,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse a `chartEx` part. `None` for anything else, and for layouts DeckCraft has no type for.
|
||||
pub fn read_chartex_xml(bytes: &[u8]) -> Option<Chart> {
|
||||
let doc = crate::xml::parse(bytes).ok()?;
|
||||
let mut root = doc.root;
|
||||
super::resolve_mc(&mut root, 0);
|
||||
let mut c = chartex_from(&root)?;
|
||||
c.raw = Some(String::from_utf8_lossy(bytes).into_owned());
|
||||
Some(c)
|
||||
}
|
||||
|
||||
pub(crate) fn chartex_from(root: &El) -> Option<Chart> {
|
||||
if !root.is("chartSpace") {
|
||||
return None;
|
||||
}
|
||||
let mut decode_budget = MAX_CHARTEX_POINTS;
|
||||
let datas: HashMap<String, Data> = root
|
||||
.child("chartData")?
|
||||
.children_named("data")
|
||||
.take(64)
|
||||
.map(|d| (d.attr("id").unwrap_or("0").to_string(), data(d, &mut decode_budget)))
|
||||
.collect();
|
||||
let ch = root.child("chart")?;
|
||||
let region = ch.child("plotArea")?.child("plotAreaRegion")?;
|
||||
let mut c = Chart { categories: vec![], series: vec![], title: None, legend: None, gridlines: false, ..Default::default() };
|
||||
c.title = ch.child("title").map(|t| rich_text(t).filter(|s| !s.is_empty()).unwrap_or_else(|| "Chart Title".into()));
|
||||
c.legend = ch.child("legend").map(|l| l.attr("pos").unwrap_or("t").to_string());
|
||||
let mut kind = None;
|
||||
let mut output_budget = MAX_CHARTEX_POINTS;
|
||||
let mut categories_set = false;
|
||||
for s in region.children_named("series").take(1000) {
|
||||
let layout = s.attr("layoutId").unwrap_or("");
|
||||
if layout == "paretoLine" {
|
||||
// The cumulative line PowerPoint adds to a Pareto histogram.
|
||||
kind = Some(ChartType::Pareto);
|
||||
continue;
|
||||
}
|
||||
let k = kind_of(layout)?;
|
||||
if s.bool("hidden") == Some(true) {
|
||||
continue;
|
||||
}
|
||||
kind = Some(match kind {
|
||||
Some(ChartType::Pareto) => ChartType::Pareto,
|
||||
_ => k,
|
||||
});
|
||||
let d = datas.get(s.child("dataId").and_then(|i| i.attr("val")).unwrap_or("0"))?;
|
||||
let (values_src, format) = ["val", "size", "colorVal"]
|
||||
.iter()
|
||||
.find_map(|t| d.numbers.get(*t))
|
||||
.or_else(|| d.numbers.values().next())
|
||||
.map(|(v, f)| (v.as_slice(), f.clone()))
|
||||
.unwrap_or((&[], None));
|
||||
let take_len = values_src.len().min(output_budget);
|
||||
let values = values_src[..take_len].to_vec();
|
||||
output_budget = output_budget.saturating_sub(values.len());
|
||||
if !categories_set && (!d.categories.is_empty() || !d.levels.is_empty()) {
|
||||
categories_set = true;
|
||||
c.categories = d.categories.clone();
|
||||
c.category_levels = d.levels.clone();
|
||||
output_budget = output_budget.saturating_sub(c.categories.len());
|
||||
for lvl in &c.category_levels {
|
||||
output_budget = output_budget.saturating_sub(lvl.len());
|
||||
}
|
||||
}
|
||||
if let Some(st) = s.child("layoutPr").and_then(|l| l.child("statistics")) {
|
||||
c.inclusive_quartiles = st.attr("quartileMethod") == Some("inclusive");
|
||||
}
|
||||
if let Some(b) = s.child("layoutPr").and_then(|l| l.child("binning")) {
|
||||
c.bin_count = b.child("binCount").and_then(|n| n.u32("val")).filter(|n| *n > 0);
|
||||
c.bin_size = b.child("binSize").and_then(|n| n.attr("val")).and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite() && *v > 0.0);
|
||||
}
|
||||
if let Some(st) = s.child("layoutPr").and_then(|l| l.child("subtotals")) {
|
||||
c.subtotals = st.children_named("idx").filter_map(|i| i.u32("val")).map(|i| i as usize).take(MAX_POINTS).collect();
|
||||
}
|
||||
let name = s.child("tx").and_then(|t| t.find("v")).map(|v| v.text()).unwrap_or_default();
|
||||
c.series.push(Series {
|
||||
name,
|
||||
values,
|
||||
data_labels: s.child("dataLabels").map(|l| l.bool("hidden") != Some(true)),
|
||||
number_format: format,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
c.kind = kind?;
|
||||
c.data_labels = c.series.iter().any(|s| s.data_labels == Some(true));
|
||||
c.vary_colors = matches!(c.kind, ChartType::Funnel | ChartType::Treemap | ChartType::Sunburst | ChartType::Waterfall);
|
||||
// Waterfall, histogram and box charts have a value axis with gridlines by default.
|
||||
c.gridlines = matches!(c.kind, ChartType::Waterfall | ChartType::Histogram | ChartType::Pareto | ChartType::BoxWhisker);
|
||||
Some(c)
|
||||
}
|
||||
@@ -1,824 +0,0 @@
|
||||
//! DrawingML reading: colours, fills, lines, effects, transforms and text.
|
||||
|
||||
use deckcraft_color::{ColorTransform, Rgba, SchemeSlot};
|
||||
use deckcraft_geom::{Xfrm, emu_to_pt};
|
||||
use deckcraft_model::style::{
|
||||
ColorBase, ColorRef, Compound, Dash, Effects, Fill, Glow, Gradient, GradientFlip, GradientShape, GradientStop, Line, LineAlign, LineCap, LineEnd,
|
||||
LineJoin, PatternFill, PictureFill, PictureMode, Reflection, Shadow,
|
||||
};
|
||||
use deckcraft_model::text::{
|
||||
Action, Align, Anchor, AutoFit, BodyProps, Bullet, Caps, Hyperlink, LevelStyle, ListStyle, ParaProps, Paragraph, Run, RunKind, RunProps, Spacing,
|
||||
Strike, TabStop, TextBody, TextDir,
|
||||
};
|
||||
|
||||
use super::{Imp, Part};
|
||||
use crate::xml::El;
|
||||
|
||||
pub fn pt(e: &El, name: &str) -> Option<f64> {
|
||||
e.i64(name).map(emu_to_pt)
|
||||
}
|
||||
|
||||
/// 1/100 000 → fraction.
|
||||
pub fn pct(e: &El, name: &str) -> Option<f64> {
|
||||
e.f64(name).map(|v| v / 100_000.0)
|
||||
}
|
||||
|
||||
fn bullet_size_points(value: Option<&str>) -> Option<f64> {
|
||||
value.and_then(|v| v.trim().parse::<u32>().ok()).filter(|v| (100..=400_000).contains(v)).map(|v| v as f64 / 100.0)
|
||||
}
|
||||
|
||||
fn bullet_size_percent(value: Option<&str>) -> Option<f64> {
|
||||
let value = value?.trim();
|
||||
let (value, scale) = if let Some(value) = value.strip_suffix('%') { (value.trim(), 100.0) } else { (value, 100_000.0) };
|
||||
value.parse::<f64>().ok().filter(|v| v.is_finite()).map(|v| v / scale)
|
||||
}
|
||||
|
||||
/// 1/60 000 degree → degrees.
|
||||
pub fn ang(e: &El, name: &str) -> Option<f64> {
|
||||
e.f64(name).map(|v| v / 60_000.0)
|
||||
}
|
||||
|
||||
fn lin_to_srgb(v: f64) -> f64 {
|
||||
let v = v.clamp(0.0, 1.0);
|
||||
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
/// A colour element (`srgbClr`, `schemeClr`, …) with its transforms.
|
||||
pub fn color_el(c: &El) -> Option<ColorRef> {
|
||||
let base = match c.local() {
|
||||
"srgbClr" => ColorBase::Rgb { rgb: Rgba::from_hex(c.attr("val").unwrap_or("000000")).unwrap_or(Rgba::BLACK) },
|
||||
"schemeClr" => ColorBase::Scheme { slot: c.attr("val").and_then(SchemeSlot::from_xml).unwrap_or(SchemeSlot::Tx1) },
|
||||
"sysClr" => ColorBase::System {
|
||||
name: c.attr("val").unwrap_or("windowText").to_string(),
|
||||
last: c.attr("lastClr").and_then(Rgba::from_hex).unwrap_or(if c.attr("val") == Some("window") { Rgba::WHITE } else { Rgba::BLACK }),
|
||||
},
|
||||
"prstClr" => ColorBase::Preset { name: c.attr("val").unwrap_or("black").to_string() },
|
||||
"scrgbClr" => {
|
||||
let f = |n: &str| lin_to_srgb(c.f64(n).unwrap_or(0.0) / 100_000.0);
|
||||
ColorBase::Rgb { rgb: Rgba::from_f64(f("r"), f("g"), f("b"), 1.0) }
|
||||
}
|
||||
"hslClr" => {
|
||||
let h = c.f64("hue").unwrap_or(0.0) / 60_000.0;
|
||||
let s = c.f64("sat").unwrap_or(0.0) / 100_000.0;
|
||||
let l = c.f64("lum").unwrap_or(0.0) / 100_000.0;
|
||||
ColorBase::Rgb { rgb: Rgba::from_hsl(h, s, l, 255) }
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let mods = c.elements().take(32).filter_map(|m| ColorTransform::from_xml(m.local(), m.i32("val"))).collect();
|
||||
Some(ColorRef { base, mods })
|
||||
}
|
||||
|
||||
/// The first colour child of a container (`solidFill`, `fgClr`, `lnRef`…).
|
||||
pub fn color(container: &El) -> Option<ColorRef> {
|
||||
container.elements().find_map(color_el)
|
||||
}
|
||||
|
||||
const FILL_NAMES: [&str; 6] = ["noFill", "solidFill", "gradFill", "blipFill", "pattFill", "grpFill"];
|
||||
|
||||
/// The fill child of `parent`, if any.
|
||||
pub fn fill_of(imp: &mut Imp, part: &Part, parent: &El) -> Option<Fill> {
|
||||
parent.elements().find(|e| FILL_NAMES.contains(&e.local())).and_then(|f| fill_el(imp, part, f))
|
||||
}
|
||||
|
||||
pub fn fill_el(imp: &mut Imp, part: &Part, f: &El) -> Option<Fill> {
|
||||
Some(match f.local() {
|
||||
"noFill" => Fill::None,
|
||||
"solidFill" => Fill::Solid { color: color(f).unwrap_or(ColorRef::rgb(Rgba::BLACK)) },
|
||||
"gradFill" => Fill::Gradient(gradient(f)),
|
||||
"blipFill" => match blip_fill(imp, part, f) {
|
||||
// A picture filling a shape or background with neither `a:stretch` nor `a:tile` is
|
||||
// tiled at its own size, as PowerPoint draws it.
|
||||
Some(mut p) if f.child("stretch").is_none() && f.child("tile").is_none() => {
|
||||
p.mode = PictureMode::Tile { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, flip: "none".into(), align: "tl".into() };
|
||||
Fill::Picture(p)
|
||||
}
|
||||
Some(p) => Fill::Picture(p),
|
||||
None => Fill::None,
|
||||
},
|
||||
"pattFill" => Fill::Pattern(pattern(f)),
|
||||
"grpFill" => Fill::Group,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// An `a:pattFill`: its preset (5 % dots when unset), foreground (black) and background (white).
|
||||
pub fn pattern(f: &El) -> PatternFill {
|
||||
PatternFill {
|
||||
preset: f.attr("prst").unwrap_or("pct5").to_string(),
|
||||
fg: f.child("fgClr").and_then(color).unwrap_or(ColorRef::rgb(Rgba::BLACK)),
|
||||
bg: f.child("bgClr").and_then(color).unwrap_or(ColorRef::rgb(Rgba::WHITE)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gradient(f: &El) -> Gradient {
|
||||
let mut stops: Vec<GradientStop> = f
|
||||
.child("gsLst")
|
||||
.map(|l| {
|
||||
l.children_named("gs")
|
||||
.take(256)
|
||||
.map(|g| GradientStop { pos: pct(g, "pos").unwrap_or(0.0).clamp(0.0, 1.0), color: color(g).unwrap_or(ColorRef::rgb(Rgba::BLACK)) })
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
stops.sort_by(|a, b| a.pos.total_cmp(&b.pos));
|
||||
let shape = if let Some(l) = f.child("lin") {
|
||||
GradientShape::Linear { angle: ang(l, "ang").unwrap_or(0.0), scaled: l.bool("scaled").unwrap_or(false) }
|
||||
} else if let Some(p) = f.child("path") {
|
||||
let r = p.child("fillToRect");
|
||||
let g = |n: &str| r.and_then(|r| pct(r, n)).unwrap_or(0.0);
|
||||
GradientShape::Path { path: p.attr("path").unwrap_or("circle").to_string(), focus: [g("l"), g("t"), g("r"), g("b")] }
|
||||
} else {
|
||||
GradientShape::Linear { angle: 90.0, scaled: false }
|
||||
};
|
||||
let tile = f.child("tileRect").map(|r| [pct(r, "l"), pct(r, "t"), pct(r, "r"), pct(r, "b")].map(|v| v.unwrap_or(0.0).clamp(-10.0, 10.0)));
|
||||
Gradient {
|
||||
tile: tile.unwrap_or_default(),
|
||||
stops,
|
||||
shape,
|
||||
flip: f.attr("flip").and_then(GradientFlip::from_xml),
|
||||
rotate_with_shape: f.bool("rotWithShape").unwrap_or(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// `blipFill` (either `a:` or `p:`) → picture fill, registering the image as media.
|
||||
pub fn blip_fill(imp: &mut Imp, part: &Part, bf: &El) -> Option<PictureFill> {
|
||||
let blip = bf.child("blip");
|
||||
let media = blip.and_then(|b| media_ref(imp, part, b));
|
||||
let media = media?;
|
||||
let mut pf = PictureFill { media, upright: !bf.bool("rotWithShape").unwrap_or(true), ..Default::default() };
|
||||
if let Some(layer) = blip.and_then(|b| b.child("extLst")).and_then(|x| x.find("imgLayer"))
|
||||
&& let Some(effect) = layer
|
||||
.elements()
|
||||
.filter(|e| e.local() == "imgEffect")
|
||||
.flat_map(|e| e.elements())
|
||||
.map(|e| e.local().to_string())
|
||||
.find(|n| n.starts_with("artistic"))
|
||||
&& let Some(original) = media_ref(imp, part, layer)
|
||||
{
|
||||
pf.artistic = Some(deckcraft_model::style::Artistic { effect, original });
|
||||
}
|
||||
if let Some(b) = blip {
|
||||
for e in b.elements() {
|
||||
match e.local() {
|
||||
"alphaModFix" => pf.alpha = Some(pct(e, "amt").unwrap_or(1.0).clamp(0.0, 1.0)),
|
||||
"lum" => {
|
||||
pf.adjust.brightness = pct(e, "bright").unwrap_or(0.0).clamp(-1.0, 1.0);
|
||||
pf.adjust.contrast = pct(e, "contrast").unwrap_or(0.0).clamp(-1.0, 1.0);
|
||||
}
|
||||
"grayscl" => pf.adjust.grayscale = true,
|
||||
"biLevel" => pf.adjust.bilevel = Some(pct(e, "thresh").unwrap_or(0.5).clamp(0.0, 1.0)),
|
||||
"alphaInv" => pf.adjust.alpha_inv = true,
|
||||
"duotone" => {
|
||||
let cs: Vec<ColorRef> = e.elements().filter_map(color_el).collect();
|
||||
if let [a, b] = cs.as_slice() {
|
||||
pf.adjust.duotone = Some((a.clone(), b.clone()));
|
||||
}
|
||||
}
|
||||
"clrChange" => {
|
||||
if let Some(ColorRef { base: ColorBase::Rgb { rgb }, .. }) = e.child("clrFrom").and_then(color) {
|
||||
pf.adjust.clear_color = Some(rgb);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(r) = bf.child("srcRect") {
|
||||
pf.crop = [pct(r, "l").unwrap_or(0.0), pct(r, "t").unwrap_or(0.0), pct(r, "r").unwrap_or(0.0), pct(r, "b").unwrap_or(0.0)]
|
||||
.map(|v| v.clamp(-10.0, 1.0));
|
||||
}
|
||||
if let Some(t) = bf.child("tile") {
|
||||
pf.mode = PictureMode::Tile {
|
||||
tx: pt(t, "tx").unwrap_or(0.0),
|
||||
ty: pt(t, "ty").unwrap_or(0.0),
|
||||
sx: pct(t, "sx").unwrap_or(1.0),
|
||||
sy: pct(t, "sy").unwrap_or(1.0),
|
||||
flip: t.attr("flip").unwrap_or("none").to_string(),
|
||||
align: t.attr("algn").unwrap_or("tl").to_string(),
|
||||
};
|
||||
} else {
|
||||
let r = bf.path(&["stretch", "fillRect"]);
|
||||
let g = |n: &str| r.and_then(|r| pct(r, n)).unwrap_or(0.0).clamp(-10.0, 1.0);
|
||||
pf.mode = PictureMode::Stretch { fill_rect: [g("l"), g("t"), g("r"), g("b")] };
|
||||
}
|
||||
Some(pf)
|
||||
}
|
||||
|
||||
/// Media for an element with `r:embed` (or `r:link`).
|
||||
pub fn media_ref(imp: &mut Imp, part: &Part, b: &El) -> Option<deckcraft_model::MediaId> {
|
||||
if let Some(id) = b.attr("r:embed").filter(|s| !s.is_empty())
|
||||
&& let Some(r) = part.rels.get(id)
|
||||
{
|
||||
if r.external {
|
||||
return Some(imp.media_link(&r.target));
|
||||
}
|
||||
let t = r.target.clone();
|
||||
if let Some(m) = imp.media_for(&t) {
|
||||
return Some(m);
|
||||
}
|
||||
}
|
||||
if let Some(id) = b.attr("r:link").filter(|s| !s.is_empty())
|
||||
&& let Some(r) = part.rels.get(id)
|
||||
{
|
||||
if r.external {
|
||||
return Some(imp.media_link(&r.target));
|
||||
}
|
||||
let t = r.target.clone();
|
||||
return imp.media_for(&t);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn line(imp: &mut Imp, part: &Part, ln: &El) -> Line {
|
||||
let mut l = Line { width: pt(ln, "w").map(|w| w.clamp(0.0, 2000.0)), ..Default::default() };
|
||||
l.cap = ln.attr("cap").map(|c| match c {
|
||||
"rnd" => LineCap::Round,
|
||||
"sq" => LineCap::Square,
|
||||
_ => LineCap::Flat,
|
||||
});
|
||||
l.compound = ln.attr("cmpd").map(Compound::from_xml);
|
||||
l.align = ln.attr("algn").and_then(LineAlign::from_xml);
|
||||
l.fill = fill_of(imp, part, ln);
|
||||
for e in ln.elements() {
|
||||
match e.local() {
|
||||
"prstDash" => l.dash = Some(Dash::Preset { name: e.attr("val").unwrap_or("solid").to_string() }),
|
||||
"custDash" => {
|
||||
let pattern = e.children_named("ds").take(64).map(|d| (pct(d, "d").unwrap_or(1.0), pct(d, "sp").unwrap_or(1.0))).collect();
|
||||
l.dash = Some(Dash::Custom { pattern });
|
||||
}
|
||||
"round" => l.join = Some(LineJoin::Round),
|
||||
"bevel" => l.join = Some(LineJoin::Bevel),
|
||||
"miter" => {
|
||||
l.join = Some(LineJoin::Miter);
|
||||
l.miter_limit = e.attr("lim").and_then(parse_miter_limit);
|
||||
}
|
||||
"headEnd" => l.head = line_end(e),
|
||||
"tailEnd" => l.tail = line_end(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
fn parse_miter_limit(value: &str) -> Option<u32> {
|
||||
const MAX: u32 = i32::MAX as u32;
|
||||
let value = value.trim();
|
||||
if let Some(percent) = value.strip_suffix('%') {
|
||||
let units = percent.trim().parse::<f64>().ok()? * 1000.0;
|
||||
(units.is_finite() && (0.0..=MAX as f64).contains(&units)).then(|| units.round() as u32)
|
||||
} else {
|
||||
value.parse::<u32>().ok().filter(|limit| *limit <= MAX)
|
||||
}
|
||||
}
|
||||
|
||||
fn line_end(e: &El) -> Option<LineEnd> {
|
||||
let kind = e.attr("type").unwrap_or("none");
|
||||
Some(LineEnd { kind: kind.to_string(), w: e.attr("w").unwrap_or("med").to_string(), len: e.attr("len").unwrap_or("med").to_string() })
|
||||
}
|
||||
|
||||
fn shadow(e: &El, inner: bool) -> Shadow {
|
||||
Shadow {
|
||||
color: color(e).unwrap_or(ColorRef::rgb(Rgba::BLACK)),
|
||||
blur: pt(e, "blurRad").unwrap_or(0.0).max(0.0),
|
||||
dist: pt(e, "dist").unwrap_or(0.0),
|
||||
dir: ang(e, "dir").unwrap_or(0.0),
|
||||
inner,
|
||||
sx: pct(e, "sx").unwrap_or(1.0),
|
||||
sy: pct(e, "sy").unwrap_or(1.0),
|
||||
kx: ang(e, "kx").unwrap_or(0.0),
|
||||
ky: ang(e, "ky").unwrap_or(0.0),
|
||||
align: e.attr("algn").unwrap_or(if inner { "" } else { "b" }).to_string(),
|
||||
rotate_with_shape: e.bool("rotWithShape").unwrap_or(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// `effectLst` → effects.
|
||||
pub fn effects(el: &El) -> Effects {
|
||||
let mut fx = Effects::default();
|
||||
for e in el.elements() {
|
||||
match e.local() {
|
||||
"outerShdw" => fx.outer_shadow = Some(shadow(e, false)),
|
||||
"prstShdw" => {
|
||||
let mut s = shadow(e, false);
|
||||
s.align = "b".into();
|
||||
fx.outer_shadow = Some(s);
|
||||
}
|
||||
"innerShdw" => fx.inner_shadow = Some(shadow(e, true)),
|
||||
"glow" => fx.glow = Some(Glow { color: color(e).unwrap_or(ColorRef::rgb(Rgba::BLACK)), radius: pt(e, "rad").unwrap_or(0.0).max(0.0) }),
|
||||
"softEdge" => fx.soft_edge = Some(pt(e, "rad").unwrap_or(0.0).max(0.0)),
|
||||
"fillOverlay" => {
|
||||
let fill = e.elements().find_map(|f| match f.local() {
|
||||
"solidFill" => color(f).map(|c| Fill::Solid { color: c }),
|
||||
"gradFill" => Some(Fill::Gradient(gradient(f))),
|
||||
_ => None,
|
||||
});
|
||||
fx.fill_overlay = fill.map(|fill| deckcraft_model::style::FillOverlay { blend: e.attr("blend").unwrap_or("over").to_string(), fill });
|
||||
}
|
||||
"reflection" => {
|
||||
fx.reflection = Some(Reflection {
|
||||
blur: pt(e, "blurRad").unwrap_or(0.0),
|
||||
start_alpha: pct(e, "stA").unwrap_or(1.0),
|
||||
end_alpha: pct(e, "endA").unwrap_or(0.0),
|
||||
end_pos: pct(e, "endPos").unwrap_or(1.0),
|
||||
dist: pt(e, "dist").unwrap_or(0.0),
|
||||
st_pos: e.i64("stPos").and_then(|v| i32::try_from(v).ok()),
|
||||
dir: e.i64("dir").and_then(|v| i32::try_from(v).ok()),
|
||||
fade_dir: e.i64("fadeDir").and_then(|v| i32::try_from(v).ok()),
|
||||
sx: e.i64("sx").and_then(|v| i32::try_from(v).ok()),
|
||||
sy: e.i64("sy").and_then(|v| i32::try_from(v).ok()),
|
||||
kx: e.i64("kx").and_then(|v| i32::try_from(v).ok()),
|
||||
ky: e.i64("ky").and_then(|v| i32::try_from(v).ok()),
|
||||
align: e.attr("algn").filter(|v| matches!(*v, "tl" | "t" | "tr" | "l" | "ctr" | "r" | "bl" | "b" | "br")).map(str::to_owned),
|
||||
rotate_with_shape: e.bool("rotWithShape"),
|
||||
})
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fx
|
||||
}
|
||||
|
||||
/// `a:xfrm` → (box, child box for groups).
|
||||
pub fn xfrm(x: &El) -> (Xfrm, Option<Xfrm>) {
|
||||
let off = x.child("off");
|
||||
let ext = x.child("ext");
|
||||
let g = |e: Option<&El>, n: &str| e.and_then(|e| pt(e, n)).unwrap_or(0.0);
|
||||
let mut xf = Xfrm::new(g(off, "x"), g(off, "y"), g(ext, "cx").max(0.0), g(ext, "cy").max(0.0));
|
||||
xf.rot = ang(x, "rot").unwrap_or(0.0);
|
||||
if !xf.rot.is_finite() {
|
||||
xf.rot = 0.0;
|
||||
}
|
||||
xf.flip_h = x.bool("flipH").unwrap_or(false);
|
||||
xf.flip_v = x.bool("flipV").unwrap_or(false);
|
||||
let child = match (x.child("chOff"), x.child("chExt")) {
|
||||
(Some(o), Some(e)) => Some(Xfrm::new(g(Some(o), "x"), g(Some(o), "y"), g(Some(e), "cx").max(0.0), g(Some(e), "cy").max(0.0))),
|
||||
_ => None,
|
||||
};
|
||||
(xf, child)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Text
|
||||
|
||||
pub fn body_pr(b: &El) -> BodyProps {
|
||||
let mut p = BodyProps {
|
||||
inset_l: pt(b, "lIns"),
|
||||
inset_t: pt(b, "tIns"),
|
||||
inset_r: pt(b, "rIns"),
|
||||
inset_b: pt(b, "bIns"),
|
||||
anchor: b.attr("anchor").and_then(Anchor::from_xml),
|
||||
anchor_ctr: b.bool("anchorCtr"),
|
||||
wrap: b.attr("wrap").map(|w| w != "none"),
|
||||
vert: b.attr("vert").and_then(TextDir::from_xml),
|
||||
rot: ang(b, "rot"),
|
||||
columns: b.u32("numCol").map(|n| n.clamp(1, 16)),
|
||||
col_spacing: pt(b, "spcCol"),
|
||||
rtl_col: b.bool("rtlCol"),
|
||||
upright: b.bool("upright"),
|
||||
space_first_last: b.bool("spcFirstLastPara"),
|
||||
compat_ln_spc: b.bool("compatLnSpc"),
|
||||
vert_overflow: b.attr("vertOverflow").and_then(deckcraft_model::text::TextOverflow::from_xml),
|
||||
horz_overflow: b.attr("horzOverflow").and_then(deckcraft_model::text::TextOverflow::from_horz_xml),
|
||||
..Default::default()
|
||||
};
|
||||
for e in b.elements() {
|
||||
match e.local() {
|
||||
"normAutofit" => {
|
||||
p.autofit = Some(AutoFit::Shrink {
|
||||
font_scale: pct(e, "fontScale").map(|v| v.clamp(0.01, 1.0)),
|
||||
line_reduction: pct(e, "lnSpcReduction").unwrap_or(0.0).clamp(0.0, 1.0),
|
||||
})
|
||||
}
|
||||
"spAutoFit" => p.autofit = Some(AutoFit::Shape),
|
||||
"noAutofit" => p.autofit = Some(AutoFit::None),
|
||||
"prstTxWarp" => {
|
||||
p.warp = e.attr("prst").filter(|w| *w != "textNoShape" && !w.is_empty()).map(String::from);
|
||||
p.warp_adj = p.warp.as_deref().map(|w| warp_adjusts(w, e)).unwrap_or_default();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// `prstTxWarp/avLst` guides `adj` / `adj1`… as raw values by index (empty when none is given);
|
||||
/// slots the file leaves out keep the preset's default.
|
||||
fn warp_adjusts(preset: &str, e: &El) -> Vec<f64> {
|
||||
let mut adj: Vec<f64> = Vec::new();
|
||||
let Some(av) = e.child("avLst") else { return adj };
|
||||
let defaults = deckcraft_geom::warp::adjust_defaults(preset);
|
||||
for gd in av.children_named("gd").take(16) {
|
||||
let n = gd.attr("name").unwrap_or("");
|
||||
let idx = if n == "adj" {
|
||||
0
|
||||
} else if let Some(k) = n.strip_prefix("adj").and_then(|k| k.parse::<usize>().ok()).filter(|k| (1..=8).contains(k)) {
|
||||
k - 1
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let Some(v) = gd.attr("fmla").and_then(|f| f.trim().strip_prefix("val")).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
while adj.len() <= idx {
|
||||
adj.push(defaults.get(adj.len()).copied().unwrap_or(0.0));
|
||||
}
|
||||
if let Some(slot) = adj.get_mut(idx) {
|
||||
*slot = v.clamp(-1.0e9, 1.0e9);
|
||||
}
|
||||
}
|
||||
adj
|
||||
}
|
||||
|
||||
fn spacing(e: &El) -> Option<Spacing> {
|
||||
if let Some(p) = e.child("spcPct") {
|
||||
return Some(Spacing::Pct(pct(p, "val").unwrap_or(1.0).clamp(0.0, 100.0)));
|
||||
}
|
||||
e.child("spcPts").map(|p| Spacing::Pts(p.f64("val").unwrap_or(0.0).clamp(0.0, 1_000_000.0) / 100.0))
|
||||
}
|
||||
|
||||
/// `a:pPr` / `a:lvlNpPr` → (level, paragraph props, default run props).
|
||||
pub fn ppr(imp: &mut Imp, part: &Part, p: &El) -> (Option<u8>, ParaProps, Option<RunProps>) {
|
||||
let mut pp = ParaProps {
|
||||
align: p.attr("algn").and_then(Align::from_xml),
|
||||
margin_left: pt(p, "marL"),
|
||||
margin_right: pt(p, "marR"),
|
||||
indent: pt(p, "indent"),
|
||||
rtl: p.bool("rtl"),
|
||||
font_align: p.attr("fontAlgn").map(String::from),
|
||||
east_asian_line_break: p.bool("eaLnBrk"),
|
||||
latin_line_break: p.bool("latinLnBrk"),
|
||||
hanging_punct: p.bool("hangingPunct"),
|
||||
default_tab: pt(p, "defTabSz"),
|
||||
..Default::default()
|
||||
};
|
||||
let lvl = p.u32("lvl").map(|l| l.min(8) as u8);
|
||||
let mut def = None;
|
||||
for e in p.elements() {
|
||||
match e.local() {
|
||||
"lnSpc" => pp.line_spacing = spacing(e),
|
||||
"spcBef" => pp.space_before = spacing(e),
|
||||
"spcAft" => pp.space_after = spacing(e),
|
||||
"buNone" => pp.bullet = Some(Bullet::None),
|
||||
"buChar" => pp.bullet = Some(Bullet::Char { char: e.attr("char").unwrap_or("•").chars().take(4).collect() }),
|
||||
"buAutoNum" => {
|
||||
pp.bullet = Some(Bullet::AutoNum {
|
||||
scheme: e.attr("type").unwrap_or("arabicPeriod").to_string(),
|
||||
start_at: e.u32("startAt").unwrap_or(1).clamp(1, 32767),
|
||||
})
|
||||
}
|
||||
"buBlip" => {
|
||||
if let Some(m) = e.child("blip").and_then(|b| media_ref(imp, part, b)) {
|
||||
pp.bullet = Some(Bullet::Picture { media: m });
|
||||
}
|
||||
}
|
||||
"buFont" => pp.bullet_font = e.attr("typeface").map(String::from),
|
||||
"buFontTx" => pp.bullet_font_follow_text = Some(true),
|
||||
"buClr" => pp.bullet_color = color(e),
|
||||
"buSzPct" => {
|
||||
pp.bullet_size_points = None;
|
||||
pp.bullet_size_follow_text = None;
|
||||
pp.bullet_size = bullet_size_percent(e.attr("val")).map(|v| v.clamp(0.25, 4.0));
|
||||
}
|
||||
"buSzPts" => {
|
||||
pp.bullet_size = None;
|
||||
pp.bullet_size_follow_text = None;
|
||||
pp.bullet_size_points = bullet_size_points(e.attr("val"));
|
||||
}
|
||||
"buClrTx" => pp.bullet_color_follow_text = Some(true),
|
||||
"buSzTx" => {
|
||||
pp.bullet_size = None;
|
||||
pp.bullet_size_points = None;
|
||||
pp.bullet_size_follow_text = Some(true);
|
||||
}
|
||||
"tabLst" => {
|
||||
pp.tabs = Some(
|
||||
e.children_named("tab")
|
||||
.take(64)
|
||||
.map(|t| TabStop { pos: pt(t, "pos").unwrap_or(0.0), align: t.attr("algn").unwrap_or("l").to_string() })
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
"defRPr" => def = Some(rpr(imp, part, e)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(lvl, pp, def)
|
||||
}
|
||||
|
||||
pub fn hyperlink(imp: &mut Imp, part: &Part, h: &El) -> Option<Hyperlink> {
|
||||
let rid = h.attr("r:id").unwrap_or("");
|
||||
let rel = part.rels.get(rid);
|
||||
let action = h.attr("action").unwrap_or("");
|
||||
let a = if let Some(rest) = action.strip_prefix("ppaction://hlinkshowjump?jump=") {
|
||||
match rest {
|
||||
"nextslide" => Action::NextSlide,
|
||||
"previousslide" => Action::PreviousSlide,
|
||||
"firstslide" => Action::FirstSlide,
|
||||
"lastslide" => Action::LastSlide,
|
||||
"endshow" => Action::EndShow,
|
||||
"lastslideviewed" => Action::LastViewed,
|
||||
_ => return None,
|
||||
}
|
||||
} else if action.starts_with("ppaction://hlinksldjump") {
|
||||
let slide = rel.and_then(|r| imp.slide_by_part.get(&crate::opc::norm(&r.target)).copied())?;
|
||||
Action::Slide { slide }
|
||||
} else if let Some(q) = action.strip_prefix("ppaction://customshow?") {
|
||||
let id = q.split('&').find_map(|kv| kv.strip_prefix("id=")).unwrap_or("0");
|
||||
let returns = !matches!(q.split('&').find_map(|kv| kv.strip_prefix("return=")), Some("false" | "0"));
|
||||
Action::CustomShow { name: imp.custom_show_names.get(id).cloned().unwrap_or_else(|| id.to_string()), returns }
|
||||
} else if action.starts_with("ppaction://program") {
|
||||
Action::Program { path: rel.map(|r| r.target.clone()).unwrap_or_default() }
|
||||
} else if action.starts_with("ppaction://media") {
|
||||
Action::PlayMedia
|
||||
} else if action.is_empty() || action.starts_with("ppaction://hlinkfile") {
|
||||
let r = rel?;
|
||||
if r.target.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if !r.external
|
||||
&& let Some(s) = imp.slide_by_part.get(&crate::opc::norm(&r.target))
|
||||
{
|
||||
Action::Slide { slide: *s }
|
||||
} else {
|
||||
Action::Url { url: r.target.clone() }
|
||||
}
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some(Hyperlink {
|
||||
action: a,
|
||||
tooltip: h.attr("tooltip").unwrap_or("").to_string(),
|
||||
highlight_click: h.bool("highlightClick").unwrap_or(false),
|
||||
stop_sound: h.bool("endSnd").unwrap_or(false),
|
||||
sound: h.child("snd").and_then(|s| media_ref(imp, part, s)),
|
||||
zoom_return: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn typeface(e: &El) -> Option<String> {
|
||||
let t = e.attr("typeface").filter(|t| !t.is_empty())?;
|
||||
Some(t.chars().take(256).collect())
|
||||
}
|
||||
|
||||
pub fn rpr(imp: &mut Imp, part: &Part, r: &El) -> RunProps {
|
||||
let mut p = RunProps {
|
||||
lang: r.attr("lang").map(String::from),
|
||||
alt_lang: r.attr("altLang").map(|lang| lang.chars().take(256).collect()),
|
||||
size: r.f64("sz").map(|s| (s / 100.0).clamp(1.0, 4000.0)),
|
||||
bold: r.bool("b"),
|
||||
italic: r.bool("i"),
|
||||
underline: r.attr("u").map(String::from),
|
||||
strike: r.attr("strike").map(|s| match s {
|
||||
"sngStrike" => Strike::Single,
|
||||
"dblStrike" => Strike::Double,
|
||||
_ => Strike::None,
|
||||
}),
|
||||
baseline: pct(r, "baseline").map(|b| b.clamp(-10.0, 10.0)),
|
||||
caps: r.attr("cap").map(|c| match c {
|
||||
"small" => Caps::Small,
|
||||
"all" => Caps::All,
|
||||
_ => Caps::None,
|
||||
}),
|
||||
spacing: r.f64("spc").map(|s| (s / 100.0).clamp(-4000.0, 4000.0)),
|
||||
kern: r.f64("kern").map(|k| (k / 100.0).clamp(0.0, 4000.0)),
|
||||
no_proof: r.bool("noProof"),
|
||||
normalize_height: r.bool("normalizeH"),
|
||||
..Default::default()
|
||||
};
|
||||
for e in r.elements() {
|
||||
match e.local() {
|
||||
"ln" => p.outline = Some(line(imp, part, e)),
|
||||
n if FILL_NAMES.contains(&n) => p.fill = fill_el(imp, part, e),
|
||||
"effectLst" => {
|
||||
let fx = effects(e);
|
||||
p.shadow = fx.outer_shadow;
|
||||
p.inner_shadow = fx.inner_shadow;
|
||||
p.glow = fx.glow;
|
||||
p.reflection = fx.reflection;
|
||||
p.soft_edge = fx.soft_edge;
|
||||
}
|
||||
"highlight" => p.highlight = color(e),
|
||||
"uFill" => p.underline_color = e.child("solidFill").and_then(color),
|
||||
"latin" => p.font = typeface(e),
|
||||
"ea" => p.font_ea = typeface(e),
|
||||
"cs" => p.font_cs = typeface(e),
|
||||
"sym" => p.font_sym = typeface(e),
|
||||
"hlinkClick" => p.link = hyperlink(imp, part, e),
|
||||
"hlinkMouseOver" => p.hover = hyperlink(imp, part, e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// `a:lstStyle`, `p:titleStyle`, `a:defaultTextStyle`… → list style.
|
||||
pub fn list_style(imp: &mut Imp, part: &Part, ls: &El) -> ListStyle {
|
||||
let mut out = ListStyle::default();
|
||||
for e in ls.elements() {
|
||||
let n = e.local();
|
||||
let Some(l) = n.strip_prefix("lvl").and_then(|r| r.strip_suffix("pPr")).and_then(|d| d.parse::<u8>().ok()) else { continue };
|
||||
if !(1..=9).contains(&l) {
|
||||
continue;
|
||||
}
|
||||
let (_, para, run) = ppr(imp, part, e);
|
||||
out.set(l - 1, LevelStyle { para, run: run.unwrap_or_default() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn text_body(imp: &mut Imp, part: &Part, tx: &El) -> TextBody {
|
||||
let mut body = tx.child("bodyPr").map(body_pr).unwrap_or_default();
|
||||
if let Some(b) = tx.child("bodyPr") {
|
||||
let mut raw3d = String::new();
|
||||
if let Some(sc) = b.child("scene3d") {
|
||||
raw3d.push_str(&part.keep_inner(sc));
|
||||
}
|
||||
if let Some(sp) = b.child("sp3d").or_else(|| b.child("flatTx")) {
|
||||
raw3d.push_str(&part.keep_inner(sp));
|
||||
}
|
||||
if !raw3d.is_empty() && raw3d.len() <= 64 * 1024 {
|
||||
body.raw3d = Some(raw3d);
|
||||
}
|
||||
}
|
||||
let list_style = tx.child("lstStyle").map(|l| list_style(imp, part, l)).unwrap_or_default();
|
||||
let paragraphs = tx.children_named("p").take(100_000).map(|p| paragraph(imp, part, p)).collect();
|
||||
TextBody { body, list_style, paragraphs }
|
||||
}
|
||||
|
||||
const MAX_PARAGRAPH_RUNS: usize = 10_000;
|
||||
|
||||
/// The run properties of `e`'s `rPr` child, or the defaults.
|
||||
fn run_props(imp: &mut Imp, part: &Part, e: &El) -> RunProps {
|
||||
e.child("rPr").map(|r| rpr(imp, part, r)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Appends the runs of an `a:r` text, where a vertical tab or line feed is a line break, as it
|
||||
/// lays out and as export writes it.
|
||||
fn push_text_runs(para: &mut Paragraph, props: RunProps, text: &str) {
|
||||
for (i, piece) in text.split(['\u{b}', '\n']).enumerate() {
|
||||
if para.runs.len() >= MAX_PARAGRAPH_RUNS {
|
||||
break;
|
||||
}
|
||||
if i > 0 {
|
||||
para.runs.push(Run { text: String::new(), props: props.clone(), kind: RunKind::Break });
|
||||
}
|
||||
if !piece.is_empty() {
|
||||
if para.runs.len() >= MAX_PARAGRAPH_RUNS {
|
||||
break;
|
||||
}
|
||||
para.runs.push(Run { text: piece.to_string(), props: props.clone(), kind: RunKind::Text });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends an Office Math (a14:m) run: its plain text and its OMML.
|
||||
fn push_math_run(para: &mut Paragraph, part: &Part, e: &El) {
|
||||
if para.runs.len() < MAX_PARAGRAPH_RUNS {
|
||||
// The text of the outermost `t` elements: a `t` nested in another is already part of
|
||||
// the outer one's text, and taking it again would copy it once per nesting level.
|
||||
fn outer_t(e: &El, depth: usize, text: &mut String) {
|
||||
if depth > crate::xml::MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in e.elements() {
|
||||
if c.is("t") {
|
||||
text.push_str(&c.text());
|
||||
} else {
|
||||
outer_t(c, depth + 1, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut text = String::new();
|
||||
outer_t(e, 0, &mut text);
|
||||
let omml = e.elements().map(|c| part.keep_inner(c)).collect::<String>();
|
||||
para.runs.push(Run { text, props: RunProps::default(), kind: RunKind::Math { omml } });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn paragraph(imp: &mut Imp, part: &Part, p: &El) -> Paragraph {
|
||||
let mut para = Paragraph::default();
|
||||
for e in p.elements() {
|
||||
match e.local() {
|
||||
"pPr" => {
|
||||
let (lvl, pp, def) = ppr(imp, part, e);
|
||||
para.level = lvl.unwrap_or(0);
|
||||
para.props = pp;
|
||||
if let Some(d) = def {
|
||||
para.def_props = d;
|
||||
}
|
||||
}
|
||||
"r" => {
|
||||
let props = run_props(imp, part, e);
|
||||
let text: String = e.child("t").map(|t| t.text()).unwrap_or_default();
|
||||
push_text_runs(&mut para, props, &text);
|
||||
}
|
||||
"br" if para.runs.len() < MAX_PARAGRAPH_RUNS => {
|
||||
let props = run_props(imp, part, e);
|
||||
para.runs.push(Run { text: String::new(), props, kind: RunKind::Break });
|
||||
}
|
||||
"fld" if para.runs.len() < MAX_PARAGRAPH_RUNS => {
|
||||
let props = run_props(imp, part, e);
|
||||
let text = e.child("t").map(|t| t.text()).unwrap_or_default();
|
||||
para.runs.push(Run { text, props, kind: RunKind::Field { field: e.attr("type").unwrap_or("").to_string() } });
|
||||
}
|
||||
"m" => push_math_run(&mut para, part, e),
|
||||
"endParaRPr" => para.end_props = rpr(imp, part, e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
para
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::xml::parse;
|
||||
|
||||
#[test]
|
||||
fn nested_math_text_is_taken_once() {
|
||||
// 200 `m:t` nested in each other around one word: the word, not 200 copies of it.
|
||||
let x = format!(r#"<a14:m xmlns:a14="a" xmlns:m="m"><m:oMath>{}word{}</m:oMath></a14:m>"#, "<m:t>".repeat(200), "</m:t>".repeat(200));
|
||||
let d = parse(x.as_bytes()).unwrap();
|
||||
let part = Part {
|
||||
name: "ppt/slides/slide1.xml".into(),
|
||||
rels: Default::default(),
|
||||
ns: vec![],
|
||||
inner_ns: vec![],
|
||||
ns_budget: std::cell::Cell::new(1 << 20),
|
||||
};
|
||||
let mut para = Paragraph::default();
|
||||
push_math_run(&mut para, &part, &d.root);
|
||||
assert_eq!(para.runs[0].text, "word");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_and_transforms() {
|
||||
let d = parse(
|
||||
br#"<a:solidFill xmlns:a="x"><a:schemeClr val="accent2"><a:lumMod val="75000"/><a:alpha val="50000"/></a:schemeClr></a:solidFill>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let c = color(&d.root).unwrap();
|
||||
assert_eq!(c.base, ColorBase::Scheme { slot: SchemeSlot::Accent2 });
|
||||
assert_eq!(c.mods, vec![ColorTransform::LumMod(75000), ColorTransform::Alpha(50000)]);
|
||||
let d = parse(br#"<x><a:sysClr val="window" lastClr="FFFFFF"/></x>"#).unwrap();
|
||||
assert!(matches!(color(&d.root).unwrap().base, ColorBase::System { last: Rgba::WHITE, .. }));
|
||||
let d = parse(br#"<x><a:scrgbClr r="100000" g="0" b="0"/></x>"#).unwrap();
|
||||
assert_eq!(color(&d.root).unwrap().base, ColorBase::Rgb { rgb: Rgba::rgb(255, 0, 0) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullet_point_size_trims_schema_whitespace() {
|
||||
let d = parse(br#"<a:buSzPts xmlns:a="x" val=" 1400 "/>"#).unwrap();
|
||||
assert_eq!(bullet_size_points(d.root.attr("val")), Some(14.0));
|
||||
assert_eq!(bullet_size_points(Some("1400")), Some(14.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullet_percentage_size_accepts_numeric_and_percent_forms() {
|
||||
assert_eq!(bullet_size_percent(Some("100000")), Some(1.0));
|
||||
assert_eq!(bullet_size_percent(Some("100%")), Some(1.0));
|
||||
assert_eq!(bullet_size_percent(Some(" 125% ")), Some(1.25));
|
||||
assert_eq!(bullet_size_percent(Some("invalid")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn miter_limit_accepts_both_percentage_forms_with_schema_bounds() {
|
||||
assert_eq!(parse_miter_limit("200000"), Some(200_000));
|
||||
assert_eq!(parse_miter_limit("200%"), Some(200_000));
|
||||
assert_eq!(parse_miter_limit("1000001"), Some(1_000_001));
|
||||
assert_eq!(parse_miter_limit("malformed"), None);
|
||||
assert_eq!(parse_miter_limit("2147483648"), None);
|
||||
assert_eq!(parse_miter_limit("2147483.648%"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_props() {
|
||||
let d = parse(br#"<a:bodyPr lIns="91440" anchor="ctr" wrap="none" vert="vert270" numCol="2"><a:normAutofit fontScale="62500" lnSpcReduction="20000"/></a:bodyPr>"#).unwrap();
|
||||
let b = body_pr(&d.root);
|
||||
assert_eq!(b.inset_l, Some(7.2));
|
||||
assert_eq!(b.anchor, Some(Anchor::Middle));
|
||||
assert_eq!(b.wrap, Some(false));
|
||||
assert_eq!(b.vert, Some(TextDir::Vertical270));
|
||||
assert_eq!(b.columns, Some(2));
|
||||
assert_eq!(b.autofit, Some(AutoFit::Shrink { font_scale: Some(0.625), line_reduction: 0.2 }));
|
||||
assert_eq!(b.space_first_last, None);
|
||||
// A bare `<a:normAutofit/>` keeps no scale: the schema default 100 % is drawn as it is,
|
||||
// not the same as a saved 100 % (`fontScale="100000"`) (#724).
|
||||
let d = parse(br#"<a:bodyPr><a:normAutofit/></a:bodyPr>"#).unwrap();
|
||||
assert_eq!(body_pr(&d.root).autofit, Some(AutoFit::Shrink { font_scale: None, line_reduction: 0.0 }));
|
||||
let d = parse(br#"<a:bodyPr><a:normAutofit fontScale="100000"/></a:bodyPr>"#).unwrap();
|
||||
assert_eq!(body_pr(&d.root).autofit, Some(AutoFit::Shrink { font_scale: Some(1.0), line_reduction: 0.0 }));
|
||||
let d = parse(br#"<a:bodyPr spcFirstLastPara="1"/>"#).unwrap();
|
||||
assert_eq!(body_pr(&d.root).space_first_last, Some(true));
|
||||
// mongolianVert is its own direction (PowerPoint runs its lines left to right) and is
|
||||
// written back as it was read.
|
||||
let d = parse(br#"<a:bodyPr vert="mongolianVert"/>"#).unwrap();
|
||||
let b = body_pr(&d.root);
|
||||
assert_eq!(b.vert, Some(TextDir::MongolianVertical));
|
||||
assert_eq!(b.vert.map(|v| v.xml()), Some("mongolianVert"));
|
||||
let d = parse(br#"<a:bodyPr vert="wordArtVertRtl"/>"#).unwrap();
|
||||
assert_eq!(body_pr(&d.root).vert.map(|v| v.xml()), Some("wordArtVertRtl"));
|
||||
}
|
||||
}
|
||||
@@ -1,924 +0,0 @@
|
||||
//! Shape trees: `p:sp`, `p:pic`, `p:grpSp`, `p:cxnSp`, `p:graphicFrame` (tables, charts, SmartArt,
|
||||
//! OLE and other objects) and `p:contentPart` (3-D models).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use deckcraft_color::SchemeSlot;
|
||||
use deckcraft_geom::{Xfrm, preset};
|
||||
use deckcraft_model::style::{ColorRef, Effects, Fill};
|
||||
use deckcraft_model::table::{Cell, Row, Table};
|
||||
use deckcraft_model::text::{Anchor, TextDir};
|
||||
use deckcraft_model::{Geom, MediaClip, PhType, Placeholder, Shape, ShapeId, ShapeKind, ShapeStyle};
|
||||
|
||||
use super::{Imp, Part, dml};
|
||||
use crate::xml::El;
|
||||
|
||||
/// File shape ids at or above this are reassigned.
|
||||
pub const MAX_KEPT_ID: u32 = 1 << 30;
|
||||
const MAX_TREE_DEPTH: usize = 32;
|
||||
const MAX_SHAPES: usize = 20_000;
|
||||
|
||||
/// Shape id bookkeeping for one part.
|
||||
#[derive(Default)]
|
||||
pub struct IdCtx {
|
||||
pub used: HashSet<u32>,
|
||||
/// File id → model id.
|
||||
pub map: HashMap<u32, ShapeId>,
|
||||
/// Always allocate new ids (shapes pulled in from other parts).
|
||||
pub fresh: bool,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
impl IdCtx {
|
||||
fn assign(&mut self, imp: &mut Imp, file_id: Option<u32>) -> ShapeId {
|
||||
if !self.fresh
|
||||
&& let Some(i) = file_id
|
||||
&& (2..MAX_KEPT_ID).contains(&i)
|
||||
&& !self.used.contains(&i)
|
||||
{
|
||||
self.used.insert(i);
|
||||
self.map.insert(i, ShapeId(i));
|
||||
return ShapeId(i);
|
||||
}
|
||||
let n = imp.alloc();
|
||||
self.used.insert(n);
|
||||
if let Some(i) = file_id {
|
||||
self.map.entry(i).or_insert(ShapeId(n));
|
||||
}
|
||||
ShapeId(n)
|
||||
}
|
||||
pub fn lookup(&self, file_id: u32) -> Option<ShapeId> {
|
||||
self.map.get(&file_id).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the children of an `spTree` / `grpSp`.
|
||||
pub fn sp_tree(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, tree: &El, depth: usize) -> Vec<Shape> {
|
||||
let mut out = vec![];
|
||||
if depth > MAX_TREE_DEPTH {
|
||||
log::warn!("pptx: group nesting too deep in {}", part.name);
|
||||
return out;
|
||||
}
|
||||
for e in tree.elements() {
|
||||
if ctx.count >= MAX_SHAPES {
|
||||
log::warn!("pptx: too many shapes in {}", part.name);
|
||||
break;
|
||||
}
|
||||
let s = match e.local() {
|
||||
"sp" => Some(sp(imp, part, ctx, e)),
|
||||
"pic" => Some(pic(imp, part, ctx, e)),
|
||||
"grpSp" => Some(grp(imp, part, ctx, e, depth)),
|
||||
"cxnSp" => Some(cxn(imp, part, ctx, e)),
|
||||
"graphicFrame" => Some(frame(imp, part, ctx, e, depth)),
|
||||
"contentPart" => content_part(imp, part, ctx, e).or_else(|| {
|
||||
log::warn!("pptx: content part in {} not imported", part.name);
|
||||
None
|
||||
}),
|
||||
"AlternateContent" => read_model_alternate(imp, part, ctx, e),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(s) = s {
|
||||
ctx.count += 1;
|
||||
out.push(s);
|
||||
}
|
||||
}
|
||||
if depth == 0 {
|
||||
remap_connectors(&mut out, ctx, 0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// ActiveX controls (`p:controls`): each control's picture (`p:pic`), the image PowerPoint shows
|
||||
/// for it, as a picture above the slide's shapes. Controls without one are left out.
|
||||
pub fn controls(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, controls: &El) -> Vec<Shape> {
|
||||
let mut out = vec![];
|
||||
for c in controls.children_named("control") {
|
||||
if ctx.count >= MAX_SHAPES {
|
||||
break;
|
||||
}
|
||||
if let Some(p) = c.child("pic") {
|
||||
ctx.count += 1;
|
||||
out.push(pic(imp, part, ctx, p));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn remap_connectors(shapes: &mut [Shape], ctx: &IdCtx, depth: usize) {
|
||||
if depth > MAX_TREE_DEPTH {
|
||||
return;
|
||||
}
|
||||
for s in shapes.iter_mut() {
|
||||
match &mut s.kind {
|
||||
ShapeKind::Connector { start, end } => {
|
||||
for e in [start, end] {
|
||||
*e = e.and_then(|(id, site)| ctx.lookup(id.0).map(|m| (m, site)));
|
||||
}
|
||||
}
|
||||
ShapeKind::Group { children, .. } => remap_connectors(children, ctx, depth + 1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PowerPoint's Lock (right-click > Lock, the Selection pane padlock) writes a full set of locking
|
||||
/// attributes; it reads an object as locked only when the whole set for its kind is there, so a
|
||||
/// lone `noMove` or `noResize` (other tools' partial locks) isn't Lock.
|
||||
fn is_locked(l: &El) -> bool {
|
||||
let set: &[&str] = match l.local() {
|
||||
"grpSpLocks" => &["noGrp", "noUngrp", "noRot", "noMove", "noResize"],
|
||||
"graphicFrameLocks" => &["noGrp", "noDrilldown", "noMove", "noResize"],
|
||||
_ => &["noGrp", "noRot", "noMove", "noResize", "noEditPoints", "noAdjustHandles", "noChangeArrowheads", "noChangeShapeType"],
|
||||
};
|
||||
set.iter().all(|a| l.bool(a) == Some(true))
|
||||
}
|
||||
|
||||
/// Common non-visual properties (`p:nvSpPr`, `p:nvPicPr`…).
|
||||
fn base(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, nv: Option<&El>) -> Shape {
|
||||
let c = nv.and_then(|n| n.child("cNvPr"));
|
||||
let mut s = Shape { id: ctx.assign(imp, c.and_then(|c| c.u32("id"))), ..Default::default() };
|
||||
if let Some(c) = c {
|
||||
s.name = c.attr("name").unwrap_or("").to_string();
|
||||
s.descr = c.attr("descr").unwrap_or("").to_string();
|
||||
s.title = c.attr("title").unwrap_or("").to_string();
|
||||
s.hidden = c.bool("hidden").unwrap_or(false);
|
||||
s.click = c.child("hlinkClick").and_then(|h| dml::hyperlink(imp, part, h));
|
||||
s.hover = c.child("hlinkHover").and_then(|h| dml::hyperlink(imp, part, h));
|
||||
s.decorative = c.find("decorative").and_then(|d| d.bool("val")).unwrap_or(false);
|
||||
}
|
||||
if let Some(nv) = nv {
|
||||
for e in nv.elements() {
|
||||
match e.local() {
|
||||
"cNvSpPr" => {
|
||||
s.text_box = e.bool("txBox").unwrap_or(false);
|
||||
s.locked = e.child("spLocks").is_some_and(is_locked);
|
||||
}
|
||||
"cNvPicPr" | "cNvGrpSpPr" | "cNvCxnSpPr" | "cNvGraphicFramePr" => {
|
||||
s.locked = e.elements().find(|l| l.local().ends_with("Locks")).is_some_and(is_locked);
|
||||
}
|
||||
"nvPr" => {
|
||||
if let Some(ph) = e.child("ph") {
|
||||
s.ph = Some(Placeholder {
|
||||
kind: ph.attr("type").map(PhType::from_xml).unwrap_or(PhType::Obj),
|
||||
idx: ph.u32("idx").unwrap_or(0),
|
||||
vertical: ph.attr("orient") == Some("vert"),
|
||||
size: ph.attr("sz").map(String::from),
|
||||
has_custom_prompt: ph.bool("hasCustomPrompt").unwrap_or(false),
|
||||
});
|
||||
}
|
||||
s.tags = super::tags(imp, part, e);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn preset_geom(pg: &El) -> Geom {
|
||||
let name = pg.attr("prst").unwrap_or("rect").to_string();
|
||||
let defaults: Vec<f64> = preset::adjust_defaults(&name).to_vec();
|
||||
let mut adj = defaults;
|
||||
let mut any = false;
|
||||
if let Some(av) = pg.child("avLst") {
|
||||
for gd in av.children_named("gd").take(16) {
|
||||
let n = gd.attr("name").unwrap_or("");
|
||||
let idx = if n == "adj" {
|
||||
0
|
||||
} else if let Some(k) = n.strip_prefix("adj").and_then(|k| k.parse::<usize>().ok()).filter(|k| (1..=16).contains(k)) {
|
||||
k - 1
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let Some(v) =
|
||||
gd.attr("fmla").and_then(|f| f.trim().strip_prefix("val")).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if adj.len() <= idx {
|
||||
adj.resize(idx + 1, 0.0);
|
||||
}
|
||||
if let Some(slot) = adj.get_mut(idx) {
|
||||
*slot = v;
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
adj.clear();
|
||||
}
|
||||
Geom::Preset { name, adj }
|
||||
}
|
||||
|
||||
/// A placeholder whose `spPr` names no geometry takes its layout's (or master's) placeholder's:
|
||||
/// marked here with an empty custom geometry, filled in once the layouts are read
|
||||
/// (`inherit_placeholder_geometry`).
|
||||
fn mark_inherited_geometry(s: &mut Shape, pr: Option<&El>) {
|
||||
if s.ph.is_some() && pr.is_none_or(|pr| pr.child("prstGeom").is_none() && pr.child("custGeom").is_none()) {
|
||||
s.geom = Geom::Custom { paths: vec![] };
|
||||
}
|
||||
}
|
||||
|
||||
/// `spPr` → transform, geometry, fill, line, effects.
|
||||
fn sp_pr(imp: &mut Imp, part: &Part, s: &mut Shape, pr: &El) {
|
||||
if let Some(x) = pr.child("xfrm") {
|
||||
s.xfrm = Some(dml::xfrm(x).0);
|
||||
}
|
||||
if let Some(pg) = pr.child("prstGeom") {
|
||||
s.geom = preset_geom(pg);
|
||||
} else if let Some(cg) = pr.child("custGeom") {
|
||||
let (w, h) = s.xfrm.map(|x| (deckcraft_geom::pt_to_emu(x.w) as f64, deckcraft_geom::pt_to_emu(x.h) as f64)).unwrap_or((21600.0, 21600.0));
|
||||
let paths = crate::custgeom::read_cust_geom(cg, w, h);
|
||||
if !paths.is_empty() {
|
||||
s.geom = Geom::Custom { paths };
|
||||
}
|
||||
}
|
||||
s.fill = dml::fill_of(imp, part, pr);
|
||||
if let Some(ln) = pr.child("ln") {
|
||||
s.line = Some(dml::line(imp, part, ln));
|
||||
}
|
||||
if let Some(fx) = pr.child("effectLst") {
|
||||
s.effects = Some(dml::effects(fx));
|
||||
}
|
||||
let raw: String = pr.elements().filter(|c| c.is("scene3d") || c.is("sp3d")).map(|c| part.keep(c)).collect();
|
||||
if !raw.is_empty() {
|
||||
let fx = s.effects.get_or_insert_with(Effects::default);
|
||||
fx.bevel = pr.path(&["sp3d", "bevelT"]).map(|b| b.attr("prst").unwrap_or("circle").to_string());
|
||||
fx.raw3d = Some(raw);
|
||||
}
|
||||
}
|
||||
|
||||
fn style(st: &El) -> ShapeStyle {
|
||||
let r = |n: &str| {
|
||||
st.child(n)
|
||||
.map(|e| (e.u32("idx").unwrap_or(0).min(1003), dml::color(e).unwrap_or(ColorRef::scheme(SchemeSlot::Accent1))))
|
||||
.unwrap_or((0, ColorRef::scheme(SchemeSlot::Accent1)))
|
||||
};
|
||||
let font = st.child("fontRef");
|
||||
ShapeStyle {
|
||||
line_ref: r("lnRef"),
|
||||
fill_ref: r("fillRef"),
|
||||
effect_ref: r("effectRef"),
|
||||
font_ref: (font.and_then(|f| f.attr("idx")).unwrap_or("minor").to_string(), font.and_then(dml::color)),
|
||||
}
|
||||
}
|
||||
|
||||
fn sp(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Shape {
|
||||
let mut s = base(imp, part, ctx, e.child("nvSpPr"));
|
||||
if let Some(pr) = e.child("spPr") {
|
||||
sp_pr(imp, part, &mut s, pr);
|
||||
}
|
||||
mark_inherited_geometry(&mut s, e.child("spPr"));
|
||||
if e.bool("useBgFill") == Some(true) {
|
||||
s.fill = Some(Fill::Background);
|
||||
}
|
||||
s.style = e.child("style").map(style);
|
||||
s.text = e.child("txBody").map(|t| dml::text_body(imp, part, t));
|
||||
s
|
||||
}
|
||||
|
||||
fn ms(v: Option<&str>) -> u32 {
|
||||
v.and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, u32::MAX as f64) as u32).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn find_content_part(el: &El) -> Option<&El> {
|
||||
fn rec(el: &El, depth: usize) -> Option<&El> {
|
||||
if depth > 16 {
|
||||
return None;
|
||||
}
|
||||
if el.is("contentPart") {
|
||||
return Some(el);
|
||||
}
|
||||
el.elements().find_map(|c| rec(c, depth + 1))
|
||||
}
|
||||
rec(el, 0)
|
||||
}
|
||||
|
||||
/// `p:contentPart` whose relationship is a 3-D model. Other content parts (ink) are left out.
|
||||
fn content_part(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Option<Shape> {
|
||||
let id = e.attr("r:id").filter(|s| !s.is_empty())?;
|
||||
let rel = part.rels.get(id)?;
|
||||
if !super::is_model3d(rel) {
|
||||
return None;
|
||||
}
|
||||
let target = rel.target.clone();
|
||||
let media = imp.media_for(&target).or_else(|| {
|
||||
log::warn!("pptx: 3-D model part missing in {}", part.name);
|
||||
None
|
||||
})?;
|
||||
let mut s = base(imp, part, ctx, e.child("nvContentPartPr"));
|
||||
if let Some(x) = e.child("xfrm") {
|
||||
s.xfrm = Some(dml::xfrm(x).0);
|
||||
}
|
||||
s.kind = ShapeKind::Model3d { media, poster: None };
|
||||
Some(s)
|
||||
}
|
||||
|
||||
/// A 3-D model wrapped in `mc:AlternateContent`: the model choice, plus the fallback picture.
|
||||
/// If the model part is missing, the fallback picture is the shape.
|
||||
fn read_model_alternate(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Option<Shape> {
|
||||
if let Some(content) = e.children_named("Choice").find_map(find_content_part)
|
||||
&& let Some(mut s) = content_part(imp, part, ctx, content)
|
||||
{
|
||||
let poster = e.child("Fallback").and_then(|fb| {
|
||||
let mut pics = vec![];
|
||||
fb.find_all("blip", &mut pics);
|
||||
pics.into_iter().find_map(|b| dml::media_ref(imp, part, b))
|
||||
});
|
||||
if let ShapeKind::Model3d { media, .. } = s.kind {
|
||||
s.kind = ShapeKind::Model3d { media, poster };
|
||||
}
|
||||
return Some(s);
|
||||
}
|
||||
e.child("Fallback").and_then(|fb| fb.elements().find(|c| c.is("pic")).map(|p| pic(imp, part, ctx, p)))
|
||||
}
|
||||
|
||||
fn pic(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Shape {
|
||||
let mut s = base(imp, part, ctx, e.child("nvPicPr"));
|
||||
if let Some(pr) = e.child("spPr") {
|
||||
sp_pr(imp, part, &mut s, pr);
|
||||
}
|
||||
// A picture in a picture placeholder is cut into the layout's shape (a circle, say).
|
||||
mark_inherited_geometry(&mut s, e.child("spPr"));
|
||||
s.style = e.child("style").map(style);
|
||||
let pf = e.child("blipFill").and_then(|b| dml::blip_fill(imp, part, b));
|
||||
let nvpr = e.path(&["nvPicPr", "nvPr"]);
|
||||
let vf = nvpr.and_then(|n| n.child("videoFile"));
|
||||
let af = nvpr.and_then(|n| n.child("audioFile"));
|
||||
let p14 = nvpr.and_then(|n| n.child("extLst")).and_then(|x| x.find("media"));
|
||||
if vf.is_some() || af.is_some() || p14.is_some() {
|
||||
let media = p14.and_then(|m| dml::media_ref(imp, part, m)).or_else(|| vf.or(af).and_then(|f| dml::media_ref(imp, part, f)));
|
||||
if let Some(media) = media {
|
||||
let mut clip = MediaClip {
|
||||
media,
|
||||
video: vf.is_some() || af.is_none(),
|
||||
poster: pf.as_ref().map(|p| p.media),
|
||||
crop: pf.as_ref().map(|p| p.crop).unwrap_or_default(),
|
||||
volume: 1.0,
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(m) = p14 {
|
||||
if let Some(t) = m.child("trim") {
|
||||
clip.trim_start_ms = ms(t.attr("st"));
|
||||
clip.trim_end_ms = ms(t.attr("end"));
|
||||
}
|
||||
if let Some(f) = m.child("fade") {
|
||||
clip.fade_in_ms = ms(f.attr("in"));
|
||||
clip.fade_out_ms = ms(f.attr("out"));
|
||||
}
|
||||
if let Some(l) = m.child("bmkLst") {
|
||||
clip.bookmarks =
|
||||
l.children_named("bmk").take(1000).map(|b| (b.attr("name").unwrap_or("").to_string(), ms(b.attr("time")))).collect();
|
||||
}
|
||||
}
|
||||
s.kind = ShapeKind::Media(clip);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
match pf {
|
||||
Some(fill) => s.kind = ShapeKind::Picture { fill },
|
||||
None => log::warn!("pptx: picture {} in {} has no readable image", s.name, part.name),
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn grp(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> Shape {
|
||||
let mut s = base(imp, part, ctx, e.child("nvGrpSpPr"));
|
||||
let mut child = None;
|
||||
if let Some(pr) = e.child("grpSpPr") {
|
||||
if let Some(x) = pr.child("xfrm") {
|
||||
let (xf, ch) = dml::xfrm(x);
|
||||
s.xfrm = Some(xf);
|
||||
child = ch;
|
||||
}
|
||||
s.fill = dml::fill_of(imp, part, pr);
|
||||
if let Some(fx) = pr.child("effectLst") {
|
||||
s.effects = Some(dml::effects(fx));
|
||||
}
|
||||
if let Some(sc) = pr.child("scene3d") {
|
||||
let raw = part.keep_inner(sc);
|
||||
if !raw.is_empty() && raw.len() <= 64 * 1024 {
|
||||
s.effects.get_or_insert_with(Effects::default).raw3d = Some(raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
let children = sp_tree(imp, part, ctx, e, depth + 1);
|
||||
let child = child.or_else(|| s.xfrm.map(|x| Xfrm::new(x.x, x.y, x.w, x.h))).unwrap_or_default();
|
||||
s.kind = ShapeKind::Group { children, child };
|
||||
s
|
||||
}
|
||||
|
||||
fn cxn(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Shape {
|
||||
let nv = e.child("nvCxnSpPr");
|
||||
let mut s = base(imp, part, ctx, nv);
|
||||
if let Some(pr) = e.child("spPr") {
|
||||
sp_pr(imp, part, &mut s, pr);
|
||||
}
|
||||
s.style = e.child("style").map(style);
|
||||
let c = nv.and_then(|n| n.child("cNvCxnSpPr"));
|
||||
let end = |n: &str| c.and_then(|c| c.child(n)).and_then(|x| Some((ShapeId(x.u32("id")?), x.u32("idx").unwrap_or(0))));
|
||||
s.kind = ShapeKind::Connector { start: end("stCxn"), end: end("endCxn") };
|
||||
s
|
||||
}
|
||||
|
||||
fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> Shape {
|
||||
let mut s = base(imp, part, ctx, e.child("nvGraphicFramePr"));
|
||||
if let Some(x) = e.child("xfrm") {
|
||||
s.xfrm = Some(dml::xfrm(x).0);
|
||||
}
|
||||
let gd = e.path(&["graphic", "graphicData"]);
|
||||
let uri = gd.and_then(|g| g.attr("uri")).unwrap_or("");
|
||||
if let Some(gd) = gd {
|
||||
if let Some(tbl) = gd.child("tbl") {
|
||||
s.kind = ShapeKind::Table(table(imp, part, tbl));
|
||||
return s;
|
||||
}
|
||||
if let Some(c) = gd.child("chart")
|
||||
&& let Some(chart) = super::chart::frame_chart(imp, part, c.attr("r:id").unwrap_or(""), uri)
|
||||
{
|
||||
s.kind = ShapeKind::Chart(Box::new(chart));
|
||||
return s;
|
||||
}
|
||||
if uri.ends_with("/diagram")
|
||||
&& let Some(g) = smartart(imp, part, gd, &s, depth)
|
||||
{
|
||||
return g;
|
||||
}
|
||||
}
|
||||
// Something we don't model: keep its XML and show a preview picture when it has one.
|
||||
let preview = {
|
||||
let mut pics = vec![];
|
||||
e.find_all("blip", &mut pics);
|
||||
pics.into_iter().find_map(|b| dml::media_ref(imp, part, b))
|
||||
}
|
||||
.or_else(|| gd.and_then(|g| g.find("oleObj")).and_then(|o| vml_preview(imp, part, o.attr("spid")?)));
|
||||
// An embedded object's fallback picture (`p:oleObj/p:pic`) can carry a fill and an outline,
|
||||
// which PowerPoint draws behind and around the preview (old equation objects on coloured
|
||||
// boxes). The frame's own position stays.
|
||||
if let Some(pr) = gd.and_then(|g| g.find("oleObj")).and_then(|o| o.find("pic")).and_then(|p| p.child("spPr")) {
|
||||
if s.fill.is_none() {
|
||||
s.fill = dml::fill_of(imp, part, pr);
|
||||
}
|
||||
if s.line.is_none() {
|
||||
s.line = pr.child("ln").map(|ln| dml::line(imp, part, ln));
|
||||
}
|
||||
}
|
||||
let label = if let Some(o) = gd.and_then(|g| g.find("oleObj")) {
|
||||
o.attr("progId").or(o.attr("name")).unwrap_or("Object").to_string()
|
||||
} else if uri.ends_with("/diagram") {
|
||||
"SmartArt".to_string()
|
||||
} else if uri.contains("chart") {
|
||||
"Chart".to_string()
|
||||
} else {
|
||||
uri.rsplit('/').next().unwrap_or("Object").to_string()
|
||||
};
|
||||
// Keep the parts it points to so a save writes it back whole (#203). A part with relationships
|
||||
// of its own, or an external link, can't be carried: the save then falls back to the preview.
|
||||
// Validate every relationship (and charge the budget) before copying anything, so a fallback
|
||||
// that cannot be kept whole copies no part at all.
|
||||
let mark = imp.mark();
|
||||
let mut planned = Vec::new();
|
||||
let mut spent = imp.diagram_xml_bytes;
|
||||
let mut ok = true;
|
||||
for id in super::rel_refs(e) {
|
||||
let Some(rel) = part.rels.get(&id).filter(|r| !r.external) else {
|
||||
ok = false;
|
||||
break;
|
||||
};
|
||||
let pkg = imp.pkg;
|
||||
if *imp.has_rels.entry(crate::opc::norm(&rel.target)).or_insert_with(|| !pkg.rels(&rel.target).items.is_empty()) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
// A diagram's definition parts copied here count against the same presentation-wide budget.
|
||||
if rel.kind.starts_with("diagram") && !imp.media_by_part.contains_key(&crate::opc::norm(&rel.target)) {
|
||||
let len = pkg.get(&rel.target).map_or(0, |b| b.len());
|
||||
if len > MAX_DIAGRAM_PART_BYTES || spent.saturating_add(len) > MAX_DIAGRAM_XML_BYTES {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
spent += len;
|
||||
}
|
||||
if pkg.get(&rel.target).is_none() {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
planned.push((id, rel.ty.clone(), rel.target.clone(), rel.kind == "diagramData"));
|
||||
}
|
||||
let parts = if ok {
|
||||
imp.diagram_xml_bytes = spent;
|
||||
let copied: Option<Vec<_>> = planned
|
||||
.into_iter()
|
||||
.map(|(id, kind, target, data)| {
|
||||
let media = if data { diagram_data(imp, &target) } else { imp.media_for(&target) };
|
||||
Some((id, kind, media?))
|
||||
})
|
||||
.collect();
|
||||
if copied.is_none() {
|
||||
imp.rollback(&mark);
|
||||
}
|
||||
copied
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let parts = parts.unwrap_or_default();
|
||||
s.kind = ShapeKind::Opaque { xml: part.keep(e), preview, label, parts };
|
||||
s
|
||||
}
|
||||
|
||||
/// The preview picture of an old-style embedded object (`p:oleObj spid` with no `p:pic`): the
|
||||
/// `v:imagedata` of the legacy VML drawing shape with that id, as PowerPoint 2007 wrote them.
|
||||
fn vml_preview(imp: &mut Imp, part: &Part, spid: &str) -> Option<deckcraft_model::MediaId> {
|
||||
for rel in part.rels.items.iter().filter(|r| r.kind == "vmlDrawing" && !r.external) {
|
||||
let key = crate::opc::norm(&rel.target);
|
||||
if !imp.vml_previews.contains_key(&key) {
|
||||
let index = vml_index(imp.pkg, &rel.target);
|
||||
imp.vml_previews.insert(key.clone(), index);
|
||||
}
|
||||
let Some(target) = imp.vml_previews.get(&key).and_then(|m| m.get(spid)).cloned() else { continue };
|
||||
return imp.media_for(&target);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Every shape id in a VML drawing with a picture, mapped to that picture's part: parsed once per
|
||||
/// drawing however many objects look it up.
|
||||
fn vml_index(pkg: &crate::opc::Package, vml: &str) -> std::collections::HashMap<String, String> {
|
||||
let mut out = std::collections::HashMap::new();
|
||||
let Some(doc) = pkg.xml(vml) else { return out };
|
||||
let rels = pkg.rels(vml);
|
||||
let mut shapes = vec![];
|
||||
doc.root.find_all("shape", &mut shapes);
|
||||
for s in shapes {
|
||||
let Some(id) = s.attr("id") else { continue };
|
||||
if out.contains_key(id) {
|
||||
continue; // the first shape with an id wins, as the old lookup did
|
||||
}
|
||||
let Some(img) = s.find("imagedata") else { continue };
|
||||
let Some(rid) = img.attr("o:relid").or(img.attr("r:id")) else { continue };
|
||||
if let Some(r) = rels.get(rid).filter(|r| !r.external) {
|
||||
out.insert(id.to_string(), r.target.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A diagram's data part, without the link to its cached drawing: that link is a slide
|
||||
/// relationship id, which a save renumbers. Only diagrams whose drawing is missing or empty get
|
||||
/// here, and those are drawn from their data.
|
||||
fn diagram_data(imp: &mut Imp, target: &str) -> Option<deckcraft_model::MediaId> {
|
||||
let norm_target = crate::opc::norm(target);
|
||||
if let Some(&id) = imp.media_by_part.get(&norm_target) {
|
||||
return Some(id);
|
||||
}
|
||||
fn strip(e: &mut El, depth: usize) {
|
||||
if depth > crate::xml::MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
e.children.retain(|n| !matches!(n, crate::xml::Node::El(c) if c.is("ext") && c.find("dataModelExt").is_some()));
|
||||
for c in e.elements_mut() {
|
||||
strip(c, depth + 1);
|
||||
}
|
||||
}
|
||||
let mut doc = imp.pkg.xml(target)?;
|
||||
strip(&mut doc.root, 0);
|
||||
let xml = format!("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n{}", doc.root.to_xml());
|
||||
let id = deckcraft_model::MediaId(imp.alloc());
|
||||
let content_type = imp.pkg.content_type(target)?;
|
||||
imp.media.push(deckcraft_model::MediaItem {
|
||||
id,
|
||||
name: crate::opc::file_of(target).to_string(),
|
||||
content_type,
|
||||
data: std::sync::Arc::new(xml.into_bytes()),
|
||||
link: None,
|
||||
});
|
||||
imp.media_keys.push(norm_target.clone());
|
||||
imp.media_by_part.insert(norm_target, id);
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// Shapes all SmartArt drawings of one presentation may add; a frame read after that is left as a
|
||||
/// placeholder. Each frame that references a drawing reads it again.
|
||||
const MAX_SMARTART_SHAPES: usize = 250_000;
|
||||
|
||||
/// SmartArt definition XML (layout, style, colours) all diagrams of one presentation may copy.
|
||||
const MAX_DIAGRAM_XML_BYTES: usize = 32 << 20;
|
||||
|
||||
/// The largest single diagram definition part copied.
|
||||
const MAX_DIAGRAM_PART_BYTES: usize = 4 << 20;
|
||||
|
||||
fn count_shapes(shapes: &[Shape]) -> usize {
|
||||
shapes.iter().map(|s| 1 + count_shapes(s.children())).sum()
|
||||
}
|
||||
|
||||
/// SmartArt: read the pre-drawn shapes of its drawing part as a group.
|
||||
fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> Option<Shape> {
|
||||
if depth > 8 || imp.smartart_shapes >= MAX_SMARTART_SHAPES {
|
||||
return None;
|
||||
}
|
||||
let rel_ids = gd.child("relIds")?;
|
||||
let dm = part.rels.get(rel_ids.attr("r:dm").unwrap_or(""))?;
|
||||
let data = imp.pkg.xml(&dm.target)?;
|
||||
let drawing_rel = data.root.find("dataModelExt").and_then(|x| x.attr("relId")).and_then(|id| part.rels.get(id)).map(|r| r.target.clone())?;
|
||||
let mut d = imp.pkg.xml(&drawing_rel)?;
|
||||
super::resolve_mc(&mut d.root, 0);
|
||||
let dpart = Part::new(imp.pkg, &drawing_rel, &d);
|
||||
let tree = d.root.child("spTree")?;
|
||||
let mut sub = IdCtx { fresh: true, ..Default::default() };
|
||||
let before = imp.smartart_shapes;
|
||||
let mark = imp.mark();
|
||||
let children = sp_tree(imp, &dpart, &mut sub, tree, depth + 1);
|
||||
if children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Counted once here, nested SmartArt included: a drawing that frames reuse counts every time it is read.
|
||||
let total = before.saturating_add(count_shapes(&children));
|
||||
if total > MAX_SMARTART_SHAPES {
|
||||
// Over the presentation's remaining budget: a placeholder, and nothing charged, nested SmartArt included.
|
||||
imp.smartart_shapes = before;
|
||||
imp.rollback(&mark);
|
||||
return None;
|
||||
}
|
||||
imp.smartart_shapes = total;
|
||||
let children = smartart_text_rects(imp, &mut sub, tree, children, depth + 1);
|
||||
let mut g = frame.clone();
|
||||
let x = frame.xfrm.unwrap_or_default();
|
||||
g.kind = ShapeKind::Group { children, child: Xfrm::new(0.0, 0.0, x.w, x.h) };
|
||||
g.diagram = diagram_outline(imp, part, rel_ids, &data.root);
|
||||
// Node pictures, from the blips of the data model's presentation points.
|
||||
if let Some(d) = &mut g.diagram {
|
||||
let rels = imp.pkg.rels(&dm.target);
|
||||
for (k, rid) in crate::dgm::node_pictures(&data.root) {
|
||||
let Some(target) = rels.get(&rid).filter(|r| !r.external).map(|r| r.target.clone()) else { continue };
|
||||
let media = imp.media_for(&target);
|
||||
if let Some(n) = d.nodes.get_mut(k) {
|
||||
n.picture = media;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(g)
|
||||
}
|
||||
|
||||
/// A SmartArt drawing shape (`dsp:sp`) keeps its text rectangle in `dsp:txXfrm`, apart from the
|
||||
/// shape's own box: the text of a narrow shape turned by 90° is often laid out across it. Put each
|
||||
/// shape's text on that rectangle. `shapes` are what [`sp_tree`] read from `tree`, in order.
|
||||
fn smartart_text_rects(imp: &mut Imp, ctx: &mut IdCtx, tree: &El, shapes: Vec<Shape>, depth: usize) -> Vec<Shape> {
|
||||
if depth > MAX_TREE_DEPTH {
|
||||
return shapes;
|
||||
}
|
||||
let mut out = Vec::with_capacity(shapes.len());
|
||||
let mut shapes = shapes.into_iter();
|
||||
// The same elements `sp_tree` turns into shapes.
|
||||
for e in tree.elements().filter(|e| matches!(e.local(), "sp" | "pic" | "grpSp" | "cxnSp" | "graphicFrame")) {
|
||||
let Some(mut s) = shapes.next() else { break };
|
||||
let mut text_box = None;
|
||||
match (e.local(), &mut s.kind) {
|
||||
("grpSp", ShapeKind::Group { children, .. }) => {
|
||||
let kids = std::mem::take(children);
|
||||
*children = smartart_text_rects(imp, ctx, e, kids, depth + 1);
|
||||
}
|
||||
("sp", ShapeKind::Shape) => {
|
||||
if let Some(t) = e.child("txXfrm") {
|
||||
text_box = text_on_rect(imp, ctx, &mut s, dml::xfrm(t).0);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.push(s);
|
||||
out.extend(text_box);
|
||||
}
|
||||
out.extend(shapes);
|
||||
out
|
||||
}
|
||||
|
||||
/// Lay out the text of `s` on `t`, a text rectangle in the same space as the shape's box, turned by
|
||||
/// the shape's rotation plus its own. When that is the shape's text area shrunk by some margin, the
|
||||
/// shape keeps its text with wider insets. Otherwise (a rectangle reaching outside the shape, or
|
||||
/// turned against it) the text moves to a new frameless text shape over `s`, which is returned:
|
||||
/// both export as plain DrawingML that any reader lays out the same way.
|
||||
fn text_on_rect(imp: &mut Imp, ctx: &mut IdCtx, s: &mut Shape, t: Xfrm) -> Option<Shape> {
|
||||
const EPS: f64 = 0.01;
|
||||
let x = s.xfrm?;
|
||||
if !x.is_finite() || !t.is_finite() || t.w <= EPS || t.h <= EPS {
|
||||
return None;
|
||||
}
|
||||
let body = s.text.as_mut().filter(|b| !b.is_empty())?;
|
||||
let turn = |a: f64| a.rem_euclid(360.0);
|
||||
let upright = |a: f64| turn(a + EPS) < 2.0 * EPS;
|
||||
let bp = &mut body.body;
|
||||
if !x.flip_h
|
||||
&& !x.flip_v
|
||||
&& upright(t.rot)
|
||||
&& bp.rot.is_none_or(upright)
|
||||
&& bp.vert.is_none_or(|v| v == TextDir::Horizontal)
|
||||
&& bp.upright != Some(true)
|
||||
{
|
||||
// Same orientation as the shape: express the rectangle as insets from the shape's text area.
|
||||
let c = x.affine().inverse() * t.center();
|
||||
let (l, top) = (c.x - t.w / 2.0, c.y - t.h / 2.0);
|
||||
let (r, b) = (l + t.w, top + t.h);
|
||||
let area = text_area(&s.geom, x.w, x.h);
|
||||
let extra = [l - area.x0, top - area.y0, area.x1 - r, area.y1 - b];
|
||||
if extra.iter().all(|v| v.is_finite() && *v >= -EPS) {
|
||||
let [el, et, er, eb] = extra.map(|v| v.max(0.0));
|
||||
bp.inset_l = Some(bp.inset_l.unwrap_or(7.2) + el);
|
||||
bp.inset_t = Some(bp.inset_t.unwrap_or(3.6) + et);
|
||||
bp.inset_r = Some(bp.inset_r.unwrap_or(7.2) + er);
|
||||
bp.inset_b = Some(bp.inset_b.unwrap_or(3.6) + eb);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if ctx.count >= MAX_SHAPES || imp.smartart_shapes >= MAX_SMARTART_SHAPES {
|
||||
return None;
|
||||
}
|
||||
ctx.count += 1;
|
||||
imp.smartart_shapes += 1;
|
||||
let text = s.text.take();
|
||||
// No fill, outline or effects; the style keeps only the text colour and font.
|
||||
let style = s.style.clone().map(|mut st| {
|
||||
st.fill_ref.0 = 0;
|
||||
st.line_ref.0 = 0;
|
||||
st.effect_ref.0 = 0;
|
||||
st
|
||||
});
|
||||
Some(Shape {
|
||||
id: ctx.assign(imp, None),
|
||||
name: s.name.clone(),
|
||||
xfrm: Some(Xfrm { rot: turn(x.rot + t.rot), flip_h: false, flip_v: false, ..t }),
|
||||
fill: Some(Fill::None),
|
||||
line: Some(deckcraft_model::style::Line { fill: Some(Fill::None), ..Default::default() }),
|
||||
style,
|
||||
text,
|
||||
click: s.click.clone(),
|
||||
hover: s.hover.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a shape's geometry puts its text, in shape-local points (as the renderer computes it).
|
||||
fn text_area(geom: &Geom, w: f64, h: f64) -> deckcraft_geom::Rect {
|
||||
let full = deckcraft_geom::Rect::new(0.0, 0.0, w, h);
|
||||
match geom {
|
||||
Geom::Preset { name, adj } => {
|
||||
preset::build(name, w, h, adj).or_else(|| preset::build("rect", w, h, &[])).map(|g| g.text_rect).unwrap_or(full)
|
||||
}
|
||||
Geom::Custom { .. } => full,
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline of a SmartArt graphic (for the Text Pane), with its layout, quick style and colour
|
||||
/// parts kept to be written back.
|
||||
fn diagram_outline(imp: &mut Imp, part: &Part, rel_ids: &El, data: &El) -> Option<deckcraft_model::Diagram> {
|
||||
let nodes = crate::dgm::outline(data);
|
||||
if nodes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (pkg, spent) = (imp.pkg, std::cell::Cell::new(imp.diagram_xml_bytes));
|
||||
let raw = |attr: &str| -> Option<String> {
|
||||
let rel = part.rels.get(rel_ids.attr(attr)?)?;
|
||||
let bytes = pkg.get(&rel.target)?;
|
||||
// Every diagram copies its definitions, so the copies share one presentation-wide budget.
|
||||
if bytes.len() > MAX_DIAGRAM_PART_BYTES || spent.get().saturating_add(bytes.len()) > MAX_DIAGRAM_XML_BYTES {
|
||||
return None;
|
||||
}
|
||||
let xml = String::from_utf8(bytes.to_vec()).ok()?;
|
||||
spent.set(spent.get() + xml.len());
|
||||
Some(xml)
|
||||
};
|
||||
let layout_xml = raw("r:lo");
|
||||
let (layout_id, cat) = layout_xml
|
||||
.as_deref()
|
||||
.and_then(|x| crate::xml::parse(x.as_bytes()).ok())
|
||||
.map(|d| {
|
||||
let cat = d.root.child("catLst").and_then(|c| c.child("cat")).and_then(|c| c.attr("type")).unwrap_or("").to_string();
|
||||
(d.root.attr("uniqueId").unwrap_or("").to_string(), cat)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let lo_type = data
|
||||
.path(&["ptLst"])
|
||||
.and_then(|l| l.children_named("pt").find(|p| p.attr("type") == Some("doc")))
|
||||
.and_then(|p| p.child("prSet"))
|
||||
.and_then(|p| p.attr("loTypeId"))
|
||||
.unwrap_or("");
|
||||
let id = if layout_id.is_empty() { lo_type.to_string() } else { layout_id };
|
||||
let pr = data.path(&["ptLst"]).and_then(|l| l.children_named("pt").find(|p| p.attr("type") == Some("doc"))).and_then(|p| p.child("prSet"));
|
||||
let style = crate::dgm::style_for(pr.and_then(|p| p.attr("qsTypeId")).unwrap_or("")).to_string();
|
||||
let colors = crate::dgm::colors_for(pr.and_then(|p| p.attr("csTypeId")).unwrap_or(""));
|
||||
let (style_xml, colors_xml) = (raw("r:qs"), raw("r:cs"));
|
||||
imp.diagram_xml_bytes = spent.get();
|
||||
Some(deckcraft_model::Diagram {
|
||||
kind: crate::dgm::kind_for(&id, &cat).to_string(),
|
||||
nodes,
|
||||
style,
|
||||
colors,
|
||||
imported: true,
|
||||
// Without the layout part the writer generates one for `kind`; empty keeps data's loTypeId in step with it.
|
||||
layout_id: if layout_xml.is_some() { id } else { String::new() },
|
||||
layout_xml,
|
||||
style_xml,
|
||||
colors_xml,
|
||||
})
|
||||
}
|
||||
|
||||
fn table(imp: &mut Imp, part: &Part, tbl: &El) -> Table {
|
||||
// A table naming no style is drawn by PowerPoint with thin dark grid lines ("No Style, Table
|
||||
// Grid"), not without lines.
|
||||
let mut t = Table { style: "grid".into(), first_row: false, band_row: false, ..Default::default() };
|
||||
if let Some(pr) = tbl.child("tblPr") {
|
||||
t.background = pr.elements().find(|e| e.local().ends_with("Fill") && e.local() != "noFill").and_then(|f| dml::fill_el(imp, part, f));
|
||||
t.first_row = pr.bool("firstRow").unwrap_or(false);
|
||||
t.first_col = pr.bool("firstCol").unwrap_or(false);
|
||||
t.last_row = pr.bool("lastRow").unwrap_or(false);
|
||||
t.last_col = pr.bool("lastCol").unwrap_or(false);
|
||||
t.band_row = pr.bool("bandRow").unwrap_or(false);
|
||||
t.band_col = pr.bool("bandCol").unwrap_or(false);
|
||||
t.rtl = pr.bool("rtl");
|
||||
if let Some(id) = pr.child("tableStyleId").map(|e| e.text()) {
|
||||
// A style the file defines is drawn from its definition (by its GUID).
|
||||
// DeckCraft's own styles (written with GUIDs derived from their ids) map back to them.
|
||||
let up = id.trim().to_ascii_uppercase();
|
||||
t.style =
|
||||
if imp.table_style_ids.contains(&up) && !crate::tables::is_own_guid(&up) { up } else { crate::tables::style_from_guid(id.trim()) };
|
||||
}
|
||||
}
|
||||
t.cols = tbl
|
||||
.child("tblGrid")
|
||||
.map(|g| g.children_named("gridCol").take(1000).map(|c| dml::pt(c, "w").unwrap_or(72.0).clamp(0.0, 20_000.0)).collect())
|
||||
.unwrap_or_default();
|
||||
for tr in tbl.children_named("tr").take(1000) {
|
||||
let mut row = Row { height: dml::pt(tr, "h").unwrap_or(0.0).clamp(0.0, 20_000.0), cells: vec![] };
|
||||
for tc in tr.children_named("tc").take(1000) {
|
||||
row.cells.push(cell(imp, part, tc));
|
||||
}
|
||||
t.rows.push(row);
|
||||
}
|
||||
if t.cols.is_empty() {
|
||||
let n = t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0);
|
||||
t.cols = vec![72.0; n];
|
||||
}
|
||||
if t.over_cap() {
|
||||
imp.warn(format!("a table in {} is over {} cells; its last rows were left out", part.name, deckcraft_model::table::MAX_CELLS));
|
||||
}
|
||||
t.normalize();
|
||||
t
|
||||
}
|
||||
|
||||
fn cell(imp: &mut Imp, part: &Part, tc: &El) -> Cell {
|
||||
let mut c = Cell {
|
||||
grid_span: tc.u32("gridSpan").unwrap_or(1).clamp(1, 1000),
|
||||
row_span: tc.u32("rowSpan").unwrap_or(1).clamp(1, 1000),
|
||||
h_merge: tc.bool("hMerge").unwrap_or(false),
|
||||
v_merge: tc.bool("vMerge").unwrap_or(false),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(tx) = tc.child("txBody") {
|
||||
c.text = dml::text_body(imp, part, tx);
|
||||
}
|
||||
if let Some(pr) = tc.child("tcPr") {
|
||||
if ["marL", "marR", "marT", "marB"].iter().any(|n| pr.has_attr(n)) {
|
||||
c.margins = Some([
|
||||
dml::pt(pr, "marL").unwrap_or(7.2),
|
||||
dml::pt(pr, "marR").unwrap_or(7.2),
|
||||
dml::pt(pr, "marT").unwrap_or(3.6),
|
||||
dml::pt(pr, "marB").unwrap_or(3.6),
|
||||
]);
|
||||
}
|
||||
c.anchor = pr.attr("anchor").and_then(Anchor::from_xml);
|
||||
c.anchor_ctr = pr.bool("anchorCtr");
|
||||
c.horz_overflow = pr.attr("horzOverflow").and_then(deckcraft_model::text::TextOverflow::from_horz_xml);
|
||||
c.vertical = pr.attr("vert").and_then(TextDir::from_xml);
|
||||
for (i, n) in ["lnL", "lnR", "lnT", "lnB"].iter().enumerate() {
|
||||
if let Some(ln) = pr.child(n)
|
||||
&& let Some(b) = c.borders.get_mut(i)
|
||||
{
|
||||
*b = Some(dml::line(imp, part, ln));
|
||||
}
|
||||
}
|
||||
c.diag_down = pr.child("lnTlToBr").map(|l| dml::line(imp, part, l));
|
||||
c.diag_up = pr.child("lnBlToTr").map(|l| dml::line(imp, part, l));
|
||||
c.fill = dml::fill_of(imp, part, pr);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod preset_geom_tests {
|
||||
use super::*;
|
||||
|
||||
fn geom(xml: &str) -> Geom {
|
||||
let doc = crate::xml::parse(xml.as_bytes()).unwrap();
|
||||
preset_geom(&doc.root)
|
||||
}
|
||||
|
||||
// A file may give some adjust values and rely on the defaults for the rest. A preset outside the
|
||||
// gallery had no defaults, so a missing value read as 0: a bentConnector4 with only adj2 lost
|
||||
// its middle leg.
|
||||
#[test]
|
||||
fn a_missing_adjust_value_takes_the_spec_default() {
|
||||
let a = r#"xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#;
|
||||
let g = geom(&format!(r#"<a:prstGeom {a} prst="bentConnector4"><a:avLst><a:gd name="adj2" fmla="val 25000"/></a:avLst></a:prstGeom>"#));
|
||||
assert!(matches!(&g, Geom::Preset { name, adj } if name == "bentConnector4" && adj == &[50000.0, 25000.0]), "{g:?}");
|
||||
let g = geom(&format!(r#"<a:prstGeom {a} prst="bentConnector5"><a:avLst><a:gd name="adj3" fmla="val 10000"/></a:avLst></a:prstGeom>"#));
|
||||
assert!(matches!(&g, Geom::Preset { adj, .. } if adj == &[50000.0, 50000.0, 10000.0]), "{g:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
//! Theme parts (`a:theme`).
|
||||
|
||||
use deckcraft_color::{ColorScheme, Rgba, SchemeSlot};
|
||||
use deckcraft_model::style::{ColorBase, Effects};
|
||||
use deckcraft_model::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, Theme, default_format};
|
||||
|
||||
use super::{Imp, Part, dml};
|
||||
use crate::xml::El;
|
||||
|
||||
fn font_set(e: Option<&El>) -> FontSet {
|
||||
let tf = |n: &str| e.and_then(|e| e.child(n)).and_then(|c| c.attr("typeface")).unwrap_or("").to_string();
|
||||
let scripts = e
|
||||
.map(|e| {
|
||||
e.children_named("font")
|
||||
.filter_map(|f| Some(ScriptFont { script: f.attr("script")?.to_string(), typeface: f.attr("typeface").unwrap_or("").to_string() }))
|
||||
.take(256)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), scripts }
|
||||
}
|
||||
|
||||
/// Bytes of preserved theme XML (object defaults and extra colour schemes) all masters of one
|
||||
/// presentation may keep.
|
||||
const MAX_THEME_EXTRA_BYTES: usize = 16 << 20;
|
||||
|
||||
pub fn read_theme(imp: &mut Imp, part: &Part, root: &El) -> Theme {
|
||||
let mut t = Theme { name: root.attr("name").unwrap_or("Theme").to_string(), ..Default::default() };
|
||||
let Some(te) = root.child("themeElements") else { return t };
|
||||
if let Some(cs) = te.child("clrScheme") {
|
||||
let mut scheme = ColorScheme::new(cs.attr("name").unwrap_or("").to_string(), t.colors.colors);
|
||||
for slot in SchemeSlot::THEME {
|
||||
if let Some(c) = cs.child(slot.xml_name()).and_then(dml::color) {
|
||||
let rgb = match c.base {
|
||||
ColorBase::Rgb { rgb } => rgb,
|
||||
ColorBase::System { last, .. } => last,
|
||||
ColorBase::Preset { name } => deckcraft_color::preset(&name).unwrap_or(Rgba::BLACK),
|
||||
ColorBase::Scheme { .. } => continue,
|
||||
};
|
||||
scheme.set(slot, rgb);
|
||||
}
|
||||
}
|
||||
t.colors = scheme;
|
||||
}
|
||||
if let Some(fs) = te.child("fontScheme") {
|
||||
t.fonts = FontScheme {
|
||||
name: fs.attr("name").unwrap_or("").to_string(),
|
||||
major: font_set(fs.child("majorFont")),
|
||||
minor: font_set(fs.child("minorFont")),
|
||||
};
|
||||
}
|
||||
if let Some(fm) = te.child("fmtScheme") {
|
||||
let dflt = default_format();
|
||||
let mut f = FormatScheme { name: fm.attr("name").unwrap_or("").to_string(), ..Default::default() };
|
||||
if let Some(l) = fm.child("fillStyleLst") {
|
||||
f.fills = l.elements().take(16).filter_map(|e| dml::fill_el(imp, part, e)).collect();
|
||||
}
|
||||
if let Some(l) = fm.child("lnStyleLst") {
|
||||
f.lines = l.children_named("ln").take(16).map(|e| dml::line(imp, part, e)).collect();
|
||||
}
|
||||
if let Some(l) = fm.child("effectStyleLst") {
|
||||
f.effects = l
|
||||
.children_named("effectStyle")
|
||||
.take(16)
|
||||
.map(|e| {
|
||||
let mut fx = e.child("effectLst").map(dml::effects).unwrap_or_default();
|
||||
if let Some(b) = e.path(&["sp3d", "bevelT"]) {
|
||||
fx.bevel = Some(b.attr("prst").unwrap_or("circle").to_string());
|
||||
}
|
||||
let raw: String = e.elements().filter(|c| c.is("scene3d") || c.is("sp3d")).map(|c| part.keep(c)).collect();
|
||||
if !raw.is_empty() {
|
||||
fx.raw3d = Some(raw);
|
||||
}
|
||||
fx
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
if let Some(l) = fm.child("bgFillStyleLst") {
|
||||
f.bg_fills = l.elements().take(16).filter_map(|e| dml::fill_el(imp, part, e)).collect();
|
||||
}
|
||||
// The style matrix needs three entries of each kind.
|
||||
pad(&mut f.fills, &dflt.fills);
|
||||
pad(&mut f.lines, &dflt.lines);
|
||||
pad(&mut f.bg_fills, &dflt.bg_fills);
|
||||
while f.effects.len() < 3 {
|
||||
f.effects.push(Effects::default());
|
||||
}
|
||||
t.format = f;
|
||||
}
|
||||
let extra: String = root
|
||||
.elements()
|
||||
.filter(|e| e.is("objectDefaults") || e.is("extraClrSchemeLst"))
|
||||
.filter(|e| !super::has_rel_refs(e))
|
||||
.map(|e| part.keep(e))
|
||||
.collect();
|
||||
// Every master that references this theme keeps its own copy of the preserved XML, so the
|
||||
// copies share one budget for the presentation.
|
||||
if !extra.is_empty() && imp.theme_extra_bytes.saturating_add(extra.len()) <= MAX_THEME_EXTRA_BYTES {
|
||||
imp.theme_extra_bytes += extra.len();
|
||||
t.raw_extra = Some(extra);
|
||||
} else if !extra.is_empty() {
|
||||
log::warn!("pptx: theme object defaults not kept; the preserved-XML budget is spent");
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
fn pad<T: Clone>(v: &mut Vec<T>, d: &[T]) {
|
||||
while v.len() < 3 {
|
||||
match d.get(v.len()) {
|
||||
Some(x) => v.push(x.clone()),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,493 +0,0 @@
|
||||
//! Slide transitions (`p:transition`) and animations (`p:timing`).
|
||||
|
||||
use deckcraft_model::anim::{AnimClass, AnimStart, Animation, BuildRole, TextBuild, Transition, build_filled, paragraph_build_roles};
|
||||
use deckcraft_model::{Shape, ShapeKind, TextBody, find_shape, find_shape_mut};
|
||||
|
||||
use super::shapes::IdCtx;
|
||||
use super::{Imp, Part, dml};
|
||||
use crate::maps;
|
||||
use crate::xml::El;
|
||||
|
||||
fn ms_attr(e: &El, name: &str) -> Option<u32> {
|
||||
let v = e.attr(name)?.trim();
|
||||
if v == "indefinite" {
|
||||
return None;
|
||||
}
|
||||
v.parse::<f64>().ok().filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 86_400_000.0) as u32)
|
||||
}
|
||||
|
||||
pub fn transition(imp: &mut Imp, part: &Part, t: &El) -> Option<Transition> {
|
||||
let effect = t.elements().find(|e| !matches!(e.local(), "sndAc" | "extLst"));
|
||||
let mut tr = Transition { advance_on_click: t.bool("advClick").unwrap_or(true), advance_after_ms: ms_attr(t, "advTm"), ..Default::default() };
|
||||
match effect.and_then(maps::transition_from_xml) {
|
||||
Some((k, o)) => {
|
||||
tr.kind = k;
|
||||
tr.option = o;
|
||||
}
|
||||
None => match effect {
|
||||
Some(e) => {
|
||||
tr.kind = e.local().to_string();
|
||||
tr.raw = Some(part.keep(t));
|
||||
}
|
||||
None => tr.kind = "none".into(),
|
||||
},
|
||||
}
|
||||
let default_dur = deckcraft_model::anim::TRANSITIONS.iter().find(|x| x.0 == tr.kind).map(|x| x.3).unwrap_or(1000);
|
||||
// `spd` defaults to "fast" in the schema; PowerPoint omits both attributes for 0.5 s.
|
||||
tr.duration_ms = ms_attr(t, "dur").unwrap_or(match t.attr("spd") {
|
||||
Some("med") => 750,
|
||||
Some("slow") => default_dur.max(1000),
|
||||
_ => 500,
|
||||
});
|
||||
if let Some(snd) = t.path(&["sndAc", "stSnd", "snd"]) {
|
||||
tr.sound = dml::media_ref(imp, part, snd);
|
||||
tr.sound_loop = t.path(&["sndAc", "stSnd"]).and_then(|s| s.attr("loop")).is_some_and(|v| v == "1" || v == "true");
|
||||
}
|
||||
tr.stop_sound = t.path(&["sndAc", "endSnd"]).is_some();
|
||||
if tr.kind == "none" && tr.advance_on_click && tr.advance_after_ms.is_none() && tr.sound.is_none() && !tr.stop_sound {
|
||||
return None;
|
||||
}
|
||||
Some(tr)
|
||||
}
|
||||
|
||||
struct Found<'a> {
|
||||
ctn: &'a El,
|
||||
trigger: Option<u32>,
|
||||
/// Click group the effect sits in: a new one starts at every time node whose start is `indefinite`.
|
||||
group: usize,
|
||||
/// Sum of the start delays of the time nodes between the click group and the effect, in ms.
|
||||
offset: u32,
|
||||
/// Whether any ancestor time node defers start until an event (`onClick`, `onEnd`, targeted `onBegin`) or nonzero delay.
|
||||
deferred: bool,
|
||||
}
|
||||
|
||||
/// Where `collect` is in the time tree: the click group and the delay accumulated inside it.
|
||||
#[derive(Clone, Copy)]
|
||||
struct At {
|
||||
trigger: Option<u32>,
|
||||
main_seq_id: Option<u32>,
|
||||
group: usize,
|
||||
offset: u32,
|
||||
deferred: bool,
|
||||
}
|
||||
|
||||
/// Returns whether `st` (`p:stCondLst`) is PowerPoint's automatic main-sequence step wrapper:
|
||||
/// `<p:cond delay="indefinite"/>` paired only with `<p:cond evt="onBegin" delay="0"><p:tn val="{main_seq_id}"/></p:cond>`
|
||||
/// referencing the immediate enclosing `mainSeq` `<p:cTn>`.
|
||||
fn is_main_seq_auto(st: &El, main_seq_id: Option<u32>) -> bool {
|
||||
let Some(ms_id) = main_seq_id else {
|
||||
return false;
|
||||
};
|
||||
let is_indefinite = |d: &El| {
|
||||
d.attr("evt").is_none()
|
||||
&& d.attr("delay").map(str::trim) == Some("indefinite")
|
||||
&& d.child("tgtEl").is_none()
|
||||
&& d.child("tn").is_none()
|
||||
&& d.child("rtn").is_none()
|
||||
};
|
||||
let is_main_seq_on_begin = |d: &El| {
|
||||
d.attr("evt") == Some("onBegin")
|
||||
&& d.attr("delay").map(str::trim) == Some("0")
|
||||
&& d.child("tgtEl").is_none()
|
||||
&& d.child("rtn").is_none()
|
||||
&& d.child("tn").and_then(|tn| tn.u32("val")) == Some(ms_id)
|
||||
};
|
||||
st.children_named("cond").any(is_indefinite)
|
||||
&& st.children_named("cond").any(is_main_seq_on_begin)
|
||||
&& st.children_named("cond").all(|d| is_indefinite(d) || is_main_seq_on_begin(d))
|
||||
}
|
||||
|
||||
fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec<Found<'a>>, depth: usize) {
|
||||
if depth > 64 || out.len() > 10_000 {
|
||||
return;
|
||||
}
|
||||
for c in e.elements() {
|
||||
if c.is("cTn") && c.has_attr("presetClass") {
|
||||
let deferred = at.deferred || c.child("stCondLst").is_some_and(defers_start);
|
||||
out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset, deferred });
|
||||
continue;
|
||||
}
|
||||
let mut at = at;
|
||||
if c.is("seq")
|
||||
&& let Some(ctn) = c.child("cTn")
|
||||
&& ctn.attr("nodeType") == Some("interactiveSeq")
|
||||
{
|
||||
at.trigger = ctn.path(&["stCondLst", "cond", "tgtEl", "spTgt"]).and_then(|s| s.u32("spid"));
|
||||
at.main_seq_id = None;
|
||||
}
|
||||
if c.is("cTn") {
|
||||
let is_main_seq = c.attr("nodeType") == Some("mainSeq");
|
||||
if let Some(st) = c.child("stCondLst") {
|
||||
if !(!is_main_seq && !at.deferred && is_main_seq_auto(st, at.main_seq_id)) && defers_start(st) {
|
||||
at.deferred = true;
|
||||
}
|
||||
if let Some(cond) = st.child("cond") {
|
||||
if cond.attr("delay").map(str::trim) == Some("indefinite") {
|
||||
*groups += 1;
|
||||
at.group = *groups;
|
||||
at.offset = 0;
|
||||
} else {
|
||||
at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
at.main_seq_id = if is_main_seq && !at.deferred { c.u32("id") } else { None };
|
||||
}
|
||||
collect(c, at, groups, out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long an effect holds back an After Previous one, as the show timeline counts it.
|
||||
fn span_ms(a: &Animation) -> u32 {
|
||||
let iterations = if a.repeat == u32::MAX || a.repeat <= 1 { 1 } else { a.repeat.min(1_000) };
|
||||
a.duration_ms.saturating_mul(if a.auto_reverse { 2 } else { 1 }).saturating_mul(iterations)
|
||||
}
|
||||
|
||||
/// Start times (ms after the click) that the flat effect list plays at, effect after effect.
|
||||
fn flat_starts(anims: &[&Animation]) -> Vec<u32> {
|
||||
let (mut begin, mut end) = (0u32, 0u32);
|
||||
anims
|
||||
.iter()
|
||||
.map(|a| {
|
||||
if a.start == AnimStart::AfterPrevious {
|
||||
begin = end;
|
||||
}
|
||||
let start = begin.saturating_add(a.delay_ms);
|
||||
end = end.max(start.saturating_add(span_ms(a)));
|
||||
start
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// PowerPoint places each effect at the delays of all its enclosing time nodes, so a file may list
|
||||
/// effects out of time order (a countdown written first, then effects at 5 s placed only by their
|
||||
/// parent's delay). The flat list only knows "after/with previous" plus the effect's own delay, so
|
||||
/// a click group listed out of time order, whose flat reading disagrees with the file, is sorted by
|
||||
/// start time and its starts and delays rewritten to land every effect where PowerPoint plays it.
|
||||
/// Every other group is left untouched.
|
||||
fn place_by_parent_delays(out: &mut [(Animation, u32, String, bool, usize, u32)], at: &[(Option<u32>, usize, u32)]) {
|
||||
let mut groups: Vec<Vec<usize>> = vec![];
|
||||
let mut slot: std::collections::HashMap<(Option<u32>, usize), usize> = std::collections::HashMap::new();
|
||||
for (i, &(t, g, _)) in at.iter().enumerate() {
|
||||
let n = *slot.entry((t, g)).or_insert_with(|| {
|
||||
groups.push(vec![]);
|
||||
groups.len() - 1
|
||||
});
|
||||
groups[n].push(i);
|
||||
}
|
||||
for idx in groups {
|
||||
// More than one click in a group means the tree isn't one click per group: leave it.
|
||||
if idx.iter().skip(1).any(|&i| out[i].0.start == AnimStart::OnClick) {
|
||||
continue;
|
||||
}
|
||||
let abs: Vec<u32> = idx.iter().map(|&i| at[i].2.saturating_add(out[i].0.delay_ms)).collect();
|
||||
// Only a file that lists effects out of time order needs this: files PowerPoint or DeckCraft
|
||||
// save are in order, and their reading stays exactly as before.
|
||||
if abs.is_sorted() {
|
||||
continue;
|
||||
}
|
||||
let flat = flat_starts(&idx.iter().map(|&i| &out[i].0).collect::<Vec<_>>());
|
||||
if flat == abs {
|
||||
continue;
|
||||
}
|
||||
// The group's click stays on whichever effect now plays first.
|
||||
let had_click = out[idx[0]].0.start == AnimStart::OnClick;
|
||||
let mut order: Vec<usize> = (0..idx.len()).collect();
|
||||
order.sort_by_key(|&k| abs[k]);
|
||||
let mut sorted: Vec<(Animation, u32, String, bool, usize, u32)> = order.iter().map(|&k| out[idx[k]].clone()).collect();
|
||||
let (mut begin, mut end) = (0u32, 0u32);
|
||||
for (n, (&k, item)) in order.iter().zip(sorted.iter_mut()).enumerate() {
|
||||
let a = &mut item.0;
|
||||
let t = abs[k];
|
||||
if n == 0 && had_click {
|
||||
a.start = AnimStart::OnClick;
|
||||
a.delay_ms = t;
|
||||
} else if a.start == AnimStart::AfterPrevious && t >= end {
|
||||
begin = end;
|
||||
a.delay_ms = t - end;
|
||||
} else {
|
||||
a.start = AnimStart::WithPrevious;
|
||||
a.delay_ms = t.saturating_sub(begin);
|
||||
}
|
||||
item.5 = 0;
|
||||
end = end.max(t.saturating_add(span_ms(a)));
|
||||
}
|
||||
for (&i, item) in idx.iter().zip(sorted) {
|
||||
out[i] = item;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn max_dur(e: &El, depth: usize) -> Option<u32> {
|
||||
if depth > 64 {
|
||||
return None;
|
||||
}
|
||||
let mut best: Option<u32> = None;
|
||||
for c in e.elements() {
|
||||
if c.is("cTn")
|
||||
&& let Some(d) = ms_attr(c, "dur")
|
||||
&& d > 1
|
||||
{
|
||||
best = Some(best.map_or(d, |b: u32| b.max(d)));
|
||||
}
|
||||
if let Some(d) = max_dur(c, depth + 1) {
|
||||
best = Some(best.map_or(d, |b| b.max(d)));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Does every behaviour time node (`p:cBhvr/p:cTn`) under the effect node `c` carry `autoRev`?
|
||||
fn behaviour_auto_reverses(c: &El) -> bool {
|
||||
let mut behaviours = vec![];
|
||||
c.find_all("cBhvr", &mut behaviours);
|
||||
!behaviours.is_empty() && behaviours.iter().all(|b| b.child("cTn").and_then(|t| t.bool("autoRev")).unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Volume, mute, Loop until Stopped, Hide While Not Playing and Play Full Screen live in the timing tree
|
||||
/// (`p:video`/`p:audio` > `p:cMediaNode`), not on the picture: copy them onto the target's `MediaClip`.
|
||||
/// Returns whether `st` (`p:stCondLst`) defers playback instead of starting immediately on slide entry.
|
||||
fn defers_start(st: &El) -> bool {
|
||||
let is_auto_begin = |c: &El| {
|
||||
c.attr("evt") == Some("onBegin")
|
||||
&& c.attr("delay").map(str::trim) == Some("0")
|
||||
&& c.child("tgtEl").is_none()
|
||||
&& c.child("tn").is_none()
|
||||
&& c.child("rtn").is_none()
|
||||
};
|
||||
let has_on_begin = st.children_named("cond").any(is_auto_begin);
|
||||
st.children_named("cond")
|
||||
.any(|c| (c.attr("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr("delay").map(str::trim) != Some("0")))
|
||||
}
|
||||
|
||||
/// Applies `p:video`/`p:audio` timing node settings and main-sequence autoplay triggers to media shapes.
|
||||
pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) {
|
||||
fn collect_media<'a>(e: &'a El, deferred: bool, out: &mut Vec<(&'a El, bool)>, depth: usize) {
|
||||
if depth > 64 || out.len() >= 10_000 {
|
||||
return;
|
||||
}
|
||||
let mut deferred = deferred;
|
||||
if e.is("cTn")
|
||||
&& let Some(st) = e.child("stCondLst")
|
||||
&& defers_start(st)
|
||||
{
|
||||
deferred = true;
|
||||
}
|
||||
if e.is("video") || e.is("audio") {
|
||||
out.push((e, deferred));
|
||||
return;
|
||||
}
|
||||
for c in e.elements() {
|
||||
collect_media(c, deferred, out, depth + 1);
|
||||
}
|
||||
}
|
||||
let mut nodes = vec![];
|
||||
collect_media(timing, false, &mut nodes, 0);
|
||||
for (node, deferred) in nodes {
|
||||
let Some(cm) = node.child("cMediaNode") else { continue };
|
||||
let Some(id) = cm.path(&["tgtEl", "spTgt"]).and_then(|t| t.u32("spid")).and_then(|f| ctx.lookup(f)) else { continue };
|
||||
let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) else { continue };
|
||||
if let Some(v) = cm.attr("vol").and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite()) {
|
||||
clip.volume = (v / 100_000.0).clamp(0.0, 1.0);
|
||||
}
|
||||
if cm.bool("mute") == Some(true) {
|
||||
clip.volume = 0.0;
|
||||
}
|
||||
if cm.bool("showWhenStopped") == Some(false) {
|
||||
clip.hide_while_not_playing = true;
|
||||
}
|
||||
if cm.child("cTn").and_then(|c| c.attr("repeatCount")) == Some("indefinite") {
|
||||
clip.loop_play = true;
|
||||
}
|
||||
if cm.child("cTn").and_then(|c| c.attr("fill")) == Some("remove") {
|
||||
clip.rewind = true;
|
||||
}
|
||||
if cm.u32("numSld").is_some_and(|n| n > 1) {
|
||||
clip.play_across_slides = true;
|
||||
}
|
||||
if !deferred && cm.path(&["cTn", "stCondLst", "cond"]).is_some_and(|c| c.attr("evt").is_none() && c.attr("delay").map(str::trim) == Some("0"))
|
||||
{
|
||||
clip.autoplay = true;
|
||||
}
|
||||
if node.bool("fullScrn") == Some(true) {
|
||||
clip.full_screen = true;
|
||||
}
|
||||
}
|
||||
let root_deferred = timing.path(&["tnLst", "par", "cTn", "stCondLst"]).is_some_and(defers_start);
|
||||
if !root_deferred && let Some(tn) = timing.child("tnLst") {
|
||||
let mut found = vec![];
|
||||
collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0);
|
||||
for f in found.into_iter().filter(|f| f.trigger.is_none()) {
|
||||
let c = f.ctn;
|
||||
if c.attr("nodeType") == Some("clickEffect") || f.deferred {
|
||||
break;
|
||||
}
|
||||
let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr"));
|
||||
let preset = c.u32("presetID").unwrap_or(0);
|
||||
let effect = maps::effect_for_preset(class, preset).unwrap_or_else(|| maps::fallback_effect(class));
|
||||
let delay = c.path(&["stCondLst", "cond"]).and_then(|d| ms_attr(d, "delay")).unwrap_or(0);
|
||||
if class == AnimClass::Media
|
||||
&& effect == "play"
|
||||
&& f.offset == 0
|
||||
&& delay == 0
|
||||
&& let Some(id) = c.find("spTgt").and_then(|t| t.u32("spid")).and_then(|s| ctx.lookup(s))
|
||||
&& let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind)
|
||||
{
|
||||
clip.autoplay = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Flatten the timing tree into the Animation Pane list.
|
||||
pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes: &[Shape]) -> Vec<Animation> {
|
||||
let _ = (imp, part);
|
||||
let Some(tn) = timing.child("tnLst") else { return vec![] };
|
||||
let mut found = vec![];
|
||||
collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0);
|
||||
// Paragraph builds (`bldP`) by (spid, grpId) -> whether `build="p"`.
|
||||
let bld_p: std::collections::HashMap<(u32, String), bool> = timing
|
||||
.child("bldLst")
|
||||
.map(|b| {
|
||||
b.children_named("bldP")
|
||||
.filter_map(|p| Some(((p.u32("spid")?, p.attr("grpId").unwrap_or("0").to_string()), p.attr("build") == Some("p"))))
|
||||
.fold(std::collections::HashMap::new(), |mut m, (k, v)| {
|
||||
m.entry(k).and_modify(|e| *e |= v).or_insert(v);
|
||||
m
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut out: Vec<(Animation, u32, String, bool, usize, u32)> = vec![];
|
||||
let mut at: Vec<(Option<u32>, usize, u32)> = vec![];
|
||||
for f in found {
|
||||
let c = f.ctn;
|
||||
let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr"));
|
||||
let preset = c.u32("presetID").unwrap_or(0);
|
||||
let sub = c.u32("presetSubtype").unwrap_or(0);
|
||||
let Some(tgt) = c.find("spTgt") else { continue };
|
||||
let Some(file_id) = tgt.u32("spid") else { continue };
|
||||
let Some(shape) = ctx.lookup(file_id) else { continue };
|
||||
let paragraph = tgt.path(&["txEl", "pRg"]).and_then(|p| p.u32("st"));
|
||||
let effect = maps::effect_for_preset(class, preset).unwrap_or_else(|| maps::fallback_effect(class));
|
||||
// PowerPoint writes Float Down as its own preset (47), not as Float with a direction.
|
||||
let (effect, option) = match (class, preset) {
|
||||
(AnimClass::Entrance, 47) => ("float", "d".to_string()),
|
||||
(AnimClass::Exit, 47) => ("floatOut", "d".to_string()),
|
||||
_ => (effect, maps::option_from_subtype(effect, sub)),
|
||||
};
|
||||
let start = match c.attr("nodeType") {
|
||||
Some("clickEffect") => AnimStart::OnClick,
|
||||
Some("afterEffect") => AnimStart::AfterPrevious,
|
||||
_ => AnimStart::WithPrevious,
|
||||
};
|
||||
let mut a = Animation {
|
||||
shape,
|
||||
class,
|
||||
effect: effect.to_string(),
|
||||
option,
|
||||
start,
|
||||
duration_ms: max_dur(c, 0).unwrap_or(0),
|
||||
delay_ms: c.path(&["stCondLst", "cond"]).and_then(|d| ms_attr(d, "delay")).unwrap_or(0),
|
||||
paragraph,
|
||||
trigger: f.trigger.and_then(|t| ctx.lookup(t)),
|
||||
preset_id: Some(preset),
|
||||
preset_subtype: Some(sub),
|
||||
// PowerPoint's "Auto-reverse" is `autoRev` on the behaviour nodes (`p:cBhvr/p:cTn`); Color Pulse
|
||||
// always writes it there and plays back and forth on its own, so it isn't read as the option.
|
||||
auto_reverse: c.bool("autoRev").unwrap_or(false) || (effect != "colorPulse" && behaviour_auto_reverses(c)),
|
||||
// PowerPoint's "Rewind when done playing" is `fill="remove"` on the effect node.
|
||||
rewind: c.attr("fill") == Some("remove"),
|
||||
smooth_start: c.f64("accel").map(|v| v / 100_000.0).unwrap_or(0.0),
|
||||
smooth_end: c.f64("decel").map(|v| v / 100_000.0).unwrap_or(0.0),
|
||||
bounce_end: c.f64("bounceEnd").map(|v| (v / 100_000.0).clamp(0.0, 1.0)).unwrap_or(0.0),
|
||||
..Default::default()
|
||||
};
|
||||
a.repeat = match c.attr("repeatCount") {
|
||||
Some("indefinite") => u32::MAX,
|
||||
Some(v) => v.parse::<f64>().ok().filter(|v| v.is_finite()).map(|v| (v / 1000.0).round().clamp(1.0, 10_000.0) as u32).unwrap_or(1),
|
||||
None => 1,
|
||||
};
|
||||
if let Some(m) = c.find("animMotion") {
|
||||
a.path = m.attr("path").map(String::from);
|
||||
}
|
||||
if let Some(r) = c.find("animRot") {
|
||||
a.amount = r.f64("by").map(|v| v / 60_000.0);
|
||||
if a.effect == "spin" && a.amount.is_some_and(|v| v < 0.0) {
|
||||
a.option = "counterClockwise".into();
|
||||
}
|
||||
} else if let Some(s) = c.find("animScale").and_then(|s| s.child("by")) {
|
||||
a.amount = s.f64("x").map(|v| v / 100_000.0);
|
||||
}
|
||||
if let Some(clr) = c.find("animClr").and_then(|x| x.child("to")) {
|
||||
a.color = dml::color(clr);
|
||||
}
|
||||
let grp = c.attr("grpId").unwrap_or("0").to_string();
|
||||
let build = paragraph.is_some() && bld_p.get(&(file_id, grp.clone())) != Some(&false);
|
||||
out.push((a, file_id, grp, build, f.group, f.offset));
|
||||
at.push((f.trigger, f.group, f.offset));
|
||||
}
|
||||
place_by_parent_delays(&mut out, &at);
|
||||
// A paragraph build's effects, one per paragraph, become one by-paragraph animation only when
|
||||
// the timeline plays that back exactly: PowerPoint lets each paragraph keep its own start and
|
||||
// effect, and other shapes' effects can sit between them (#844).
|
||||
let same_build = |x: &(Animation, u32, String, bool, usize, u32), y: &(Animation, u32, String, bool, usize, u32)| {
|
||||
x.3 && y.3 && x.1 == y.1 && x.2 == y.2 && x.0.trigger == y.0.trigger
|
||||
};
|
||||
let mut anims = Vec::with_capacity(out.len());
|
||||
for run in out.chunk_by(same_build) {
|
||||
let effects: Vec<&Animation> = run.iter().map(|(a, ..)| a).collect();
|
||||
let offsets: Vec<u32> = run.iter().map(|r| r.5).collect();
|
||||
let build = run.first().is_some_and(|r| r.3);
|
||||
let explicit_bld = run.first().is_some_and(|r| bld_p.get(&(r.1, r.2.clone())) == Some(&true));
|
||||
let same_click_group = run.first().is_some_and(|first| first.0.start == AnimStart::OnClick || run.iter().all(|r| r.4 == first.4));
|
||||
let text = effects.first().and_then(|a| find_shape(shapes, a.shape)).and_then(|s| s.text.as_ref());
|
||||
match (effects.first(), text) {
|
||||
(Some(first), Some(text)) if build && (explicit_bld || same_click_group) && plays_as_build(&effects, &offsets, text, explicit_bld) => {
|
||||
anims.push(Animation { text_build: TextBuild::ByParagraph, paragraph: None, ..(*first).clone() });
|
||||
}
|
||||
_ => anims.extend(effects.into_iter().cloned()),
|
||||
}
|
||||
}
|
||||
anims
|
||||
}
|
||||
|
||||
/// Are `effects` (paragraph effects of one shape, in file order) what a by-paragraph build of the
|
||||
/// first one plays: one effect per paragraph the build animates, in paragraph order, later top
|
||||
/// paragraphs on click (after previous when the build doesn't start on click), deeper ones with
|
||||
/// their parent, all with the same settings?
|
||||
fn plays_as_build(effects: &[&Animation], offsets: &[u32], text: &TextBody, explicit_bld: bool) -> bool {
|
||||
let roles = paragraph_build_roles(text);
|
||||
let expected = roles.iter().enumerate().filter(|(i, r)| match r {
|
||||
BuildRole::Top => true,
|
||||
BuildRole::Member(_) => text.paragraphs.get(*i).is_some_and(build_filled),
|
||||
BuildRole::Unowned => false,
|
||||
});
|
||||
let Some(first) = effects.first() else { return false };
|
||||
let off0 = offsets.first().copied().unwrap_or(0);
|
||||
let flat = flat_starts(effects);
|
||||
let parent_starts_match = offsets
|
||||
.iter()
|
||||
.zip(effects.iter())
|
||||
.zip(flat.iter())
|
||||
.all(|((&off, a), &ft)| off == off0 || off.saturating_add(a.delay_ms) == off0.saturating_add(ft));
|
||||
if !explicit_bld && (!parent_starts_match || (first.start != AnimStart::OnClick && (span_ms(first) != 500 || first.delay_ms != 0 || off0 != 0))) {
|
||||
return false;
|
||||
}
|
||||
let settings = |a: &Animation| Animation { start: AnimStart::OnClick, paragraph: None, ..a.clone() };
|
||||
let base = settings(first);
|
||||
let mut matched = 0;
|
||||
for (k, (i, role)) in expected.enumerate() {
|
||||
let Some(a) = effects.get(k) else { return false };
|
||||
let start_ok = match role {
|
||||
BuildRole::Top if k == 0 => true,
|
||||
BuildRole::Top if first.start == AnimStart::OnClick => a.start == AnimStart::OnClick,
|
||||
BuildRole::Top => a.start == AnimStart::AfterPrevious,
|
||||
_ => a.start == AnimStart::WithPrevious,
|
||||
};
|
||||
if a.paragraph != u32::try_from(i).ok() || !start_ok || settings(a) != base {
|
||||
return false;
|
||||
}
|
||||
matched = k + 1;
|
||||
}
|
||||
matched == effects.len()
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
//! Table style XML uses the shared writer; app XML admission remains unchanged.
|
||||
pub use craft_drawingml::table::styles::{guid, guid_for_style, is_own_guid, style_from_guid};
|
||||
|
||||
pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec<u8> {
|
||||
craft_drawingml_table::table::styles::table_styles_xml_with(used, defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())), "DeckCraft", |raw| {
|
||||
crate::xml::parse(raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle"))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tables_legacy.rs"]
|
||||
mod legacy;
|
||||
|
||||
#[cfg(test)]
|
||||
fn own_guid(style: &str) -> String {
|
||||
guid(&format!("deckcraft-table-style:{style}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_writer_matches_legacy_bytes_and_admission() {
|
||||
use deckcraft_model::table::TableStyleDef;
|
||||
let mut used: Vec<String> = deckcraft_model::table::table_styles().into_iter().map(|(id, _)| id).collect();
|
||||
used.extend(["unknown<&\"".into(), "Custom".into(), "Custom".into(), "CUSTOM".into()]);
|
||||
for raw in [
|
||||
"<a:tblStyle xmlns:a=\"urn:test\"/>",
|
||||
"<tblStyle>", // Existing lenient partial-root policy.
|
||||
"<tblStyle></other><trailing/>",
|
||||
"<!--prefix--><tblStyle name=\"&\"/>",
|
||||
"<notAStyle/>",
|
||||
"",
|
||||
"<tblStyle><child/></tblStyle>",
|
||||
] {
|
||||
let defs = vec![
|
||||
TableStyleDef { id: "custom".into(), raw: raw.into(), ..Default::default() },
|
||||
TableStyleDef { id: "CUSTOM".into(), raw: "<tblStyle second=\"1\"/>".into(), ..Default::default() },
|
||||
TableStyleDef { id: "unused".into(), raw: "<tblStyle unused=\"1\"/>".into(), ..Default::default() },
|
||||
];
|
||||
for selection in [&used[..], &[][..]] {
|
||||
assert_eq!(table_styles_xml(selection, &defs), legacy::table_styles_xml(selection, &defs), "{raw:?}");
|
||||
}
|
||||
}
|
||||
for depth in [255, 256, 257] {
|
||||
let raw = format!("{}{}", "<tblStyle>".repeat(depth), "</tblStyle>".repeat(depth));
|
||||
let defs = [TableStyleDef { id: "custom".into(), raw, ..Default::default() }];
|
||||
assert_eq!(table_styles_xml(&used, &defs), legacy::table_styles_xml(&used, &defs));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_style_catalog_matches_deckcraft() {
|
||||
assert_eq!(deckcraft_model::table::table_styles(), craft_drawingml::table::table_styles());
|
||||
assert_eq!(style_from_guid(""), "none");
|
||||
let custom = "{abcdef00-0000-0000-0000-000000000000}";
|
||||
assert_eq!(style_from_guid(custom), custom);
|
||||
assert_eq!(guid_for_style(custom), (custom.to_string(), false));
|
||||
assert_eq!(guid_for_style("unknown"), guid_for_style("medium2-accent1"));
|
||||
for (id, _) in deckcraft_model::table::table_styles() {
|
||||
let generated = own_guid(&id);
|
||||
assert!(is_own_guid(&generated.to_ascii_lowercase()));
|
||||
if guid_for_style(&id).1 {
|
||||
assert_eq!(guid_for_style(&id).0, generated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_parts_follow_schema_order() {
|
||||
const ORDER: [&str; 14] = [
|
||||
"tblBg", "wholeTbl", "band1H", "band2H", "band1V", "band2V", "lastCol", "firstCol", "lastRow", "seCell", "swCell", "firstRow", "neCell",
|
||||
"nwCell",
|
||||
];
|
||||
let used: Vec<String> = deckcraft_model::table::table_styles().into_iter().map(|(id, _)| id).collect();
|
||||
let d = crate::xml::parse(&table_styles_xml(&used, &[])).unwrap();
|
||||
let mut n = 0;
|
||||
for st in d.root.children_named("tblStyle") {
|
||||
n += 1;
|
||||
let pos: Vec<usize> = st.elements().map(|e| ORDER.iter().position(|o| *o == e.local()).unwrap()).collect();
|
||||
assert!(pos.windows(2).all(|w| w[0] < w[1]), "{:?}: {pos:?}", st.attr("styleName"));
|
||||
}
|
||||
assert!(n > 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guids_round_trip() {
|
||||
for (id, _) in deckcraft_model::table::table_styles() {
|
||||
let (g, _) = guid_for_style(&id);
|
||||
assert_eq!(style_from_guid(&g), id, "{id} via {g}");
|
||||
assert_eq!(g.len(), 38);
|
||||
}
|
||||
assert_eq!(style_from_guid("{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"), "medium2-accent1");
|
||||
assert_eq!(style_from_guid("{ABCDEF00-0000-0000-0000-000000000000}"), "{ABCDEF00-0000-0000-0000-000000000000}");
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
//! Table styles: our style ids ↔ table style GUIDs, and `tableStyles.xml` definitions for the
|
||||
//! styles we write (generated from theme accents, matching how DeckCraft draws them).
|
||||
|
||||
use crate::opc::NS_A;
|
||||
use crate::xml::{A, W};
|
||||
|
||||
// Keep file-format identifiers in the shared DrawingML implementation. The local
|
||||
// writer below still owns DeckCraft's table style definitions and XML policy.
|
||||
pub use craft_drawingml::table::styles::{guid, guid_for_style};
|
||||
|
||||
fn own_guid(style: &str) -> String {
|
||||
guid(&format!("deckcraft-table-style:{style}"))
|
||||
}
|
||||
|
||||
fn clr(w: &mut W, slot: &str, mods: &[(&str, i32)]) {
|
||||
if mods.is_empty() {
|
||||
w.val("a:schemeClr", slot);
|
||||
return;
|
||||
}
|
||||
w.open("a:schemeClr", A::new().a("val", slot));
|
||||
for (n, v) in mods {
|
||||
w.val(n, v);
|
||||
}
|
||||
w.close("a:schemeClr");
|
||||
}
|
||||
|
||||
fn solid(w: &mut W, slot: &str, mods: &[(&str, i32)]) {
|
||||
w.open0("a:fill");
|
||||
w.open0("a:solidFill");
|
||||
clr(w, slot, mods);
|
||||
w.close("a:solidFill");
|
||||
w.close("a:fill");
|
||||
}
|
||||
|
||||
fn borders(w: &mut W, b: Option<(&str, &[(&str, i32)], i32)>) {
|
||||
w.open0("a:tcBdr");
|
||||
if let Some((slot, mods, width)) = b {
|
||||
for side in ["a:left", "a:right", "a:top", "a:bottom", "a:insideH", "a:insideV"] {
|
||||
w.open0(side);
|
||||
w.open("a:ln", A::new().a("w", width).a("cmpd", "sng"));
|
||||
w.open0("a:solidFill");
|
||||
clr(w, slot, mods);
|
||||
w.close("a:solidFill");
|
||||
w.close("a:ln");
|
||||
w.close(side);
|
||||
}
|
||||
}
|
||||
w.close("a:tcBdr");
|
||||
}
|
||||
|
||||
fn txt(w: &mut W, bold: bool, color: Option<&str>) {
|
||||
w.open("a:tcTxStyle", A::new().o("b", bold.then_some("on")));
|
||||
w.open("a:fontRef", A::new().a("idx", "minor"));
|
||||
w.val("a:prstClr", "black");
|
||||
w.close("a:fontRef");
|
||||
match color {
|
||||
Some(c) => w.val("a:schemeClr", c),
|
||||
None => w.val("a:schemeClr", "dk1"),
|
||||
}
|
||||
w.close("a:tcTxStyle");
|
||||
}
|
||||
|
||||
/// Write one `a:tblStyle` for our style id.
|
||||
fn style_def(w: &mut W, id: &str, name: &str) {
|
||||
let kind = id.split('-').next().unwrap_or("medium2");
|
||||
let acc = match id.rsplit('-').next().unwrap_or("accent1") {
|
||||
"tx1" => "dk1",
|
||||
a if a.starts_with("accent") => a,
|
||||
_ => "accent1",
|
||||
};
|
||||
let acc: &str = acc;
|
||||
w.open("a:tblStyle", A::new().a("styleId", own_guid(id)).a("styleName", name));
|
||||
let part =
|
||||
|w: &mut W, tag: &str, bold: bool, text: Option<&str>, fill: Option<(&str, &[(&str, i32)])>, bdr: Option<(&str, &[(&str, i32)], i32)>| {
|
||||
w.open0(tag);
|
||||
if bold || text.is_some() {
|
||||
txt(w, bold, text);
|
||||
}
|
||||
w.open0("a:tcStyle");
|
||||
borders(w, bdr);
|
||||
if let Some((s, m)) = fill {
|
||||
solid(w, s, m);
|
||||
}
|
||||
w.close("a:tcStyle");
|
||||
w.close(tag);
|
||||
};
|
||||
match kind {
|
||||
"grid" => {
|
||||
part(w, "a:wholeTbl", false, Some("dk1"), None, Some(("dk1", &[], 9525)));
|
||||
}
|
||||
"light1" => {
|
||||
part(w, "a:wholeTbl", false, Some("dk1"), None, None);
|
||||
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 20000)])), None);
|
||||
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 20000)])), None);
|
||||
part(w, "a:lastCol", true, None, None, None);
|
||||
part(w, "a:firstCol", true, None, None, None);
|
||||
part(w, "a:lastRow", true, None, None, None);
|
||||
part(w, "a:firstRow", true, None, None, Some((acc, &[], 12700)));
|
||||
}
|
||||
"light2" => {
|
||||
part(w, "a:wholeTbl", false, Some("dk1"), None, Some((acc, &[], 12700)));
|
||||
// Schema order: … lastCol, firstCol, lastRow, …, firstRow.
|
||||
part(w, "a:firstCol", true, None, None, None);
|
||||
part(w, "a:lastRow", true, None, None, None);
|
||||
part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), Some((acc, &[], 12700)));
|
||||
}
|
||||
"dark1" => {
|
||||
part(w, "a:wholeTbl", false, Some("lt1"), Some((acc, &[("a:shade", 75000)])), Some(("lt1", &[], 12700)));
|
||||
part(w, "a:band1H", false, None, Some((acc, &[("a:shade", 60000)])), None);
|
||||
part(w, "a:band1V", false, None, Some((acc, &[("a:shade", 60000)])), None);
|
||||
part(w, "a:firstCol", true, None, None, None);
|
||||
part(w, "a:lastRow", true, None, None, None);
|
||||
part(w, "a:firstRow", true, Some("lt1"), Some(("dk1", &[])), None);
|
||||
}
|
||||
"medium4" => {
|
||||
part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some((acc, &[], 9525)));
|
||||
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None);
|
||||
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None);
|
||||
part(w, "a:lastCol", true, None, None, None);
|
||||
part(w, "a:firstCol", true, None, None, None);
|
||||
part(w, "a:lastRow", true, None, None, None);
|
||||
part(w, "a:firstRow", true, None, Some((acc, &[("a:tint", 40000)])), None);
|
||||
}
|
||||
_ => {
|
||||
// medium2
|
||||
part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some(("lt1", &[], 12700)));
|
||||
part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None);
|
||||
part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None);
|
||||
part(w, "a:lastCol", true, Some("lt1"), Some((acc, &[])), None);
|
||||
part(w, "a:firstCol", true, Some("lt1"), Some((acc, &[])), None);
|
||||
part(w, "a:lastRow", true, Some("lt1"), Some((acc, &[])), None);
|
||||
part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), None);
|
||||
}
|
||||
}
|
||||
w.close("a:tblStyle");
|
||||
}
|
||||
|
||||
/// `ppt/tableStyles.xml` with definitions for the styles in `used`: ours, generated, and those the
|
||||
/// opened file defined (`defs`), written back as they were read.
|
||||
pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec<u8> {
|
||||
let mut w = W::new();
|
||||
w.open("a:tblStyleLst", A::new().a("xmlns:a", NS_A).a("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"));
|
||||
let names = deckcraft_model::table::table_styles();
|
||||
// Indexes instead of scans: written ids (as given and ASCII lower-case), and the file's
|
||||
// definitions by lower-case id (the first wins).
|
||||
let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
let mut done_lower: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
let mut def_of: std::collections::HashMap<String, &deckcraft_model::table::TableStyleDef> = std::collections::HashMap::new();
|
||||
for d in defs {
|
||||
def_of.entry(d.id.to_ascii_lowercase()).or_insert(d);
|
||||
}
|
||||
for s in used {
|
||||
if !done.insert(s.as_str()) {
|
||||
continue;
|
||||
}
|
||||
done_lower.insert(s.to_ascii_lowercase());
|
||||
if let Some(d) = def_of.get(&s.to_ascii_lowercase())
|
||||
&& crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle"))
|
||||
{
|
||||
w.raw(&d.raw);
|
||||
continue;
|
||||
}
|
||||
let (_, define) = guid_for_style(s);
|
||||
if !define {
|
||||
continue;
|
||||
}
|
||||
let name = names.iter().find(|(id, _)| id == s).map(|(_, n)| format!("DeckCraft {n}")).unwrap_or_else(|| s.clone());
|
||||
style_def(&mut w, s, &name);
|
||||
}
|
||||
// Styles the file defined but no table uses still belong to the deck.
|
||||
for d in defs {
|
||||
if done_lower.contains(&d.id.to_ascii_lowercase()) {
|
||||
continue;
|
||||
}
|
||||
if crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) {
|
||||
done_lower.insert(d.id.to_ascii_lowercase());
|
||||
w.raw(&d.raw);
|
||||
}
|
||||
}
|
||||
w.close("a:tblStyleLst");
|
||||
w.finish()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,871 +0,0 @@
|
||||
//! DrawingML writing: colours, fills, lines, effects, transforms and text.
|
||||
|
||||
use deckcraft_geom::{Xfrm, pt_to_emu};
|
||||
use deckcraft_model::style::{
|
||||
ColorBase, ColorRef, Compound, Dash, Effects, Fill, GradientFlip, GradientShape, Line, LineAlign, LineCap, LineJoin, PictureFill, PictureMode,
|
||||
};
|
||||
use deckcraft_model::text::{
|
||||
Action, AutoFit, BodyProps, Bullet, Caps, Hyperlink, ListStyle, ParaProps, Paragraph, RunKind, RunProps, Spacing, Strike, TextBody,
|
||||
};
|
||||
|
||||
use super::{Exp, Out};
|
||||
use crate::xml::{A, W};
|
||||
|
||||
pub fn emu(pt: f64) -> i64 {
|
||||
pt_to_emu(pt).clamp(-27_273_042_316_900, 27_273_042_316_900)
|
||||
}
|
||||
|
||||
/// Positive coordinate extent (ST_PositiveCoordinate).
|
||||
pub fn emu_pos(pt: f64) -> i64 {
|
||||
emu(pt).max(0)
|
||||
}
|
||||
|
||||
/// Fraction → 1/100 000.
|
||||
pub fn pct(v: f64) -> i64 {
|
||||
if v.is_finite() { (v * 100_000.0).round().clamp(-2.0e9, 2.0e9) as i64 } else { 0 }
|
||||
}
|
||||
|
||||
/// Degrees → 1/60 000 degree, normalised to 0..360.
|
||||
pub fn ang(deg: f64) -> i64 {
|
||||
if !deg.is_finite() {
|
||||
return 0;
|
||||
}
|
||||
let d = deg.rem_euclid(360.0);
|
||||
((d * 60_000.0).round() as i64).clamp(0, 21_599_999)
|
||||
}
|
||||
|
||||
pub fn color(w: &mut W, c: &ColorRef) {
|
||||
let (tag, a) = match &c.base {
|
||||
ColorBase::Rgb { rgb } => ("a:srgbClr", A::new().a("val", rgb.hex())),
|
||||
ColorBase::Scheme { slot } => ("a:schemeClr", A::new().a("val", slot.xml_name())),
|
||||
// The reader keeps any name a file has; only names the schema allows are written.
|
||||
ColorBase::Preset { name } => ("a:prstClr", A::new().a("val", if deckcraft_color::is_preset_name(name) { name } else { "black" })),
|
||||
ColorBase::System { name, last } => {
|
||||
("a:sysClr", A::new().a("val", if deckcraft_color::is_system_name(name) { name } else { "windowText" }).a("lastClr", last.hex()))
|
||||
}
|
||||
};
|
||||
let rgb_alpha = match &c.base {
|
||||
ColorBase::Rgb { rgb } if rgb.a < 255 && !c.mods.iter().any(|m| matches!(m, deckcraft_color::ColorTransform::Alpha(_))) => {
|
||||
Some((rgb.a as i64 * 100_000 / 255) as i32)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if c.mods.is_empty() && rgb_alpha.is_none() {
|
||||
w.empty(tag, a);
|
||||
return;
|
||||
}
|
||||
w.open(tag, a);
|
||||
for m in &c.mods {
|
||||
let name = format!("a:{}", m.xml_name());
|
||||
match m.value() {
|
||||
Some(v) => w.val(&name, v),
|
||||
None => w.empty0(&name),
|
||||
}
|
||||
}
|
||||
if let Some(al) = rgb_alpha {
|
||||
w.val("a:alpha", al);
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
pub fn solid(w: &mut W, c: &ColorRef) {
|
||||
w.open0("a:solidFill");
|
||||
color(w, c);
|
||||
w.close("a:solidFill");
|
||||
}
|
||||
|
||||
/// Write a fill. `Fill::Background` (only meaningful on `p:sp`) writes nothing.
|
||||
pub fn fill(w: &mut W, x: &mut Exp, o: &mut Out, f: &Fill) {
|
||||
match f {
|
||||
Fill::None => w.empty0("a:noFill"),
|
||||
Fill::Solid { color: c } => solid(w, c),
|
||||
Fill::Gradient(g) => gradient(w, g),
|
||||
Fill::Picture(pf) => blip_fill(w, x, o, "a:blipFill", pf),
|
||||
Fill::Pattern(p) => {
|
||||
w.open("a:pattFill", A::new().a("prst", if p.preset.is_empty() { "pct5" } else { &p.preset }));
|
||||
w.open0("a:fgClr");
|
||||
color(w, &p.fg);
|
||||
w.close("a:fgClr");
|
||||
w.open0("a:bgClr");
|
||||
color(w, &p.bg);
|
||||
w.close("a:bgClr");
|
||||
w.close("a:pattFill");
|
||||
}
|
||||
Fill::Group => w.empty0("a:grpFill"),
|
||||
Fill::Background => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `a:blipFill` / `p:blipFill`.
|
||||
pub fn blip_fill(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, pf: &PictureFill) {
|
||||
// An image that lives outside the package is a linked picture: `a:blip` names it through
|
||||
// `r:link`; `r:embed` may only reference a part inside the package.
|
||||
let linked = x.media(pf.media).is_some_and(|m| m.data.is_empty() && m.link.is_some());
|
||||
let rid = x.media_rel(o, pf.media, "image").unwrap_or_else(|| x.placeholder_rel(o));
|
||||
w.open(tag, A::new().a("rotWithShape", if pf.upright { "0" } else { "1" }));
|
||||
let adj = &pf.adjust;
|
||||
let has_kids = pf.alpha.is_some()
|
||||
|| adj.brightness != 0.0
|
||||
|| adj.contrast != 0.0
|
||||
|| adj.grayscale
|
||||
|| adj.duotone.is_some()
|
||||
|| adj.clear_color.is_some()
|
||||
|| adj.bilevel.is_some()
|
||||
|| adj.alpha_inv
|
||||
|| pf.artistic.is_some();
|
||||
let a = if linked { A::new().a("r:link", &rid) } else { A::new().a("r:embed", &rid) };
|
||||
if has_kids {
|
||||
w.open("a:blip", a);
|
||||
if let Some(c) = adj.clear_color {
|
||||
w.open0("a:clrChange");
|
||||
w.open0("a:clrFrom");
|
||||
color(w, &ColorRef::rgb(c));
|
||||
w.close("a:clrFrom");
|
||||
w.open0("a:clrTo");
|
||||
color(w, &ColorRef::rgb(c).with(deckcraft_color::ColorTransform::Alpha(0)));
|
||||
w.close("a:clrTo");
|
||||
w.close("a:clrChange");
|
||||
}
|
||||
if let Some(al) = pf.alpha {
|
||||
w.empty("a:alphaModFix", A::new().a("amt", pct(al.clamp(0.0, 1.0))));
|
||||
}
|
||||
if adj.alpha_inv {
|
||||
w.empty0("a:alphaInv");
|
||||
}
|
||||
if let Some(t) = adj.bilevel {
|
||||
w.empty("a:biLevel", A::new().a("thresh", pct(t.clamp(0.0, 1.0))));
|
||||
}
|
||||
if let Some((d, l)) = &adj.duotone {
|
||||
w.open0("a:duotone");
|
||||
color(w, d);
|
||||
color(w, l);
|
||||
w.close("a:duotone");
|
||||
}
|
||||
if adj.grayscale {
|
||||
w.empty0("a:grayscl");
|
||||
}
|
||||
if adj.brightness != 0.0 || adj.contrast != 0.0 {
|
||||
w.empty("a:lum", A::new().a("bright", pct(adj.brightness.clamp(-1.0, 1.0))).a("contrast", pct(adj.contrast.clamp(-1.0, 1.0))));
|
||||
}
|
||||
// Artistic effect: the blip is the processed picture; the original rides in an
|
||||
// `a14:imgLayer` with the effect's name, as PowerPoint writes it.
|
||||
if let Some(art) = &pf.artistic
|
||||
&& art.effect.starts_with("artistic")
|
||||
&& art.effect.chars().all(|c| c.is_ascii_alphanumeric())
|
||||
&& let Some(orig) = x.media_rel(o, art.original, "image")
|
||||
{
|
||||
w.open0("a:extLst");
|
||||
w.open("a:ext", A::new().a("uri", "{BEBA8EAE-BF5A-486C-A8C5-ECC9F3942E4B}"));
|
||||
w.open("a14:imgProps", A::new().a("xmlns:a14", crate::opc::NS_A14));
|
||||
w.open("a14:imgLayer", A::new().a("r:embed", &orig));
|
||||
w.open0("a14:imgEffect");
|
||||
w.empty0(&format!("a14:{}", art.effect));
|
||||
w.close("a14:imgEffect");
|
||||
w.close("a14:imgLayer");
|
||||
w.close("a14:imgProps");
|
||||
w.close("a:ext");
|
||||
w.close("a:extLst");
|
||||
}
|
||||
w.close("a:blip");
|
||||
} else {
|
||||
w.empty("a:blip", a);
|
||||
}
|
||||
let c = pf.crop;
|
||||
if c.iter().any(|v| *v != 0.0) {
|
||||
w.empty("a:srcRect", A::new().a("l", pct(c[0])).a("t", pct(c[1])).a("r", pct(c[2])).a("b", pct(c[3])));
|
||||
}
|
||||
match &pf.mode {
|
||||
PictureMode::Stretch { fill_rect: r } => {
|
||||
w.open0("a:stretch");
|
||||
if r.iter().any(|v| *v != 0.0) {
|
||||
w.empty("a:fillRect", A::new().a("l", pct(r[0])).a("t", pct(r[1])).a("r", pct(r[2])).a("b", pct(r[3])));
|
||||
} else {
|
||||
w.empty0("a:fillRect");
|
||||
}
|
||||
w.close("a:stretch");
|
||||
}
|
||||
PictureMode::Tile { tx, ty, sx, sy, flip, align } => {
|
||||
let flip = match flip.as_str() {
|
||||
"x" | "y" | "xy" => flip.as_str(),
|
||||
_ => "none",
|
||||
};
|
||||
let algn = match align.as_str() {
|
||||
"tl" | "t" | "tr" | "l" | "ctr" | "r" | "bl" | "b" | "br" => align.as_str(),
|
||||
_ => "tl",
|
||||
};
|
||||
w.empty("a:tile", A::new().a("tx", emu(*tx)).a("ty", emu(*ty)).a("sx", pct(*sx)).a("sy", pct(*sy)).a("flip", flip).a("algn", algn));
|
||||
}
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
pub fn line(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, l: &Line) {
|
||||
let a = A::new()
|
||||
.o("w", l.width.map(|v| emu(v.clamp(0.0, 1584.0))))
|
||||
.o(
|
||||
"cap",
|
||||
l.cap.map(|c| match c {
|
||||
LineCap::Round => "rnd",
|
||||
LineCap::Square => "sq",
|
||||
LineCap::Flat => "flat",
|
||||
}),
|
||||
)
|
||||
.o("algn", l.align.map(LineAlign::xml))
|
||||
.o("cmpd", l.compound.map(Compound::xml));
|
||||
w.open(tag, a);
|
||||
if let Some(f) = &l.fill {
|
||||
match f {
|
||||
Fill::None | Fill::Solid { .. } | Fill::Gradient(_) | Fill::Pattern(_) => fill(w, x, o, f),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match &l.dash {
|
||||
Some(Dash::Preset { name }) => {
|
||||
let n = if Dash::PRESETS.contains(&name.as_str()) { name.as_str() } else { "solid" };
|
||||
w.val("a:prstDash", n);
|
||||
}
|
||||
Some(Dash::Custom { pattern }) if !pattern.is_empty() => {
|
||||
w.open0("a:custDash");
|
||||
for (d, s) in pattern.iter().take(64) {
|
||||
w.empty("a:ds", A::new().a("d", pct(*d).max(0)).a("sp", pct(*s).max(0)));
|
||||
}
|
||||
w.close("a:custDash");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match l.join {
|
||||
Some(LineJoin::Round) => w.empty0("a:round"),
|
||||
Some(LineJoin::Bevel) => w.empty0("a:bevel"),
|
||||
Some(LineJoin::Miter) => {
|
||||
let limit = l.miter_limit.filter(|limit| *limit <= i32::MAX as u32);
|
||||
w.empty("a:miter", A::new().o("lim", limit));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
for (t, e) in [("a:headEnd", &l.head), ("a:tailEnd", &l.tail)] {
|
||||
if let Some(e) = e {
|
||||
let kind = match e.kind.as_str() {
|
||||
"triangle" | "stealth" | "diamond" | "oval" | "arrow" => e.kind.as_str(),
|
||||
_ => "none",
|
||||
};
|
||||
let sz = |s: &str| match s {
|
||||
"sm" | "lg" => s.to_string(),
|
||||
_ => "med".to_string(),
|
||||
};
|
||||
w.empty(t, A::new().a("type", kind).a("w", sz(&e.w)).a("len", sz(&e.len)));
|
||||
}
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
fn shadow(w: &mut W, tag: &str, s: &deckcraft_model::style::Shadow) {
|
||||
let mut a = A::new().a("blurRad", emu(s.blur).max(0)).a("dist", emu(s.dist).max(0)).a("dir", ang(s.dir));
|
||||
if tag == "a:outerShdw" {
|
||||
if s.sx != 1.0 {
|
||||
a = a.a("sx", pct(s.sx));
|
||||
}
|
||||
if s.sy != 1.0 {
|
||||
a = a.a("sy", pct(s.sy));
|
||||
}
|
||||
if s.kx != 0.0 {
|
||||
a = a.a("kx", (s.kx.clamp(-89.0, 89.0) * 60_000.0).round() as i64);
|
||||
}
|
||||
if s.ky != 0.0 {
|
||||
a = a.a("ky", (s.ky.clamp(-89.0, 89.0) * 60_000.0).round() as i64);
|
||||
}
|
||||
let algn = match s.align.as_str() {
|
||||
"tl" | "t" | "tr" | "l" | "ctr" | "r" | "bl" | "b" | "br" => s.align.as_str(),
|
||||
_ => "b",
|
||||
};
|
||||
a = a.a("algn", algn).a("rotWithShape", if s.rotate_with_shape { "1" } else { "0" });
|
||||
}
|
||||
w.open(tag, a);
|
||||
color(w, &s.color);
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
fn gradient(w: &mut W, g: &deckcraft_model::style::Gradient) {
|
||||
w.open("a:gradFill", A::new().o("flip", g.flip.map(GradientFlip::xml)).a("rotWithShape", if g.rotate_with_shape { "1" } else { "0" }));
|
||||
// No stops: no `a:gsLst`, so the gradient keeps taking them from its style's fill.
|
||||
let mut stops = g.stops.clone();
|
||||
if stops.len() == 1 {
|
||||
let mut s = stops[0].clone();
|
||||
s.pos = 1.0;
|
||||
stops.push(s);
|
||||
}
|
||||
if !stops.is_empty() {
|
||||
w.open0("a:gsLst");
|
||||
for s in &stops {
|
||||
w.open("a:gs", A::new().a("pos", pct(s.pos.clamp(0.0, 1.0))));
|
||||
color(w, &s.color);
|
||||
w.close("a:gs");
|
||||
}
|
||||
w.close("a:gsLst");
|
||||
}
|
||||
match &g.shape {
|
||||
GradientShape::Linear { angle, scaled } => w.empty("a:lin", A::new().a("ang", ang(*angle)).a("scaled", if *scaled { "1" } else { "0" })),
|
||||
GradientShape::Path { path, focus } => {
|
||||
let p = match path.as_str() {
|
||||
"rect" | "shape" | "circle" => path.as_str(),
|
||||
_ => "circle",
|
||||
};
|
||||
w.open("a:path", A::new().a("path", p));
|
||||
w.empty("a:fillToRect", A::new().a("l", pct(focus[0])).a("t", pct(focus[1])).a("r", pct(focus[2])).a("b", pct(focus[3])));
|
||||
w.close("a:path");
|
||||
}
|
||||
}
|
||||
if g.tile.iter().any(|v| *v != 0.0) {
|
||||
let [l, t, r, b] = g.tile;
|
||||
w.empty("a:tileRect", A::new().a("l", pct(l)).a("t", pct(t)).a("r", pct(r)).a("b", pct(b)));
|
||||
}
|
||||
w.close("a:gradFill");
|
||||
}
|
||||
|
||||
pub fn effects(w: &mut W, fx: &Effects) {
|
||||
w.open0("a:effectLst");
|
||||
// Schema order: blur, fillOverlay, glow, innerShdw, outerShdw, prstShdw, reflection, softEdge.
|
||||
if let Some(ov) = &fx.fill_overlay {
|
||||
let blend = match ov.blend.as_str() {
|
||||
b @ ("over" | "mult" | "screen" | "darken" | "lighten") => b,
|
||||
_ => "over",
|
||||
};
|
||||
w.open("a:fillOverlay", A::new().a("blend", blend));
|
||||
match &ov.fill {
|
||||
Fill::Solid { color: c } => solid(w, c),
|
||||
Fill::Gradient(g) => gradient(w, g),
|
||||
_ => w.empty0("a:noFill"),
|
||||
}
|
||||
w.close("a:fillOverlay");
|
||||
}
|
||||
if let Some(g) = &fx.glow {
|
||||
w.open("a:glow", A::new().a("rad", emu(g.radius).max(0)));
|
||||
color(w, &g.color);
|
||||
w.close("a:glow");
|
||||
}
|
||||
if let Some(s) = &fx.inner_shadow {
|
||||
shadow(w, "a:innerShdw", s);
|
||||
}
|
||||
if let Some(s) = &fx.outer_shadow {
|
||||
shadow(w, "a:outerShdw", s);
|
||||
}
|
||||
if let Some(r) = &fx.reflection {
|
||||
w.empty(
|
||||
"a:reflection",
|
||||
A::new()
|
||||
.a("blurRad", emu(r.blur).max(0))
|
||||
.a("stA", pct(r.start_alpha.clamp(0.0, 1.0)))
|
||||
.a("endA", pct(r.end_alpha.clamp(0.0, 1.0)))
|
||||
.a("endPos", pct(r.end_pos.clamp(0.0, 1.0)))
|
||||
.a("dist", emu(r.dist).max(0))
|
||||
// Kept from a file as read: held to the schema's ranges so a stray value can't
|
||||
// make PowerPoint repair the file (ST_PositiveFixedAngle, ST_FixedAngle,
|
||||
// ST_PositiveFixedPercentage).
|
||||
.o("stPos", r.st_pos.map(|v| v.clamp(0, 100_000)))
|
||||
.o("dir", r.dir.map(|v| v.rem_euclid(21_600_000)))
|
||||
.o("fadeDir", r.fade_dir.map(|v| v.rem_euclid(21_600_000)))
|
||||
.o("sx", r.sx)
|
||||
.o("sy", r.sy)
|
||||
.o("kx", r.kx.map(|v| v.clamp(-5_399_999, 5_399_999)))
|
||||
.o("ky", r.ky.map(|v| v.clamp(-5_399_999, 5_399_999)))
|
||||
.o("algn", r.align.as_deref())
|
||||
.b("rotWithShape", r.rotate_with_shape),
|
||||
);
|
||||
}
|
||||
if let Some(r) = fx.soft_edge {
|
||||
w.empty("a:softEdge", A::new().a("rad", emu(r).max(0)));
|
||||
}
|
||||
w.close("a:effectLst");
|
||||
}
|
||||
|
||||
/// `a:sp3d` for a bevel preset when the shape or theme style has no kept 3-D XML.
|
||||
/// The preset name is limited to ASCII letters and digits so it cannot break the markup.
|
||||
pub fn bevel_sp3d(preset: &str) -> Option<String> {
|
||||
if preset.is_empty() || preset.len() > 32 || !preset.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("<a:sp3d><a:bevelT prst=\"{preset}\"/></a:sp3d>"))
|
||||
}
|
||||
|
||||
pub fn xfrm(w: &mut W, tag: &str, x: &Xfrm, child: Option<&Xfrm>) {
|
||||
let x = if x.is_finite() { *x } else { Xfrm::default() };
|
||||
let rot = ang(x.rot);
|
||||
w.open(tag, A::new().o("rot", (rot != 0).then_some(rot)).t("flipH", x.flip_h).t("flipV", x.flip_v));
|
||||
w.empty("a:off", A::new().a("x", emu(x.x)).a("y", emu(x.y)));
|
||||
w.empty("a:ext", A::new().a("cx", emu_pos(x.w)).a("cy", emu_pos(x.h)));
|
||||
if let Some(c) = child {
|
||||
let c = if c.is_finite() { *c } else { Xfrm::default() };
|
||||
w.empty("a:chOff", A::new().a("x", emu(c.x)).a("y", emu(c.y)));
|
||||
w.empty("a:chExt", A::new().a("cx", emu_pos(c.w)).a("cy", emu_pos(c.h)));
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Text
|
||||
|
||||
pub fn hyperlink(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, h: &Hyperlink) {
|
||||
let (rid, action) = match &h.action {
|
||||
Action::Url { url } => {
|
||||
if url.is_empty() {
|
||||
return;
|
||||
}
|
||||
(o.rels.add("hyperlink", url, true), None)
|
||||
}
|
||||
Action::Slide { slide } => match x.slide_parts.get(slide) {
|
||||
Some(target) => {
|
||||
let rel = crate::opc::relative(&o.name, target);
|
||||
(o.rels.add("slide", &rel, false), Some("ppaction://hlinksldjump".to_string()))
|
||||
}
|
||||
None => return,
|
||||
},
|
||||
Action::NextSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=nextslide".into())),
|
||||
Action::PreviousSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=previousslide".into())),
|
||||
Action::FirstSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=firstslide".into())),
|
||||
Action::LastSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=lastslide".into())),
|
||||
Action::EndShow => (String::new(), Some("ppaction://hlinkshowjump?jump=endshow".into())),
|
||||
Action::LastViewed => (String::new(), Some("ppaction://hlinkshowjump?jump=lastslideviewed".into())),
|
||||
Action::CustomShow { name, returns } => {
|
||||
let id = x.p.custom_shows.iter().position(|c| c.name == *name).unwrap_or(0);
|
||||
let ret = if *returns { "true" } else { "false" };
|
||||
(String::new(), Some(format!("ppaction://customshow?id={id}&return={ret}")))
|
||||
}
|
||||
Action::Program { path } => {
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
(o.rels.add("hyperlink", path, true), Some("ppaction://program".into()))
|
||||
}
|
||||
Action::PlayMedia => (String::new(), Some("ppaction://media".into())),
|
||||
};
|
||||
let attrs = A::new()
|
||||
.a("r:id", rid)
|
||||
.o("action", action)
|
||||
.o("tooltip", (!h.tooltip.is_empty()).then_some(h.tooltip.as_str()))
|
||||
.t("highlightClick", h.highlight_click)
|
||||
.t("endSnd", h.stop_sound);
|
||||
let sound = h.sound.and_then(|id| x.media_rel(o, id, "audio").map(|rid| (rid, id)));
|
||||
let Some((sound_rid, sound_id)) = sound else {
|
||||
w.empty(tag, attrs);
|
||||
return;
|
||||
};
|
||||
w.open(tag, attrs);
|
||||
let name = x.media(sound_id).map(|m| sound_label(&m.name)).unwrap_or_else(|| "sound.wav".into());
|
||||
w.empty("a:snd", A::new().a("r:embed", sound_rid).a("name", name));
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
/// Display name PowerPoint stores on `a:snd`.
|
||||
fn sound_label(name: &str) -> String {
|
||||
let file = name.rsplit(['/', '\\']).next().unwrap_or(name);
|
||||
let label: String = file.chars().filter(|c| c.is_ascii() && !c.is_control() && *c != '"' && *c != '<' && *c != '>').take(80).collect();
|
||||
if label.is_empty() { "sound.wav".into() } else { label }
|
||||
}
|
||||
|
||||
/// Validate an unmodelled 3-D fragment (`a:scene3d`, `a:sp3d`, `a:flatTx`) before writing raw XML.
|
||||
pub fn valid_raw3d<'a>(raw: &'a str, allowed: &[&str]) -> Option<&'a str> {
|
||||
if raw.is_empty() || raw.len() > 64 * 1024 {
|
||||
return None;
|
||||
}
|
||||
let wrap = format!("<r xmlns:a=\"{}\">{raw}</r>", crate::opc::NS_A);
|
||||
let doc = crate::xml::parse(wrap.as_bytes()).ok()?;
|
||||
let els: Vec<_> = doc.root.elements().collect();
|
||||
(!els.is_empty()
|
||||
&& els.len() <= allowed.len()
|
||||
&& doc.root.children.len() == els.len()
|
||||
&& els.iter().all(|e| e.prefix() == "a" && allowed.contains(&e.local()) && !crate::read::has_rel_refs(e)))
|
||||
.then_some(raw)
|
||||
}
|
||||
|
||||
pub fn body_pr(w: &mut W, b: &BodyProps) {
|
||||
let a = A::new()
|
||||
.o("rot", b.rot.map(|r| (r * 60_000.0).round().clamp(-21_600_000.0, 21_600_000.0) as i64))
|
||||
.o("vert", b.vert.map(|v| v.xml()))
|
||||
.o("wrap", b.wrap.map(|v| if v { "square" } else { "none" }))
|
||||
.o("lIns", b.inset_l.map(emu))
|
||||
.o("tIns", b.inset_t.map(emu))
|
||||
.o("rIns", b.inset_r.map(emu))
|
||||
.o("bIns", b.inset_b.map(emu))
|
||||
.o("numCol", b.columns.map(|c| c.clamp(1, 16)))
|
||||
.o("spcCol", b.col_spacing.map(|v| emu(v).max(0)))
|
||||
.b("rtlCol", b.rtl_col)
|
||||
.o("anchor", b.anchor.map(|a| a.xml()))
|
||||
.b("anchorCtr", b.anchor_ctr)
|
||||
.b("upright", b.upright)
|
||||
.b("spcFirstLastPara", b.space_first_last)
|
||||
.b("compatLnSpc", b.compat_ln_spc)
|
||||
.o("vertOverflow", b.vert_overflow.map(|v| v.xml()))
|
||||
.o("horzOverflow", deckcraft_model::text::TextOverflow::horz_xml(b.horz_overflow));
|
||||
let warp = b.warp.as_deref().filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric()));
|
||||
let raw3d = b.raw3d.as_deref().and_then(|s| valid_raw3d(s, &["scene3d", "sp3d", "flatTx"]));
|
||||
if warp.is_none() && b.autofit.is_none() && raw3d.is_none() {
|
||||
w.empty("a:bodyPr", a);
|
||||
return;
|
||||
}
|
||||
w.open("a:bodyPr", a);
|
||||
if let Some(p) = warp {
|
||||
w.open("a:prstTxWarp", A::new().a("prst", p));
|
||||
let adj: Vec<(usize, i64)> =
|
||||
b.warp_adj.iter().take(8).enumerate().filter(|(_, v)| v.is_finite()).map(|(i, v)| (i, v.round().clamp(-2.0e9, 2.0e9) as i64)).collect();
|
||||
if adj.is_empty() {
|
||||
w.empty0("a:avLst");
|
||||
} else {
|
||||
let single = deckcraft_geom::warp::adjust_count(p) <= 1 && b.warp_adj.len() == 1;
|
||||
w.open0("a:avLst");
|
||||
for (i, v) in adj {
|
||||
let n = if single { "adj".to_string() } else { format!("adj{}", i + 1) };
|
||||
w.empty("a:gd", A::new().a("name", n).a("fmla", format!("val {v}")));
|
||||
}
|
||||
w.close("a:avLst");
|
||||
}
|
||||
w.close("a:prstTxWarp");
|
||||
}
|
||||
match b.autofit {
|
||||
Some(AutoFit::None) => w.empty0("a:noAutofit"),
|
||||
Some(AutoFit::Shape) => w.empty0("a:spAutoFit"),
|
||||
Some(AutoFit::Shrink { font_scale, line_reduction }) => {
|
||||
// A scale the model holds is written, 100 % included: reopening then keeps the same
|
||||
// "draw the saved scale" state instead of becoming a bare `<a:normAutofit/>` (#724).
|
||||
let fs = font_scale.map(|s| pct(s.clamp(0.01, 1.0)));
|
||||
let lr = pct(line_reduction.clamp(0.0, 1.0));
|
||||
w.empty("a:normAutofit", A::new().o("fontScale", fs).o("lnSpcReduction", (lr != 0).then_some(lr)));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some(raw) = raw3d {
|
||||
w.raw(raw);
|
||||
}
|
||||
w.close("a:bodyPr");
|
||||
}
|
||||
|
||||
fn spacing(w: &mut W, tag: &str, s: &Spacing) {
|
||||
w.open0(tag);
|
||||
match s {
|
||||
Spacing::Pct(v) => w.val("a:spcPct", pct(v.clamp(0.0, 132.0))),
|
||||
Spacing::Pts(v) => w.val("a:spcPts", (v.clamp(0.0, 1584.0) * 100.0).round() as i64),
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
pub fn is_default_ppr(p: &ParaProps) -> bool {
|
||||
*p == ParaProps::default()
|
||||
}
|
||||
|
||||
/// `a:pPr` / `a:lvlNpPr`.
|
||||
pub fn ppr(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, level: Option<u8>, p: &ParaProps, def: Option<&RunProps>) {
|
||||
let a = A::new()
|
||||
.o("marL", p.margin_left.map(|v| emu(v.clamp(0.0, 4032.0))))
|
||||
.o("marR", p.margin_right.map(|v| emu(v.clamp(0.0, 4032.0))))
|
||||
.o("lvl", level.filter(|l| *l > 0).map(|l| l.min(8)))
|
||||
.o("indent", p.indent.map(|v| emu(v.clamp(-4032.0, 4032.0))))
|
||||
.o("algn", p.align.map(|a| a.xml()))
|
||||
.o("defTabSz", p.default_tab.map(|v| emu(v).max(0)))
|
||||
.b("rtl", p.rtl)
|
||||
.b("eaLnBrk", p.east_asian_line_break)
|
||||
.b("latinLnBrk", p.latin_line_break)
|
||||
.b("hangingPunct", p.hanging_punct)
|
||||
.o("fontAlgn", p.font_align.as_deref().filter(|f| matches!(*f, "auto" | "t" | "ctr" | "base" | "b")));
|
||||
let has_kids = p.line_spacing.is_some()
|
||||
|| p.space_before.is_some()
|
||||
|| p.space_after.is_some()
|
||||
|| p.bullet.is_some()
|
||||
|| p.bullet_font.is_some()
|
||||
|| p.bullet_font_follow_text.is_some()
|
||||
|| p.bullet_color.is_some()
|
||||
|| p.bullet_color_follow_text.is_some()
|
||||
|| p.bullet_size.is_some()
|
||||
|| p.bullet_size_points.is_some()
|
||||
|| p.bullet_size_follow_text.is_some()
|
||||
|| p.tabs.is_some()
|
||||
|| def.is_some();
|
||||
if !has_kids {
|
||||
w.empty(tag, a);
|
||||
return;
|
||||
}
|
||||
w.open(tag, a);
|
||||
if let Some(s) = &p.line_spacing {
|
||||
spacing(w, "a:lnSpc", s);
|
||||
}
|
||||
if let Some(s) = &p.space_before {
|
||||
spacing(w, "a:spcBef", s);
|
||||
}
|
||||
if let Some(s) = &p.space_after {
|
||||
spacing(w, "a:spcAft", s);
|
||||
}
|
||||
if p.bullet_color.is_none() && p.bullet_color_follow_text == Some(true) {
|
||||
w.empty0("a:buClrTx");
|
||||
} else if let Some(c) = &p.bullet_color {
|
||||
w.open0("a:buClr");
|
||||
color(w, c);
|
||||
w.close("a:buClr");
|
||||
}
|
||||
if p.bullet_size.is_none() && p.bullet_size_points.is_none() && p.bullet_size_follow_text == Some(true) {
|
||||
w.empty0("a:buSzTx");
|
||||
} else if let Some(s) = p.bullet_size_points.filter(|s| s.is_finite() && (1.0..=4000.0).contains(s)) {
|
||||
w.val("a:buSzPts", ((s * 100.0).round() as u32).to_string());
|
||||
} else if let Some(s) = p.bullet_size {
|
||||
w.val("a:buSzPct", pct(s.clamp(0.25, 4.0)));
|
||||
}
|
||||
if p.bullet_font.is_none() && p.bullet_font_follow_text == Some(true) {
|
||||
w.empty0("a:buFontTx");
|
||||
} else if let Some(f) = &p.bullet_font {
|
||||
w.empty("a:buFont", A::new().a("typeface", f));
|
||||
}
|
||||
match &p.bullet {
|
||||
Some(Bullet::None) => w.empty0("a:buNone"),
|
||||
Some(Bullet::Char { char }) => w.empty("a:buChar", A::new().a("char", if char.is_empty() { "•" } else { char })),
|
||||
Some(Bullet::AutoNum { scheme, start_at }) => {
|
||||
let s = if scheme.is_empty() || !scheme.chars().all(|c| c.is_ascii_alphanumeric()) { "arabicPeriod" } else { scheme };
|
||||
w.empty("a:buAutoNum", A::new().a("type", s).o("startAt", (*start_at != 1).then_some((*start_at).clamp(1, 32767))));
|
||||
}
|
||||
Some(Bullet::Picture { media }) => match x.media_rel(o, *media, "image") {
|
||||
Some(rid) => {
|
||||
w.open0("a:buBlip");
|
||||
let a = if x.media(*media).is_some_and(|m| m.data.is_empty() && m.link.is_some()) {
|
||||
A::new().a("r:link", &rid)
|
||||
} else {
|
||||
A::new().a("r:embed", &rid)
|
||||
};
|
||||
w.empty("a:blip", a);
|
||||
w.close("a:buBlip");
|
||||
}
|
||||
None => w.empty("a:buChar", A::new().a("char", "•")),
|
||||
},
|
||||
None => {}
|
||||
}
|
||||
if let Some(t) = &p.tabs {
|
||||
w.open0("a:tabLst");
|
||||
for tab in t.iter().take(32) {
|
||||
let al = match tab.align.as_str() {
|
||||
"ctr" | "r" | "dec" => tab.align.as_str(),
|
||||
_ => "l",
|
||||
};
|
||||
w.empty("a:tab", A::new().a("pos", emu(tab.pos)).a("algn", al));
|
||||
}
|
||||
w.close("a:tabLst");
|
||||
}
|
||||
if let Some(d) = def {
|
||||
rpr(w, x, o, "a:defRPr", d);
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
fn typeface(w: &mut W, tag: &str, f: &Option<String>) {
|
||||
if let Some(f) = f {
|
||||
w.empty(tag, A::new().a("typeface", f));
|
||||
}
|
||||
}
|
||||
|
||||
/// `a:rPr`, `a:defRPr`, `a:endParaRPr`.
|
||||
pub fn rpr(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, r: &RunProps) {
|
||||
let a = A::new()
|
||||
.o("lang", r.lang.as_deref().filter(|l| !l.is_empty()))
|
||||
.o("altLang", r.alt_lang.as_deref().filter(|l| !l.is_empty()))
|
||||
.o("sz", r.size.map(|s| (s.clamp(1.0, 4000.0) * 100.0).round() as i64))
|
||||
.b("b", r.bold)
|
||||
.b("i", r.italic)
|
||||
.o("u", r.underline.as_deref().filter(|u| !u.is_empty() && u.chars().all(|c| c.is_ascii_alphanumeric())))
|
||||
.o(
|
||||
"strike",
|
||||
r.strike.map(|s| match s {
|
||||
Strike::None => "noStrike",
|
||||
Strike::Single => "sngStrike",
|
||||
Strike::Double => "dblStrike",
|
||||
}),
|
||||
)
|
||||
.o("kern", r.kern.map(|k| (k.clamp(0.0, 4000.0) * 100.0).round() as i64))
|
||||
.o(
|
||||
"cap",
|
||||
r.caps.map(|c| match c {
|
||||
Caps::None => "none",
|
||||
Caps::Small => "small",
|
||||
Caps::All => "all",
|
||||
}),
|
||||
)
|
||||
.o("spc", r.spacing.map(|s| (s.clamp(-4000.0, 4000.0) * 100.0).round() as i64))
|
||||
.o("baseline", r.baseline.map(|b| pct(b.clamp(-10.0, 10.0))))
|
||||
.b("noProof", r.no_proof)
|
||||
.b("normalizeH", r.normalize_height);
|
||||
let has_fx = r.shadow.is_some() || r.inner_shadow.is_some() || r.glow.is_some() || r.reflection.is_some() || r.soft_edge.is_some();
|
||||
let has_kids = r.outline.is_some()
|
||||
|| r.fill.is_some()
|
||||
|| has_fx
|
||||
|| r.highlight.is_some()
|
||||
|| r.underline_color.is_some()
|
||||
|| r.font.is_some()
|
||||
|| r.font_ea.is_some()
|
||||
|| r.font_cs.is_some()
|
||||
|| r.font_sym.is_some()
|
||||
|| r.link.is_some()
|
||||
|| r.hover.is_some();
|
||||
if !has_kids {
|
||||
w.empty(tag, a);
|
||||
return;
|
||||
}
|
||||
w.open(tag, a);
|
||||
if let Some(l) = &r.outline {
|
||||
line(w, x, o, "a:ln", l);
|
||||
}
|
||||
if let Some(f) = &r.fill {
|
||||
match f {
|
||||
Fill::Background => {}
|
||||
f => fill(w, x, o, f),
|
||||
}
|
||||
}
|
||||
if has_fx {
|
||||
// Same child order as a shape's effect list: glow, inner shadow, outer shadow, reflection, soft edge.
|
||||
effects(
|
||||
w,
|
||||
&Effects {
|
||||
outer_shadow: r.shadow.clone(),
|
||||
inner_shadow: r.inner_shadow.clone(),
|
||||
glow: r.glow.clone(),
|
||||
reflection: r.reflection.clone(),
|
||||
soft_edge: r.soft_edge,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(h) = &r.highlight {
|
||||
w.open0("a:highlight");
|
||||
color(w, h);
|
||||
w.close("a:highlight");
|
||||
}
|
||||
if let Some(c) = &r.underline_color {
|
||||
w.open0("a:uFill");
|
||||
solid(w, c);
|
||||
w.close("a:uFill");
|
||||
}
|
||||
typeface(w, "a:latin", &r.font);
|
||||
typeface(w, "a:ea", &r.font_ea);
|
||||
typeface(w, "a:cs", &r.font_cs);
|
||||
typeface(w, "a:sym", &r.font_sym);
|
||||
if let Some(h) = &r.link {
|
||||
hyperlink(w, x, o, "a:hlinkClick", h);
|
||||
}
|
||||
// Schema order: hlinkClick, hlinkMouseOver.
|
||||
if let Some(h) = &r.hover {
|
||||
hyperlink(w, x, o, "a:hlinkMouseOver", h);
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
/// `a:lstStyle`-like element (`a:lstStyle`, `p:titleStyle`, `p:defaultTextStyle`…).
|
||||
pub fn list_style(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, ls: &ListStyle) {
|
||||
if ls.is_empty() {
|
||||
w.empty0(tag);
|
||||
return;
|
||||
}
|
||||
w.open0(tag);
|
||||
for (i, l) in ls.levels.iter().enumerate().take(9) {
|
||||
if let Some(l) = l {
|
||||
let t = format!("a:lvl{}pPr", i + 1);
|
||||
let def = (l.run != RunProps::default()).then_some(&l.run);
|
||||
ppr(w, x, o, &t, None, &l.para, def);
|
||||
}
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
/// Write `<tag>` text body (`p:txBody`, `a:txBody`). `math` selects the OMML form of equations.
|
||||
pub fn text_body(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, tb: &TextBody, math: bool) {
|
||||
w.open0(tag);
|
||||
body_pr(w, &tb.body);
|
||||
list_style(w, x, o, "a:lstStyle", &tb.list_style);
|
||||
if tb.paragraphs.is_empty() {
|
||||
w.empty0("a:p");
|
||||
}
|
||||
for (pi, p) in tb.paragraphs.iter().enumerate() {
|
||||
paragraph(w, x, o, p, math, pi);
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
fn run_text(w: &mut W, x: &mut Exp, o: &mut Out, text: &str, props: &RunProps) {
|
||||
// The run's properties are the same for every piece and line break: serialize them once.
|
||||
let mut rpr_xml: Option<String> = None;
|
||||
let mut put_rpr = |w: &mut W| match &rpr_xml {
|
||||
Some(xml) => w.s.push_str(xml),
|
||||
None => {
|
||||
let start = w.s.len();
|
||||
rpr(w, x, o, "a:rPr", props);
|
||||
rpr_xml = Some(w.s[start..].to_string());
|
||||
}
|
||||
};
|
||||
for (i, piece) in text.split(['\n', '\u{b}']).enumerate() {
|
||||
if i > 0 {
|
||||
w.open0("a:br");
|
||||
put_rpr(w);
|
||||
w.close("a:br");
|
||||
}
|
||||
if piece.is_empty() && i > 0 {
|
||||
continue;
|
||||
}
|
||||
w.open0("a:r");
|
||||
put_rpr(w);
|
||||
w.elt("a:t", piece);
|
||||
w.close("a:r");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn paragraph(w: &mut W, x: &mut Exp, o: &mut Out, p: &Paragraph, math: bool, index: usize) {
|
||||
w.open0("a:p");
|
||||
let def = (p.def_props != RunProps::default()).then_some(&p.def_props);
|
||||
if p.level > 0 || !is_default_ppr(&p.props) || def.is_some() {
|
||||
ppr(w, x, o, "a:pPr", Some(p.level), &p.props, def);
|
||||
}
|
||||
for (ri, r) in p.runs.iter().enumerate() {
|
||||
match &r.kind {
|
||||
RunKind::Text => run_text(w, x, o, &r.text, &r.props),
|
||||
RunKind::Break => {
|
||||
w.open0("a:br");
|
||||
rpr(w, x, o, "a:rPr", &r.props);
|
||||
w.close("a:br");
|
||||
}
|
||||
RunKind::Field { field } => {
|
||||
let id = crate::tables::guid(&format!("{}:{index}:{ri}:{field}", o.name));
|
||||
let ty = (!field.is_empty() && field.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then_some(field.as_str());
|
||||
w.open("a:fld", A::new().a("id", id).o("type", ty));
|
||||
rpr(w, x, o, "a:rPr", &r.props);
|
||||
w.elt("a:t", &r.text);
|
||||
w.close("a:fld");
|
||||
}
|
||||
RunKind::Math { omml } => {
|
||||
if math && !omml.is_empty() {
|
||||
w.open("a14:m", A::new().a("xmlns:a14", crate::opc::NS_A14));
|
||||
w.raw(omml);
|
||||
w.close("a14:m");
|
||||
} else {
|
||||
run_text(w, x, o, &r.text, &r.props);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.end_props != RunProps::default() {
|
||||
rpr(w, x, o, "a:endParaRPr", &p.end_props);
|
||||
}
|
||||
w.close("a:p");
|
||||
}
|
||||
|
||||
pub fn has_math(tb: &TextBody) -> bool {
|
||||
tb.paragraphs.iter().flat_map(|p| &p.runs).any(|r| matches!(&r.kind, RunKind::Math { omml } if !omml.is_empty()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use deckcraft_color::Rgba;
|
||||
|
||||
#[test]
|
||||
fn unknown_preset_and_system_names_save_as_black_and_window_text() {
|
||||
let write = |base: ColorBase| {
|
||||
let mut w = W::frag();
|
||||
color(&mut w, &ColorRef { base, mods: vec![] });
|
||||
w.s
|
||||
};
|
||||
assert_eq!(write(ColorBase::Preset { name: "notAColor".into() }), r#"<a:prstClr val="black"/>"#);
|
||||
assert_eq!(write(ColorBase::Preset { name: "darkBlue".into() }), r#"<a:prstClr val="darkBlue"/>"#);
|
||||
let last = Rgba::rgb(0x12, 0x34, 0x56);
|
||||
assert_eq!(write(ColorBase::System { name: "notAColor".into(), last }), r#"<a:sysClr val="windowText" lastClr="123456"/>"#);
|
||||
assert_eq!(write(ColorBase::System { name: "3dLight".into(), last }), r#"<a:sysClr val="3dLight" lastClr="123456"/>"#);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,112 +0,0 @@
|
||||
//! Theme parts.
|
||||
|
||||
use deckcraft_color::SchemeSlot;
|
||||
use deckcraft_model::style::{ColorRef, Effects, Fill};
|
||||
use deckcraft_model::theme::{FontSet, Theme, default_format};
|
||||
|
||||
use super::{Exp, Out, dml};
|
||||
use crate::opc::{NS_A, NS_R};
|
||||
use crate::xml::{A, W};
|
||||
|
||||
fn font_set(w: &mut W, tag: &str, f: &FontSet) {
|
||||
w.open0(tag);
|
||||
w.empty("a:latin", A::new().a("typeface", if f.latin.is_empty() { "Arial" } else { &f.latin }));
|
||||
w.empty("a:ea", A::new().a("typeface", &f.ea));
|
||||
w.empty("a:cs", A::new().a("typeface", &f.cs));
|
||||
for sf in &f.scripts {
|
||||
w.empty("a:font", A::new().a("script", &sf.script).a("typeface", &sf.typeface));
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
|
||||
fn style_fill(f: &Fill) -> Fill {
|
||||
match f {
|
||||
Fill::Background | Fill::Group => Fill::solid(ColorRef::scheme(SchemeSlot::PhClr)),
|
||||
f => f.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn theme_xml(x: &mut Exp, o: &mut Out, t: &Theme) -> Vec<u8> {
|
||||
let mut w = W::new();
|
||||
w.open("a:theme", A::new().a("xmlns:a", NS_A).a("xmlns:r", NS_R).a("name", if t.name.is_empty() { "Theme" } else { &t.name }));
|
||||
w.open0("a:themeElements");
|
||||
w.open("a:clrScheme", A::new().a("name", if t.colors.name.is_empty() { &t.name } else { &t.colors.name }));
|
||||
for slot in SchemeSlot::THEME {
|
||||
let tag = format!("a:{}", slot.xml_name());
|
||||
w.open0(&tag);
|
||||
w.val("a:srgbClr", t.colors.get(slot).hex());
|
||||
w.close(&tag);
|
||||
}
|
||||
w.close("a:clrScheme");
|
||||
w.open("a:fontScheme", A::new().a("name", if t.fonts.name.is_empty() { &t.name } else { &t.fonts.name }));
|
||||
font_set(&mut w, "a:majorFont", &t.fonts.major);
|
||||
font_set(&mut w, "a:minorFont", &t.fonts.minor);
|
||||
w.close("a:fontScheme");
|
||||
let d = default_format();
|
||||
let f = &t.format;
|
||||
w.open("a:fmtScheme", A::new().a("name", if f.name.is_empty() { &t.name } else { &f.name }));
|
||||
let three = |v: &[Fill], d: &[Fill]| -> Vec<Fill> {
|
||||
let mut out: Vec<Fill> = v.iter().map(style_fill).collect();
|
||||
while out.len() < 3 {
|
||||
out.push(d.get(out.len()).cloned().unwrap_or(Fill::solid(ColorRef::scheme(SchemeSlot::PhClr))));
|
||||
}
|
||||
out
|
||||
};
|
||||
w.open0("a:fillStyleLst");
|
||||
for fl in three(&f.fills, &d.fills) {
|
||||
dml::fill(&mut w, x, o, &fl);
|
||||
}
|
||||
w.close("a:fillStyleLst");
|
||||
w.open0("a:lnStyleLst");
|
||||
let mut lines = f.lines.clone();
|
||||
while lines.len() < 3 {
|
||||
lines.push(d.lines.get(lines.len()).cloned().unwrap_or_default());
|
||||
}
|
||||
for l in &lines {
|
||||
let mut l = l.clone();
|
||||
if l.fill.is_none() {
|
||||
l.fill = Some(Fill::solid(ColorRef::scheme(SchemeSlot::PhClr)));
|
||||
}
|
||||
if let Some(fl) = &l.fill {
|
||||
l.fill = Some(style_fill(fl));
|
||||
}
|
||||
dml::line(&mut w, x, o, "a:ln", &l);
|
||||
}
|
||||
w.close("a:lnStyleLst");
|
||||
w.open0("a:effectStyleLst");
|
||||
let mut fx = f.effects.clone();
|
||||
while fx.len() < 3 {
|
||||
fx.push(Effects::default());
|
||||
}
|
||||
for e in &fx {
|
||||
w.open0("a:effectStyle");
|
||||
dml::effects(&mut w, e);
|
||||
if let Some(raw) = &e.raw3d {
|
||||
w.raw(raw);
|
||||
} else if let Some(xml) = e.bevel.as_deref().and_then(dml::bevel_sp3d) {
|
||||
w.raw(&xml);
|
||||
}
|
||||
w.close("a:effectStyle");
|
||||
}
|
||||
w.close("a:effectStyleLst");
|
||||
w.open0("a:bgFillStyleLst");
|
||||
for fl in three(&f.bg_fills, &d.bg_fills) {
|
||||
dml::fill(&mut w, x, o, &fl);
|
||||
}
|
||||
w.close("a:bgFillStyleLst");
|
||||
w.close("a:fmtScheme");
|
||||
w.close("a:themeElements");
|
||||
match &t.raw_extra {
|
||||
Some(raw) if raw.contains("objectDefaults") => w.raw(raw),
|
||||
Some(raw) => {
|
||||
w.empty0("a:objectDefaults");
|
||||
w.raw(raw);
|
||||
}
|
||||
None => {
|
||||
w.empty0("a:objectDefaults");
|
||||
w.empty0("a:extraClrSchemeLst");
|
||||
}
|
||||
}
|
||||
w.close("a:theme");
|
||||
w.finish()
|
||||
}
|
||||
@@ -1,830 +0,0 @@
|
||||
//! Transitions and the animation timing tree.
|
||||
|
||||
use deckcraft_model::anim::{AnimClass, AnimStart, Animation, BuildRole, TextBuild, Transition, build_filled, paragraph_build_roles};
|
||||
use deckcraft_model::{Shape, ShapeId, ShapeKind};
|
||||
|
||||
use super::shapes::IdMap;
|
||||
use super::{Exp, Out};
|
||||
use crate::opc::{NS_MC, NS_P14, NS_P15, NS_P159};
|
||||
use crate::xml::{A, W};
|
||||
|
||||
pub fn transition(w: &mut W, x: &mut Exp, o: &mut Out, t: &Transition) {
|
||||
let adv_click = (!t.advance_on_click).then_some("0");
|
||||
let adv_tm = t.advance_after_ms.map(|v| v.min(86_400_000));
|
||||
let spd = match t.duration_ms {
|
||||
0..=600 => "fast",
|
||||
601..=900 => "med",
|
||||
_ => "slow",
|
||||
};
|
||||
let sound = t.sound.and_then(|m| x.media_rel(o, m, "audio").map(|r| (r, x.media(m).map(|i| i.name.clone()).unwrap_or_default())));
|
||||
let snd = |w: &mut W| {
|
||||
if let Some((r, name)) = &sound {
|
||||
w.open0("p:sndAc");
|
||||
w.open("p:stSnd", A::new().t("loop", t.sound_loop));
|
||||
let name = if name.is_empty() { "sound.wav" } else { name.as_str() };
|
||||
w.empty("p:snd", A::new().a("r:embed", r).a("name", name));
|
||||
w.close("p:stSnd");
|
||||
w.close("p:sndAc");
|
||||
} else if t.stop_sound {
|
||||
w.open0("p:sndAc");
|
||||
w.empty0("p:endSnd");
|
||||
w.close("p:sndAc");
|
||||
}
|
||||
};
|
||||
let mut effect = W::frag();
|
||||
let ns = if t.kind == "none" { Some("p") } else { super::super::maps::transition_to_xml(&mut effect, &t.kind, &t.option) };
|
||||
let ns = match ns {
|
||||
Some(ns) => ns,
|
||||
None => {
|
||||
// Unknown kind: write the kept element if there is one, else a fade.
|
||||
if let Some(raw) = &t.raw
|
||||
&& let Ok(d) = crate::xml::parse(raw.as_bytes())
|
||||
&& let Some(e) = d.root.elements().find(|e| !matches!(e.local(), "sndAc" | "extLst"))
|
||||
&& !crate::read::has_rel_refs(e)
|
||||
{
|
||||
let prefix = e.prefix().to_string();
|
||||
let mut ns_decl = d.ns_decls();
|
||||
ns_decl.retain(|(k, _)| k == &format!("xmlns:{prefix}"));
|
||||
let mut e2 = e.clone();
|
||||
for (k, v) in ns_decl {
|
||||
e2.attrs.push((k, v));
|
||||
}
|
||||
effect.raw(&e2.to_xml());
|
||||
match prefix.as_str() {
|
||||
"p14" => "p14",
|
||||
"p15" => "p15",
|
||||
"p159" => "p159",
|
||||
"p" => "p",
|
||||
_ => {
|
||||
effect = W::frag();
|
||||
effect.empty0("p:fade");
|
||||
"p"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
effect.empty0("p:fade");
|
||||
"p"
|
||||
}
|
||||
}
|
||||
};
|
||||
let is_none = t.kind == "none";
|
||||
let dur = t.duration_ms.min(60_000);
|
||||
w.open("mc:AlternateContent", A::new().a("xmlns:mc", NS_MC));
|
||||
let mut ch = A::new().a("xmlns:p14", NS_P14);
|
||||
let req = match ns {
|
||||
"p15" => {
|
||||
ch = ch.a("xmlns:p15", NS_P15);
|
||||
"p15"
|
||||
}
|
||||
"p159" => {
|
||||
ch = ch.a("xmlns:p159", NS_P159);
|
||||
"p159"
|
||||
}
|
||||
_ => "p14",
|
||||
};
|
||||
w.open("mc:Choice", ch.a("Requires", req));
|
||||
w.open("p:transition", A::new().a("spd", spd).o("p14:dur", (!is_none).then_some(dur)).o("advClick", adv_click).o("advTm", adv_tm));
|
||||
if !is_none {
|
||||
w.raw(&effect.s);
|
||||
}
|
||||
snd(w);
|
||||
w.close("p:transition");
|
||||
w.close("mc:Choice");
|
||||
w.open0("mc:Fallback");
|
||||
w.open("p:transition", A::new().a("spd", spd).o("advClick", adv_click).o("advTm", adv_tm));
|
||||
if !is_none {
|
||||
if ns == "p" {
|
||||
w.raw(&effect.s);
|
||||
} else {
|
||||
w.empty0("p:fade");
|
||||
}
|
||||
}
|
||||
snd(w);
|
||||
w.close("p:transition");
|
||||
w.close("mc:Fallback");
|
||||
w.close("mc:AlternateContent");
|
||||
}
|
||||
|
||||
/// One effect to write (an animation, or one paragraph of a by-paragraph build).
|
||||
struct Eff<'a> {
|
||||
a: &'a Animation,
|
||||
spid: u32,
|
||||
start: AnimStart,
|
||||
paragraph: Option<u32>,
|
||||
grp: u32,
|
||||
}
|
||||
|
||||
struct Ids(u32);
|
||||
|
||||
impl Ids {
|
||||
fn next(&mut self) -> u32 {
|
||||
self.0 = self.0.saturating_add(1);
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
fn tgt(w: &mut W, spid: u32, para: Option<u32>) {
|
||||
w.open0("p:tgtEl");
|
||||
match para {
|
||||
Some(p) => {
|
||||
w.open("p:spTgt", A::new().a("spid", spid));
|
||||
w.open0("p:txEl");
|
||||
w.empty("p:pRg", A::new().a("st", p).a("end", p));
|
||||
w.close("p:txEl");
|
||||
w.close("p:spTgt");
|
||||
}
|
||||
None => w.empty("p:spTgt", A::new().a("spid", spid)),
|
||||
}
|
||||
w.close("p:tgtEl");
|
||||
}
|
||||
|
||||
fn cbhvr(w: &mut W, ids: &mut Ids, e: &Eff, dur: u32, delay: Option<u32>, attrs: &[&str], additive: Option<&str>) {
|
||||
w.open("p:cBhvr", A::new().o("additive", additive));
|
||||
let a = A::new().a("id", ids.next()).a("dur", dur.max(1)).a("fill", "hold");
|
||||
match delay {
|
||||
Some(d) => {
|
||||
w.open("p:cTn", a);
|
||||
w.open0("p:stCondLst");
|
||||
w.empty("p:cond", A::new().a("delay", d));
|
||||
w.close("p:stCondLst");
|
||||
w.close("p:cTn");
|
||||
}
|
||||
None => w.empty("p:cTn", a),
|
||||
}
|
||||
tgt(w, e.spid, e.paragraph);
|
||||
if !attrs.is_empty() {
|
||||
w.open0("p:attrNameLst");
|
||||
for n in attrs {
|
||||
w.elt("p:attrName", n);
|
||||
}
|
||||
w.close("p:attrNameLst");
|
||||
}
|
||||
w.close("p:cBhvr");
|
||||
}
|
||||
|
||||
fn set_vis(w: &mut W, ids: &mut Ids, e: &Eff, delay: u32, visible: bool) {
|
||||
w.open0("p:set");
|
||||
cbhvr(w, ids, e, 1, Some(delay), &["style.visibility"], None);
|
||||
w.open0("p:to");
|
||||
w.val("p:strVal", if visible { "visible" } else { "hidden" });
|
||||
w.close("p:to");
|
||||
w.close("p:set");
|
||||
}
|
||||
|
||||
fn anim_effect(w: &mut W, ids: &mut Ids, e: &Eff, dur: u32, filter: &str, out: bool) {
|
||||
w.open("p:animEffect", A::new().a("transition", if out { "out" } else { "in" }).a("filter", filter));
|
||||
cbhvr(w, ids, e, dur, None, &[], None);
|
||||
w.close("p:animEffect");
|
||||
}
|
||||
|
||||
fn anim_prop(w: &mut W, ids: &mut Ids, e: &Eff, dur: u32, attr: &str, from: &str, to: &str) {
|
||||
w.open("p:anim", A::new().a("calcmode", "lin").a("valueType", "num"));
|
||||
cbhvr(w, ids, e, dur, None, &[attr], Some("base"));
|
||||
w.open0("p:tavLst");
|
||||
for (tm, v) in [(0, from), (100_000, to)] {
|
||||
w.open("p:tav", A::new().a("tm", tm));
|
||||
w.open0("p:val");
|
||||
w.val("p:strVal", v);
|
||||
w.close("p:val");
|
||||
w.close("p:tav");
|
||||
}
|
||||
w.close("p:tavLst");
|
||||
w.close("p:anim");
|
||||
}
|
||||
|
||||
fn filter_for(effect: &str, option: &str) -> &'static str {
|
||||
match effect {
|
||||
"wipe" | "wipeOut" => match option {
|
||||
"t" => "wipe(down)",
|
||||
"l" => "wipe(right)",
|
||||
"r" => "wipe(left)",
|
||||
_ => "wipe(up)",
|
||||
},
|
||||
"split" | "splitOut" => match option {
|
||||
"horzOut" => "barn(outHorizontal)",
|
||||
"vertIn" => "barn(inVertical)",
|
||||
"vertOut" => "barn(outVertical)",
|
||||
_ => "barn(inHorizontal)",
|
||||
},
|
||||
"randomBars" | "randomBarsOut" => {
|
||||
if option == "vert" {
|
||||
"randombar(vertical)"
|
||||
} else {
|
||||
"randombar(horizontal)"
|
||||
}
|
||||
}
|
||||
"blinds" | "blindsOut" => {
|
||||
if option == "vert" {
|
||||
"blinds(vertical)"
|
||||
} else {
|
||||
"blinds(horizontal)"
|
||||
}
|
||||
}
|
||||
"box" | "boxOut" => {
|
||||
if option == "out" {
|
||||
"box(out)"
|
||||
} else {
|
||||
"box(in)"
|
||||
}
|
||||
}
|
||||
"circle" => {
|
||||
if option == "out" {
|
||||
"circle(out)"
|
||||
} else {
|
||||
"circle(in)"
|
||||
}
|
||||
}
|
||||
"diamond" | "diamondOut" => {
|
||||
if option == "out" {
|
||||
"diamond(out)"
|
||||
} else {
|
||||
"diamond(in)"
|
||||
}
|
||||
}
|
||||
"shape" | "shapeOut" => match option {
|
||||
"circleOut" => "circle(out)",
|
||||
"boxIn" => "box(in)",
|
||||
"boxOut" => "box(out)",
|
||||
"diamondIn" => "diamond(in)",
|
||||
"diamondOut" => "diamond(out)",
|
||||
"plusIn" => "plus(in)",
|
||||
"plusOut" => "plus(out)",
|
||||
_ => "circle(in)",
|
||||
},
|
||||
"checkerboard" | "checkerboardOut" => {
|
||||
if option == "down" {
|
||||
"checkerboard(down)"
|
||||
} else {
|
||||
"checkerboard(across)"
|
||||
}
|
||||
}
|
||||
"dissolve" | "dissolveOut" => "dissolve",
|
||||
"wheel" | "wheelOut" => match option {
|
||||
"2" => "wheel(2)",
|
||||
"3" => "wheel(3)",
|
||||
"4" => "wheel(4)",
|
||||
"8" => "wheel(8)",
|
||||
_ => "wheel(1)",
|
||||
},
|
||||
"strips" | "stripsOut" => match option {
|
||||
"ru" => "strips(upRight)",
|
||||
"ld" => "strips(downLeft)",
|
||||
"rd" => "strips(downRight)",
|
||||
_ => "strips(upLeft)",
|
||||
},
|
||||
"peek" | "peekOut" => match option {
|
||||
"t" => "slide(fromTop)",
|
||||
"l" => "slide(fromLeft)",
|
||||
"r" => "slide(fromRight)",
|
||||
_ => "slide(fromBottom)",
|
||||
},
|
||||
_ => "fade",
|
||||
}
|
||||
}
|
||||
|
||||
fn fly_from(option: &str) -> (&'static str, &'static str) {
|
||||
let x = if option.contains('l') {
|
||||
"0-#ppt_w/2"
|
||||
} else if option.contains('r') {
|
||||
"1+#ppt_w/2"
|
||||
} else {
|
||||
"#ppt_x"
|
||||
};
|
||||
let y = if option.contains('t') {
|
||||
"0-#ppt_h/2"
|
||||
} else if option.contains('b') || option.is_empty() {
|
||||
"1+#ppt_h/2"
|
||||
} else {
|
||||
"#ppt_y"
|
||||
};
|
||||
(x, y)
|
||||
}
|
||||
|
||||
fn behaviors(w: &mut W, x: &mut Exp, ids: &mut Ids, e: &Eff) {
|
||||
let a = e.a;
|
||||
let dur = a.duration_ms.clamp(1, 3_600_000);
|
||||
match a.class {
|
||||
AnimClass::Entrance => {
|
||||
set_vis(w, ids, e, 0, true);
|
||||
match a.effect.as_str() {
|
||||
"appear" => {}
|
||||
"fly" => {
|
||||
let (fx, fy) = fly_from(&a.option);
|
||||
anim_prop(w, ids, e, dur, "ppt_x", fx, "#ppt_x");
|
||||
anim_prop(w, ids, e, dur, "ppt_y", fy, "#ppt_y");
|
||||
}
|
||||
"zoom" | "grow" | "expand" | "spinner" => {
|
||||
anim_prop(w, ids, e, dur, "ppt_w", "0", "#ppt_w");
|
||||
anim_prop(w, ids, e, dur, "ppt_h", "0", "#ppt_h");
|
||||
anim_effect(w, ids, e, dur, "fade", false);
|
||||
}
|
||||
"float" | "rise" => {
|
||||
anim_prop(w, ids, e, dur, "ppt_y", if a.option == "d" { "#ppt_y-.1" } else { "#ppt_y+.1" }, "#ppt_y");
|
||||
anim_effect(w, ids, e, dur, "fade", false);
|
||||
}
|
||||
other => anim_effect(w, ids, e, dur, filter_for(other, &a.option), false),
|
||||
}
|
||||
}
|
||||
AnimClass::Exit => {
|
||||
match a.effect.as_str() {
|
||||
"disappear" => {}
|
||||
"flyOut" => {
|
||||
let (fx, fy) = fly_from(&a.option);
|
||||
anim_prop(w, ids, e, dur, "ppt_x", "#ppt_x", fx);
|
||||
anim_prop(w, ids, e, dur, "ppt_y", "#ppt_y", fy);
|
||||
}
|
||||
"floatOut" | "sinkDown" => {
|
||||
let to = if a.effect == "sinkDown" || a.option == "d" { "#ppt_y+.1" } else { "#ppt_y-.1" };
|
||||
anim_prop(w, ids, e, dur, "ppt_y", "#ppt_y", to);
|
||||
anim_effect(w, ids, e, dur, "fade", true);
|
||||
}
|
||||
"zoomOut" | "shrinkTurn" | "spinnerOut" | "contract" => {
|
||||
anim_prop(w, ids, e, dur, "ppt_w", "#ppt_w", "0");
|
||||
anim_prop(w, ids, e, dur, "ppt_h", "#ppt_h", "0");
|
||||
anim_effect(w, ids, e, dur, "fade", true);
|
||||
}
|
||||
other => anim_effect(w, ids, e, dur, filter_for(other, &a.option), true),
|
||||
}
|
||||
set_vis(w, ids, e, if a.effect == "disappear" { 0 } else { dur.saturating_sub(1) }, false);
|
||||
}
|
||||
AnimClass::Emphasis => match a.effect.as_str() {
|
||||
"spin" | "teeter" => {
|
||||
let deg = a.amount.unwrap_or(if a.effect == "teeter" { 4.0 } else { 360.0 });
|
||||
let deg = if a.option == "counterClockwise" { -deg.abs() } else { deg };
|
||||
let by = (deg.clamp(-36_000.0, 36_000.0) * 60_000.0).round() as i64;
|
||||
w.open("p:animRot", A::new().a("by", by));
|
||||
cbhvr(w, ids, e, dur, None, &["r"], None);
|
||||
w.close("p:animRot");
|
||||
}
|
||||
"transparency" => {
|
||||
w.open0("p:set");
|
||||
cbhvr(w, ids, e, dur, None, &["style.opacity"], None);
|
||||
w.open0("p:to");
|
||||
w.val("p:strVal", format!("{:.2}", (1.0 - a.amount.unwrap_or(0.5)).clamp(0.0, 1.0)));
|
||||
w.close("p:to");
|
||||
w.close("p:set");
|
||||
}
|
||||
"colorPulse" => {
|
||||
// As PowerPoint writes it: text and fill go to the colour and back (autoRev). The behaviour
|
||||
// duration is the one import reads as the effect duration.
|
||||
let c = a.color.clone().unwrap_or(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(0xC0, 0x00, 0x00)));
|
||||
for (attr, child) in [("style.color", true), ("fillcolor", false)] {
|
||||
w.open("p:animClr", A::new().a("clrSpc", "rgb").a("dir", "cw"));
|
||||
w.open("p:cBhvr", A::new().o("override", child.then_some("childStyle")));
|
||||
w.empty("p:cTn", A::new().a("id", ids.next()).a("dur", dur.max(1)).a("autoRev", "1").a("fill", "remove"));
|
||||
tgt(w, e.spid, e.paragraph);
|
||||
w.open0("p:attrNameLst");
|
||||
w.elt("p:attrName", attr);
|
||||
w.close("p:attrNameLst");
|
||||
w.close("p:cBhvr");
|
||||
w.open0("p:to");
|
||||
super::dml::color(w, &c);
|
||||
w.close("p:to");
|
||||
w.close("p:animClr");
|
||||
}
|
||||
}
|
||||
// As PowerPoint writes them: a relative HSL shift of text, fill and line colour.
|
||||
"darken" | "desaturate" => {
|
||||
let (s, l) = if a.effect == "darken" { (0, -25_098) } else { (-70_588, 0) };
|
||||
for attr in ["style.color", "fillcolor", "stroke.color"] {
|
||||
w.open("p:animClr", A::new().a("clrSpc", "hsl").a("dir", "cw"));
|
||||
cbhvr(w, ids, e, dur, None, &[attr], None);
|
||||
w.open0("p:by");
|
||||
w.empty("p:hsl", A::new().a("h", 0).a("s", s).a("l", l));
|
||||
w.close("p:by");
|
||||
w.close("p:animClr");
|
||||
}
|
||||
}
|
||||
"fillColor" | "objectColor" | "fontColor" | "lineColor" | "complementaryColor" | "lighten" => {
|
||||
let attr = match a.effect.as_str() {
|
||||
"fontColor" => "style.color",
|
||||
"lineColor" => "stroke.color",
|
||||
_ => "fillcolor",
|
||||
};
|
||||
let c = a.color.clone().unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent2));
|
||||
w.open("p:animClr", A::new().a("clrSpc", "rgb").a("dir", "cw"));
|
||||
cbhvr(w, ids, e, dur, None, &[attr], None);
|
||||
w.open0("p:to");
|
||||
super::dml::color(w, &c);
|
||||
w.close("p:to");
|
||||
w.close("p:animClr");
|
||||
}
|
||||
_ => {
|
||||
let s = a.amount.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(if a.effect == "growShrink" { 1.5 } else { 1.1 });
|
||||
let (sx, sy) = match a.option.as_str() {
|
||||
"horz" => (s, 1.0),
|
||||
"vert" => (1.0, s),
|
||||
_ => (s, s),
|
||||
};
|
||||
w.open0("p:animScale");
|
||||
cbhvr(w, ids, e, dur, None, &[], None);
|
||||
w.empty(
|
||||
"p:by",
|
||||
A::new().a("x", (sx.clamp(0.01, 100.0) * 100_000.0).round() as i64).a("y", (sy.clamp(0.01, 100.0) * 100_000.0).round() as i64),
|
||||
);
|
||||
w.close("p:animScale");
|
||||
}
|
||||
},
|
||||
AnimClass::Path => {
|
||||
let path = a
|
||||
.path
|
||||
.clone()
|
||||
.filter(|p| !p.trim().is_empty() && p.chars().all(|c| c.is_ascii() && c != '"' && c != '<' && c != '&'))
|
||||
.unwrap_or_else(|| {
|
||||
match a.option.as_str() {
|
||||
"up" => "M 0 0 L 0 -0.25 E",
|
||||
"right" => "M 0 0 L 0.25 0 E",
|
||||
"left" => "M 0 0 L -0.25 0 E",
|
||||
_ => "M 0 0 L 0 0.25 E",
|
||||
}
|
||||
.to_string()
|
||||
});
|
||||
w.open("p:animMotion", A::new().a("origin", "layout").a("path", path).a("pathEditMode", "relative").a("ptsTypes", ""));
|
||||
cbhvr(w, ids, e, dur, None, &["ppt_x", "ppt_y"], None);
|
||||
w.close("p:animMotion");
|
||||
}
|
||||
AnimClass::Media => {
|
||||
let cmd = match a.effect.as_str() {
|
||||
"pause" => "togglePause",
|
||||
"stop" => "stop",
|
||||
_ => "playFrom(0.0)",
|
||||
};
|
||||
w.open("p:cmd", A::new().a("type", "call").a("cmd", cmd));
|
||||
cbhvr(w, ids, e, 1, None, &[], None);
|
||||
w.close("p:cmd");
|
||||
}
|
||||
}
|
||||
let _ = x;
|
||||
}
|
||||
|
||||
fn effect_par(w: &mut W, x: &mut Exp, ids: &mut Ids, e: &Eff, first_in_click: bool) {
|
||||
let a = e.a;
|
||||
let node = match e.start {
|
||||
AnimStart::OnClick => "clickEffect",
|
||||
AnimStart::WithPrevious => "withEffect",
|
||||
AnimStart::AfterPrevious => "afterEffect",
|
||||
};
|
||||
let _ = first_in_click;
|
||||
let preset = crate::maps::preset_for(a);
|
||||
let sub = if preset == 47 {
|
||||
0
|
||||
} else {
|
||||
crate::maps::subtype_from_option(&a.effect, &a.option).or(a.preset_subtype.filter(|_| a.preset_id == Some(preset))).unwrap_or(0)
|
||||
};
|
||||
let repeat = match a.repeat {
|
||||
u32::MAX => Some("indefinite".to_string()),
|
||||
0 | 1 => None,
|
||||
n => Some((n.min(10_000) * 1000).to_string()),
|
||||
};
|
||||
let accel = (a.smooth_start > 0.0).then(|| (a.smooth_start.clamp(0.0, 1.0) * 100_000.0).round() as i64);
|
||||
let decel = (a.smooth_end > 0.0).then(|| (a.smooth_end.clamp(0.0, 1.0) * 100_000.0).round() as i64);
|
||||
// `bounceEnd` is a positive percentage (100000 = 100%), same scale as accel/decel. The model stores 0–1.
|
||||
let bounce =
|
||||
(a.bounce_end.is_finite() && a.bounce_end > 0.0).then(|| (a.bounce_end.clamp(0.0, 1.0) * 100_000.0).round() as i64).filter(|n| *n > 0);
|
||||
w.open0("p:par");
|
||||
w.open(
|
||||
"p:cTn",
|
||||
A::new()
|
||||
.a("id", ids.next())
|
||||
.a("presetID", preset)
|
||||
.a("presetClass", a.class.xml())
|
||||
.a("presetSubtype", sub)
|
||||
.o("repeatCount", repeat)
|
||||
.o("accel", accel)
|
||||
.o("decel", decel)
|
||||
.o("bounceEnd", bounce)
|
||||
.t("autoRev", a.auto_reverse)
|
||||
.a("fill", if a.rewind { "remove" } else { "hold" })
|
||||
.a("grpId", e.grp)
|
||||
.a("nodeType", node),
|
||||
);
|
||||
w.open0("p:stCondLst");
|
||||
w.empty("p:cond", A::new().a("delay", a.delay_ms.min(3_600_000)));
|
||||
w.close("p:stCondLst");
|
||||
w.open0("p:childTnLst");
|
||||
behaviors(w, x, ids, e);
|
||||
w.close("p:childTnLst");
|
||||
w.close("p:cTn");
|
||||
w.close("p:par");
|
||||
}
|
||||
|
||||
fn end_time(e: &Eff) -> u32 {
|
||||
let rep = match e.a.repeat {
|
||||
0 | 1 => 1,
|
||||
u32::MAX => 1,
|
||||
n => n.min(100),
|
||||
};
|
||||
e.a.delay_ms.saturating_add(e.a.duration_ms.saturating_mul(rep)).min(3_600_000)
|
||||
}
|
||||
|
||||
/// click groups → after-groups → effects
|
||||
type Groups<'a> = Vec<(bool, Vec<Vec<Eff<'a>>>)>;
|
||||
|
||||
fn group<'a>(effects: Vec<Eff<'a>>) -> Groups<'a> {
|
||||
let mut clicks: Groups = vec![];
|
||||
for e in effects {
|
||||
match e.start {
|
||||
AnimStart::OnClick => clicks.push((false, vec![vec![e]])),
|
||||
AnimStart::WithPrevious => match clicks.last_mut().and_then(|c| c.1.last_mut()) {
|
||||
Some(g) => g.push(e),
|
||||
None => clicks.push((true, vec![vec![e]])),
|
||||
},
|
||||
AnimStart::AfterPrevious => match clicks.last_mut() {
|
||||
Some(c) => c.1.push(vec![e]),
|
||||
None => clicks.push((true, vec![vec![e]])),
|
||||
},
|
||||
}
|
||||
}
|
||||
clicks
|
||||
}
|
||||
|
||||
fn click_pars(w: &mut W, x: &mut Exp, ids: &mut Ids, clicks: &Groups, interactive: bool) {
|
||||
for (ci, (auto, afters)) in clicks.iter().enumerate() {
|
||||
w.open0("p:par");
|
||||
w.open("p:cTn", A::new().a("id", ids.next()).a("fill", "hold"));
|
||||
w.open0("p:stCondLst");
|
||||
if interactive && ci == 0 {
|
||||
w.empty("p:cond", A::new().a("delay", 0));
|
||||
} else {
|
||||
w.empty("p:cond", A::new().a("delay", "indefinite"));
|
||||
if *auto {
|
||||
w.open("p:cond", A::new().a("evt", "onBegin").a("delay", 0));
|
||||
w.val("p:tn", 2);
|
||||
w.close("p:cond");
|
||||
}
|
||||
}
|
||||
w.close("p:stCondLst");
|
||||
w.open0("p:childTnLst");
|
||||
let mut t = 0u32;
|
||||
for g in afters {
|
||||
w.open0("p:par");
|
||||
w.open("p:cTn", A::new().a("id", ids.next()).a("fill", "hold"));
|
||||
w.open0("p:stCondLst");
|
||||
w.empty("p:cond", A::new().a("delay", t));
|
||||
w.close("p:stCondLst");
|
||||
w.open0("p:childTnLst");
|
||||
for (i, e) in g.iter().enumerate() {
|
||||
effect_par(w, x, ids, e, i == 0);
|
||||
}
|
||||
w.close("p:childTnLst");
|
||||
w.close("p:cTn");
|
||||
w.close("p:par");
|
||||
t = t.saturating_add(g.iter().map(end_time).max().unwrap_or(0));
|
||||
}
|
||||
w.close("p:childTnLst");
|
||||
w.close("p:cTn");
|
||||
w.close("p:par");
|
||||
}
|
||||
}
|
||||
|
||||
/// Most effects one slide's timing writes; animations past it are left out.
|
||||
const MAX_EFFECTS: usize = 100_000;
|
||||
|
||||
/// The shapes of the tree by id, the first in document order for a repeated id (as `find_shape`
|
||||
/// finds it), so each animation resolves its shape without a tree walk.
|
||||
fn shape_index<'a>(shapes: &'a [Shape], depth: usize, out: &mut std::collections::HashMap<ShapeId, &'a Shape>) {
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
for s in shapes {
|
||||
out.entry(s.id).or_insert(s);
|
||||
shape_index(s.children(), depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `p:timing` for a slide's animations and media settings.
|
||||
pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idmap: &IdMap) {
|
||||
let mut grp_count: std::collections::HashMap<u32, u32> = Default::default();
|
||||
let mut main: Vec<Eff> = vec![];
|
||||
let mut triggered: Vec<(u32, Vec<Eff>)> = vec![];
|
||||
let mut bld: Vec<(u32, u32, bool)> = vec![];
|
||||
// The last paragraph effect written: (shape, class, trigger, grpId).
|
||||
let mut prev_para: Option<(ShapeId, AnimClass, Option<ShapeId>, u32)> = None;
|
||||
let mut by_id = std::collections::HashMap::new();
|
||||
shape_index(shapes, 0, &mut by_id);
|
||||
let mut roles_of: std::collections::HashMap<ShapeId, Vec<BuildRole>> = Default::default();
|
||||
let mut effect_count = 0usize;
|
||||
let mut warned = false;
|
||||
for a in anims.iter().take(10_000) {
|
||||
if effect_count >= MAX_EFFECTS {
|
||||
if !warned {
|
||||
log::warn!("pptx: more than {MAX_EFFECTS} animation effects; the rest are left out");
|
||||
}
|
||||
break;
|
||||
}
|
||||
let Some(spid) = idmap.get(a.shape) else {
|
||||
log::warn!("pptx: animation on missing shape {} skipped", a.shape);
|
||||
continue;
|
||||
};
|
||||
let Some(&shape) = by_id.get(&a.shape) else { continue };
|
||||
let text_sp = matches!(shape.kind, ShapeKind::Shape) && shape.text.is_some();
|
||||
let is_text_sp = matches!(shape.kind, ShapeKind::Shape) && shape.text.as_ref().is_some_and(|t| !t.is_empty());
|
||||
let text = shape.text.as_ref().filter(|_| a.text_build == TextBuild::ByParagraph && is_text_sp);
|
||||
let no_roles = Vec::new();
|
||||
let roles = match text {
|
||||
Some(t) => roles_of.entry(a.shape).or_insert_with(|| paragraph_build_roles(t)),
|
||||
None => &no_roles,
|
||||
};
|
||||
let by_para = roles.contains(&BuildRole::Top);
|
||||
// PowerPoint keeps a shape's consecutive paragraph effects in one build (`grpId`) marked
|
||||
// `build="p"`; the reader turns them back into a by-paragraph build only if that plays them
|
||||
// the same way.
|
||||
let para_effect = !by_para && text_sp && a.paragraph.is_some();
|
||||
let joins = para_effect && prev_para.is_some_and(|(s, c, t, _)| s == a.shape && c == a.class && t == a.trigger);
|
||||
let grp = match prev_para {
|
||||
Some((.., g)) if joins => g,
|
||||
_ => {
|
||||
let c = grp_count.entry(spid).or_insert(0);
|
||||
let g = *c;
|
||||
*c += 1;
|
||||
g
|
||||
}
|
||||
};
|
||||
prev_para = para_effect.then_some((a.shape, a.class, a.trigger, grp));
|
||||
let mut effs = vec![];
|
||||
if by_para {
|
||||
// One effect per paragraph the build animates on its own, deeper ones with their
|
||||
// parent; indices in the file count empty paragraphs too.
|
||||
let mut tops = 0;
|
||||
for (i, role) in roles.iter().enumerate() {
|
||||
let start = match role {
|
||||
BuildRole::Top => {
|
||||
tops += 1;
|
||||
if tops == 1 {
|
||||
a.start
|
||||
} else if a.start == AnimStart::OnClick {
|
||||
AnimStart::OnClick
|
||||
} else {
|
||||
AnimStart::AfterPrevious
|
||||
}
|
||||
}
|
||||
BuildRole::Member(_) if text.and_then(|t| t.paragraphs.get(i)).is_some_and(build_filled) => AnimStart::WithPrevious,
|
||||
_ => continue,
|
||||
};
|
||||
let Ok(pi) = u32::try_from(i) else { break };
|
||||
if effect_count + effs.len() >= MAX_EFFECTS {
|
||||
if !warned {
|
||||
log::warn!("pptx: more than {MAX_EFFECTS} animation effects; the rest are left out");
|
||||
warned = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
effs.push(Eff { a, spid, start, paragraph: Some(pi), grp });
|
||||
}
|
||||
} else {
|
||||
effs.push(Eff { a, spid, start: a.start, paragraph: a.paragraph, grp });
|
||||
}
|
||||
effect_count += effs.len();
|
||||
if text_sp && !joins {
|
||||
bld.push((spid, grp, by_para || para_effect));
|
||||
}
|
||||
match a.trigger.and_then(|t| idmap.get(t)) {
|
||||
Some(t) => match triggered.iter_mut().find(|(s, _)| *s == t) {
|
||||
Some((_, v)) => v.extend(effs),
|
||||
None => triggered.push((t, effs)),
|
||||
},
|
||||
None => main.extend(effs),
|
||||
}
|
||||
}
|
||||
let media = collect_media(shapes, idmap);
|
||||
if main.is_empty() && triggered.is_empty() && media.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut ids = Ids(0);
|
||||
w.open0("p:timing");
|
||||
w.open0("p:tnLst");
|
||||
w.open0("p:par");
|
||||
w.open("p:cTn", A::new().a("id", ids.next()).a("dur", "indefinite").a("restart", "never").a("nodeType", "tmRoot"));
|
||||
w.open0("p:childTnLst");
|
||||
if !main.is_empty() {
|
||||
let clicks = group(main);
|
||||
w.open("p:seq", A::new().a("concurrent", 1).a("nextAc", "seek"));
|
||||
w.open("p:cTn", A::new().a("id", ids.next()).a("dur", "indefinite").a("nodeType", "mainSeq"));
|
||||
w.open0("p:childTnLst");
|
||||
click_pars(w, x, &mut ids, &clicks, false);
|
||||
w.close("p:childTnLst");
|
||||
w.close("p:cTn");
|
||||
w.open0("p:prevCondLst");
|
||||
w.open("p:cond", A::new().a("evt", "onPrev").a("delay", 0));
|
||||
w.open0("p:tgtEl");
|
||||
w.empty0("p:sldTgt");
|
||||
w.close("p:tgtEl");
|
||||
w.close("p:cond");
|
||||
w.close("p:prevCondLst");
|
||||
w.open0("p:nextCondLst");
|
||||
w.open("p:cond", A::new().a("evt", "onNext").a("delay", 0));
|
||||
w.open0("p:tgtEl");
|
||||
w.empty0("p:sldTgt");
|
||||
w.close("p:tgtEl");
|
||||
w.close("p:cond");
|
||||
w.close("p:nextCondLst");
|
||||
w.close("p:seq");
|
||||
}
|
||||
for (trig, effs) in triggered {
|
||||
// The first step starts with the button's click. Later On Click effects must remain
|
||||
// separate steps; With/After Previous effects still belong to their preceding step.
|
||||
let effs: Vec<Eff> =
|
||||
effs.into_iter().enumerate().map(|(i, e)| Eff { start: if i == 0 { AnimStart::OnClick } else { e.start }, ..e }).collect();
|
||||
let clicks = group(effs);
|
||||
let trig_cond = |w: &mut W| {
|
||||
w.open("p:cond", A::new().a("evt", "onClick").a("delay", 0));
|
||||
w.open0("p:tgtEl");
|
||||
w.empty("p:spTgt", A::new().a("spid", trig));
|
||||
w.close("p:tgtEl");
|
||||
w.close("p:cond");
|
||||
};
|
||||
w.open("p:seq", A::new().a("concurrent", 1).a("nextAc", "seek"));
|
||||
w.open(
|
||||
"p:cTn",
|
||||
A::new()
|
||||
.a("id", ids.next())
|
||||
.a("restart", "whenNotActive")
|
||||
.a("fill", "hold")
|
||||
.a("evtFilter", "cancelBubble")
|
||||
.a("nodeType", "interactiveSeq"),
|
||||
);
|
||||
w.open0("p:stCondLst");
|
||||
trig_cond(w);
|
||||
w.close("p:stCondLst");
|
||||
w.open("p:endSync", A::new().a("evt", "end").a("delay", 0));
|
||||
w.empty("p:rtn", A::new().a("val", "all"));
|
||||
w.close("p:endSync");
|
||||
w.open0("p:childTnLst");
|
||||
click_pars(w, x, &mut ids, &clicks, true);
|
||||
w.close("p:childTnLst");
|
||||
w.close("p:cTn");
|
||||
w.open0("p:nextCondLst");
|
||||
trig_cond(w);
|
||||
w.close("p:nextCondLst");
|
||||
w.close("p:seq");
|
||||
}
|
||||
for (spid, clip) in &media {
|
||||
write_media_node(w, &mut ids, *spid, clip);
|
||||
}
|
||||
w.close("p:childTnLst");
|
||||
w.close("p:cTn");
|
||||
w.close("p:par");
|
||||
w.close("p:tnLst");
|
||||
if !bld.is_empty() {
|
||||
w.open0("p:bldLst");
|
||||
for (spid, grp, build_p) in bld {
|
||||
w.empty("p:bldP", A::new().a("spid", spid).a("grpId", grp).o("build", build_p.then_some("p")).t("animBg", !build_p));
|
||||
}
|
||||
w.close("p:bldLst");
|
||||
}
|
||||
w.close("p:timing");
|
||||
}
|
||||
|
||||
/// Collects media shapes on the slide that have non-default playback settings requiring a `p:video`/`p:audio` timing node.
|
||||
fn collect_media<'a>(shapes: &'a [Shape], idmap: &IdMap) -> Vec<(u32, &'a deckcraft_model::MediaClip)> {
|
||||
let mut media = Vec::new();
|
||||
deckcraft_model::walk(shapes, &mut |shape, _| {
|
||||
if let ShapeKind::Media(clip) = &shape.kind
|
||||
&& (clip.autoplay
|
||||
|| (clip.volume - 1.0).abs() > 1e-6
|
||||
|| clip.hide_while_not_playing
|
||||
|| clip.loop_play
|
||||
|| clip.rewind
|
||||
|| clip.play_across_slides
|
||||
|| (clip.video && clip.full_screen))
|
||||
&& let Some(spid) = idmap.get(shape.id)
|
||||
{
|
||||
media.push((spid, clip));
|
||||
}
|
||||
});
|
||||
media
|
||||
}
|
||||
|
||||
/// Writes a `p:video` or `p:audio` media timing node (`p:cMediaNode`) for a media shape.
|
||||
fn write_media_node(w: &mut W, ids: &mut Ids, spid: u32, clip: &deckcraft_model::MediaClip) {
|
||||
let tag = if clip.video { "p:video" } else { "p:audio" };
|
||||
w.open(tag, A::new().t("fullScrn", clip.video && clip.full_screen));
|
||||
let mut cm = A::new().a("vol", (clip.volume.clamp(0.0, 1.0) * 100_000.0).round() as u32);
|
||||
if clip.volume <= 1e-6 {
|
||||
cm = cm.t("mute", true);
|
||||
}
|
||||
if clip.hide_while_not_playing {
|
||||
cm = cm.a("showWhenStopped", 0);
|
||||
}
|
||||
if clip.play_across_slides {
|
||||
cm = cm.a("numSld", 999);
|
||||
}
|
||||
w.open("p:cMediaNode", cm);
|
||||
w.open(
|
||||
"p:cTn",
|
||||
A::new()
|
||||
.a("id", ids.next())
|
||||
.a("fill", if clip.rewind { "remove" } else { "hold" })
|
||||
.a("display", 0)
|
||||
.o("repeatCount", clip.loop_play.then_some("indefinite")),
|
||||
);
|
||||
w.open0("p:stCondLst");
|
||||
w.empty("p:cond", A::new().a("delay", if clip.autoplay { "0" } else { "indefinite" }));
|
||||
w.close("p:stCondLst");
|
||||
w.close("p:cTn");
|
||||
w.open0("p:tgtEl");
|
||||
w.empty("p:spTgt", A::new().a("spid", spid));
|
||||
w.close("p:tgtEl");
|
||||
w.close("p:cMediaNode");
|
||||
w.close(tag);
|
||||
}
|
||||
+61
-492
@@ -1,23 +1,10 @@
|
||||
//! A small, bounded XML DOM over quick-xml for reading parts, plus an escaping string builder for
|
||||
//! writing them.
|
||||
//!
|
||||
//! Reading is lenient about namespaces: elements and attributes are matched by local name, which is
|
||||
//! how real-world files are best understood (prefixes are conventional and stable in practice).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use quick_xml::events::Event;
|
||||
//! Bounded XML DOM wrapper over [`craft_drawingml::xmlx::parse`] for callers that read kept
|
||||
//! XML fragments (such as 3-D shape settings).
|
||||
|
||||
use crate::PptxError;
|
||||
|
||||
/// Maximum element nesting accepted when parsing.
|
||||
pub const MAX_DEPTH: usize = 256;
|
||||
/// Maximum number of elements in one part.
|
||||
pub const MAX_NODES: usize = 4_000_000;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct El {
|
||||
/// Qualified name as written (`p:sp`).
|
||||
pub name: String,
|
||||
pub attrs: Vec<(String, String)>,
|
||||
pub children: Vec<Node>,
|
||||
@@ -30,515 +17,97 @@ pub enum Node {
|
||||
}
|
||||
|
||||
fn local_of(name: &str) -> &str {
|
||||
name.rsplit_once(':').map(|(_, l)| l).unwrap_or(name)
|
||||
name.rsplit_once(':').map_or(name, |(_, l)| l)
|
||||
}
|
||||
|
||||
impl El {
|
||||
pub fn local(&self) -> &str {
|
||||
local_of(&self.name)
|
||||
}
|
||||
|
||||
pub fn prefix(&self) -> &str {
|
||||
self.name.split_once(':').map(|(p, _)| p).unwrap_or("")
|
||||
self.name.split_once(':').map_or("", |(p, _)| p)
|
||||
}
|
||||
|
||||
pub fn is(&self, local: &str) -> bool {
|
||||
self.local() == local
|
||||
}
|
||||
/// Attribute by local name (`id` matches `id`; `r:id` matches `id` only when no plain `id`
|
||||
/// exists). Pass a qualified name (`r:id`) to require that prefix's local name with any prefix.
|
||||
|
||||
pub fn to_xml(&self) -> String {
|
||||
let mut out = String::new();
|
||||
self.write_xml(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn write_xml(&self, out: &mut String) {
|
||||
out.push('<');
|
||||
out.push_str(&self.name);
|
||||
for (k, v) in &self.attrs {
|
||||
out.push(' ');
|
||||
out.push_str(k);
|
||||
out.push_str("=\"");
|
||||
craft_xml::push_esc_attr(out, v);
|
||||
out.push('"');
|
||||
}
|
||||
if self.children.is_empty() {
|
||||
out.push_str("/>");
|
||||
return;
|
||||
}
|
||||
out.push('>');
|
||||
for c in &self.children {
|
||||
match c {
|
||||
Node::El(e) => e.write_xml(out),
|
||||
Node::Text(t) => craft_xml::push_esc(out, t),
|
||||
}
|
||||
}
|
||||
out.push_str("</");
|
||||
out.push_str(&self.name);
|
||||
out.push('>');
|
||||
}
|
||||
|
||||
pub fn attr(&self, name: &str) -> Option<&str> {
|
||||
if let Some((_, l)) = name.split_once(':') {
|
||||
return self.attrs.iter().find(|(k, _)| k.contains(':') && !k.starts_with("xmlns") && local_of(k) == l).map(|(_, v)| v.as_str());
|
||||
}
|
||||
self.attrs
|
||||
.iter()
|
||||
.find(|(k, _)| k == name)
|
||||
.or_else(|| self.attrs.iter().find(|(k, _)| !k.starts_with("xmlns") && local_of(k) == name))
|
||||
.map(|(_, v)| v.as_str())
|
||||
}
|
||||
pub fn has_attr(&self, name: &str) -> bool {
|
||||
self.attr(name).is_some()
|
||||
}
|
||||
pub fn set_attr(&mut self, name: &str, value: &str) {
|
||||
if let Some(a) = self.attrs.iter_mut().find(|(k, _)| k == name) {
|
||||
a.1 = value.to_string();
|
||||
} else {
|
||||
self.attrs.push((name.to_string(), value.to_string()));
|
||||
}
|
||||
}
|
||||
pub fn i64(&self, name: &str) -> Option<i64> {
|
||||
let v = self.attr(name)?.trim();
|
||||
v.parse::<i64>().ok().or_else(|| v.parse::<f64>().ok().filter(|f| f.is_finite()).map(|f| f.clamp(-9.0e18, 9.0e18) as i64))
|
||||
}
|
||||
pub fn i32(&self, name: &str) -> Option<i32> {
|
||||
self.i64(name).map(|v| v.clamp(i32::MIN as i64, i32::MAX as i64) as i32)
|
||||
}
|
||||
pub fn u32(&self, name: &str) -> Option<u32> {
|
||||
self.i64(name).map(|v| v.clamp(0, u32::MAX as i64) as u32)
|
||||
}
|
||||
pub fn f64(&self, name: &str) -> Option<f64> {
|
||||
self.attr(name)?.trim().parse::<f64>().ok().filter(|f| f.is_finite())
|
||||
}
|
||||
pub fn bool(&self, name: &str) -> Option<bool> {
|
||||
match self.attr(name)?.trim() {
|
||||
"1" | "true" | "on" => Some(true),
|
||||
"0" | "false" | "off" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
self.attrs.iter().find(|(k, _)| k == name || local_of(k) == name).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
pub fn elements(&self) -> impl Iterator<Item = &El> {
|
||||
self.children.iter().filter_map(|n| match n {
|
||||
Node::El(e) => Some(e),
|
||||
Node::Text(_) => None,
|
||||
})
|
||||
}
|
||||
pub fn elements_mut(&mut self) -> impl Iterator<Item = &mut El> {
|
||||
self.children.iter_mut().filter_map(|n| match n {
|
||||
Node::El(e) => Some(e),
|
||||
Node::Text(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn child(&self, local: &str) -> Option<&El> {
|
||||
self.elements().find(|e| e.is(local))
|
||||
self.elements().find(|e| e.local() == local)
|
||||
}
|
||||
|
||||
pub fn children_named<'a>(&'a self, local: &'a str) -> impl Iterator<Item = &'a El> + 'a {
|
||||
self.elements().filter(move |e| e.is(local))
|
||||
self.elements().filter(move |e| e.local() == local)
|
||||
}
|
||||
/// Follow a chain of child local names.
|
||||
pub fn path(&self, names: &[&str]) -> Option<&El> {
|
||||
let mut cur = self;
|
||||
for n in names {
|
||||
cur = cur.child(n)?;
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
/// First descendant (depth-first, bounded) with this local name.
|
||||
pub fn find(&self, local: &str) -> Option<&El> {
|
||||
fn rec<'a>(e: &'a El, local: &str, depth: usize) -> Option<&'a El> {
|
||||
if depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
for c in e.elements() {
|
||||
if c.is(local) {
|
||||
return Some(c);
|
||||
}
|
||||
if let Some(f) = rec(c, local, depth + 1) {
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
rec(self, local, 0)
|
||||
}
|
||||
/// All descendants with this local name (bounded depth).
|
||||
pub fn find_all<'a>(&'a self, local: &str, out: &mut Vec<&'a El>) {
|
||||
fn rec<'a>(e: &'a El, local: &str, depth: usize, out: &mut Vec<&'a El>) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in e.elements() {
|
||||
if c.is(local) {
|
||||
out.push(c);
|
||||
}
|
||||
rec(c, local, depth + 1, out);
|
||||
}
|
||||
}
|
||||
rec(self, local, 0, out)
|
||||
}
|
||||
/// Concatenated text content of this element and its descendants.
|
||||
pub fn text(&self) -> String {
|
||||
let mut s = String::new();
|
||||
fn rec(e: &El, s: &mut String, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in &e.children {
|
||||
match c {
|
||||
Node::Text(t) => s.push_str(t),
|
||||
Node::El(e) => rec(e, s, depth + 1),
|
||||
}
|
||||
}
|
||||
}
|
||||
rec(self, &mut s, 0);
|
||||
s
|
||||
}
|
||||
/// Value of `<x val="…"/>` child.
|
||||
pub fn child_val(&self, local: &str) -> Option<&str> {
|
||||
self.child(local).and_then(|c| c.attr("val"))
|
||||
}
|
||||
/// Serialize to a string (no XML declaration).
|
||||
pub fn to_xml(&self) -> String {
|
||||
let mut s = String::new();
|
||||
write_el(self, &mut s, 0);
|
||||
s
|
||||
|
||||
pub fn path(&self, path: &[&str]) -> Option<&El> {
|
||||
path.iter().try_fold(self, |cur, name| cur.child(name))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_el(e: &El, s: &mut String, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
s.push('<');
|
||||
s.push_str(&e.name);
|
||||
for (k, v) in &e.attrs {
|
||||
let _ = write!(s, " {}=\"{}\"", k, esc_attr(v));
|
||||
}
|
||||
if e.children.is_empty() {
|
||||
s.push_str("/>");
|
||||
return;
|
||||
}
|
||||
s.push('>');
|
||||
for c in &e.children {
|
||||
match c {
|
||||
Node::Text(t) => s.push_str(&esc(t)),
|
||||
Node::El(c) => write_el(c, s, depth + 1),
|
||||
}
|
||||
}
|
||||
s.push_str("</");
|
||||
s.push_str(&e.name);
|
||||
s.push('>');
|
||||
}
|
||||
|
||||
/// A parsed document: its root element and the namespace declarations on the root.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Doc {
|
||||
pub root: El,
|
||||
}
|
||||
|
||||
impl Doc {
|
||||
/// Namespace declarations (`xmlns:x`, `xmlns`) on the root element.
|
||||
pub fn ns_decls(&self) -> Vec<(String, String)> {
|
||||
self.root.attrs.iter().filter(|(k, _)| k == "xmlns" || k.starts_with("xmlns:")).cloned().collect()
|
||||
}
|
||||
fn from_craft_el(el: craft_xml::El) -> El {
|
||||
let children = el
|
||||
.children
|
||||
.into_iter()
|
||||
.filter_map(|n| match n {
|
||||
craft_xml::Node::El(c) => Some(Node::El(from_craft_el(c))),
|
||||
craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => Some(Node::Text(t)),
|
||||
craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => None,
|
||||
})
|
||||
.collect();
|
||||
El { name: el.name, attrs: el.attrs, children }
|
||||
}
|
||||
|
||||
/// Parse XML bytes into a DOM. Bounded depth and node count; entity references are resolved.
|
||||
pub fn parse(bytes: &[u8]) -> Result<Doc, PptxError> {
|
||||
// Skip a UTF-8 BOM; UTF-16 parts (rare) are decoded first.
|
||||
let owned;
|
||||
let bytes = if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
|
||||
owned = decode_utf16(bytes);
|
||||
owned.as_bytes()
|
||||
} else {
|
||||
bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes)
|
||||
};
|
||||
let mut reader = quick_xml::Reader::from_reader(bytes);
|
||||
{
|
||||
let c = reader.config_mut();
|
||||
c.trim_text(false);
|
||||
c.check_end_names = false;
|
||||
c.allow_unmatched_ends = true;
|
||||
c.expand_empty_elements = false;
|
||||
}
|
||||
let mut stack: Vec<El> = vec![];
|
||||
let mut root: Option<El> = None;
|
||||
let mut nodes = 0usize;
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let ev = reader.read_event_into(&mut buf).map_err(|e| PptxError::Xml(format!("{e}")))?;
|
||||
match ev {
|
||||
Event::Start(b) | Event::Empty(b) if root.is_some() => {
|
||||
// Content after the root element: ignore.
|
||||
let _ = b;
|
||||
}
|
||||
Event::Start(b) => {
|
||||
nodes += 1;
|
||||
if nodes > MAX_NODES || stack.len() >= MAX_DEPTH {
|
||||
return Err(PptxError::Xml("document too large or too deeply nested".into()));
|
||||
}
|
||||
stack.push(start_el(&b, &reader));
|
||||
}
|
||||
Event::Empty(b) => {
|
||||
nodes += 1;
|
||||
if nodes > MAX_NODES {
|
||||
return Err(PptxError::Xml("document too large".into()));
|
||||
}
|
||||
let el = start_el(&b, &reader);
|
||||
match stack.last_mut() {
|
||||
Some(p) => p.children.push(Node::El(el)),
|
||||
None => root = Some(el),
|
||||
}
|
||||
}
|
||||
Event::End(_) => {
|
||||
if let Some(el) = stack.pop() {
|
||||
match stack.last_mut() {
|
||||
Some(p) => p.children.push(Node::El(el)),
|
||||
None => root = Some(el),
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Text(t) => {
|
||||
if let Some(p) = stack.last_mut() {
|
||||
let s = t.decode().map(|c| c.into_owned()).unwrap_or_default();
|
||||
push_text(p, &line_ends(s));
|
||||
}
|
||||
}
|
||||
Event::CData(t) => {
|
||||
if let Some(p) = stack.last_mut() {
|
||||
let s = String::from_utf8_lossy(&t).into_owned();
|
||||
push_text(p, &line_ends(s));
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) => {
|
||||
if let Some(p) = stack.last_mut() {
|
||||
let s = if r.is_char_ref() {
|
||||
r.resolve_char_ref().ok().flatten().map(String::from).unwrap_or_default()
|
||||
} else {
|
||||
match r.decode().map(|c| c.into_owned()).unwrap_or_default().as_str() {
|
||||
"amp" => "&".into(),
|
||||
"lt" => "<".into(),
|
||||
"gt" => ">".into(),
|
||||
"quot" => "\"".into(),
|
||||
"apos" => "'".into(),
|
||||
_ => String::new(),
|
||||
}
|
||||
};
|
||||
push_text(p, &s);
|
||||
}
|
||||
}
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
buf.clear();
|
||||
}
|
||||
// Unclosed elements (truncated document): fold them up so partial content is still usable.
|
||||
while let Some(el) = stack.pop() {
|
||||
match stack.last_mut() {
|
||||
Some(p) => p.children.push(Node::El(el)),
|
||||
None => root = Some(el),
|
||||
}
|
||||
}
|
||||
let root = root.ok_or_else(|| PptxError::Xml("no root element".into()))?;
|
||||
Ok(Doc { root })
|
||||
}
|
||||
|
||||
/// XML 1.0 §2.11: a literal CR LF or lone CR in the document reads as LF. A ` ` reference is
|
||||
/// not literal and reaches `push_text` through `GeneralRef`, so it stays a CR.
|
||||
fn line_ends(s: String) -> String {
|
||||
if s.contains('\r') { s.replace("\r\n", "\n").replace('\r', "\n") } else { s }
|
||||
}
|
||||
|
||||
fn push_text(p: &mut El, s: &str) {
|
||||
if s.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Some(Node::Text(t)) = p.children.last_mut() {
|
||||
t.push_str(s);
|
||||
} else {
|
||||
p.children.push(Node::Text(s.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
fn start_el(b: &quick_xml::events::BytesStart, reader: &quick_xml::Reader<&[u8]>) -> El {
|
||||
let name = String::from_utf8_lossy(b.name().as_ref()).into_owned();
|
||||
let mut attrs = vec![];
|
||||
for a in b.attributes().with_checks(false).flatten() {
|
||||
let k = String::from_utf8_lossy(a.key.as_ref()).into_owned();
|
||||
let v = a
|
||||
.decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder())
|
||||
.map(|c| c.into_owned())
|
||||
.unwrap_or_else(|_| String::from_utf8_lossy(&a.value).into_owned());
|
||||
attrs.push((k, v));
|
||||
}
|
||||
El { name, attrs, children: vec![] }
|
||||
}
|
||||
|
||||
fn decode_utf16(bytes: &[u8]) -> String {
|
||||
let le = bytes.starts_with(&[0xFF, 0xFE]);
|
||||
let units: Vec<u16> =
|
||||
bytes.get(2..).unwrap_or(&[]).as_chunks::<2>().0.iter().map(|c| if le { u16::from_le_bytes(*c) } else { u16::from_be_bytes(*c) }).collect();
|
||||
let s = String::from_utf16_lossy(&units);
|
||||
// Drop the encoding declaration so quick-xml reads it as UTF-8.
|
||||
match s.strip_prefix("<?xml").and_then(|r| r.find("?>").map(|i| i + 7)) {
|
||||
Some(end) => s.get(end..).unwrap_or("").to_string(),
|
||||
None => s,
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve the public writer helpers while sharing the XML 1.0 escaping rules.
|
||||
pub use craft_xml::{esc, esc_attr};
|
||||
|
||||
/// A string builder for XML parts.
|
||||
#[derive(Default)]
|
||||
pub struct W {
|
||||
pub s: String,
|
||||
}
|
||||
|
||||
/// Attribute list builder.
|
||||
#[derive(Default)]
|
||||
pub struct A {
|
||||
pub v: Vec<(&'static str, String)>,
|
||||
}
|
||||
|
||||
impl A {
|
||||
pub fn new() -> Self {
|
||||
A { v: vec![] }
|
||||
}
|
||||
pub fn a(mut self, k: &'static str, v: impl ToString) -> Self {
|
||||
self.v.push((k, v.to_string()));
|
||||
self
|
||||
}
|
||||
pub fn o<T: ToString>(mut self, k: &'static str, v: Option<T>) -> Self {
|
||||
if let Some(v) = v {
|
||||
self.v.push((k, v.to_string()));
|
||||
}
|
||||
self
|
||||
}
|
||||
/// Boolean attribute written as `1`/`0` when `Some`.
|
||||
pub fn b(mut self, k: &'static str, v: Option<bool>) -> Self {
|
||||
if let Some(v) = v {
|
||||
self.v.push((k, if v { "1" } else { "0" }.to_string()));
|
||||
}
|
||||
self
|
||||
}
|
||||
/// Boolean attribute written only when true.
|
||||
pub fn t(mut self, k: &'static str, v: bool) -> Self {
|
||||
if v {
|
||||
self.v.push((k, "1".to_string()));
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl W {
|
||||
pub fn new() -> Self {
|
||||
W { s: String::from("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n") }
|
||||
}
|
||||
pub fn frag() -> Self {
|
||||
W { s: String::new() }
|
||||
}
|
||||
fn attrs(&mut self, a: &A) {
|
||||
for (k, v) in &a.v {
|
||||
let _ = write!(self.s, " {}=\"{}\"", k, esc_attr(v));
|
||||
}
|
||||
}
|
||||
pub fn open(&mut self, name: &str, a: A) {
|
||||
self.s.push('<');
|
||||
self.s.push_str(name);
|
||||
self.attrs(&a);
|
||||
self.s.push('>');
|
||||
}
|
||||
pub fn open0(&mut self, name: &str) {
|
||||
self.s.push('<');
|
||||
self.s.push_str(name);
|
||||
self.s.push('>');
|
||||
}
|
||||
pub fn close(&mut self, name: &str) {
|
||||
self.s.push_str("</");
|
||||
self.s.push_str(name);
|
||||
self.s.push('>');
|
||||
}
|
||||
pub fn empty(&mut self, name: &str, a: A) {
|
||||
self.s.push('<');
|
||||
self.s.push_str(name);
|
||||
self.attrs(&a);
|
||||
self.s.push_str("/>");
|
||||
}
|
||||
pub fn empty0(&mut self, name: &str) {
|
||||
self.s.push('<');
|
||||
self.s.push_str(name);
|
||||
self.s.push_str("/>");
|
||||
}
|
||||
/// `<name val="v"/>`
|
||||
pub fn val(&mut self, name: &str, v: impl ToString) {
|
||||
self.empty(name, A::new().a("val", v));
|
||||
}
|
||||
pub fn text(&mut self, t: &str) {
|
||||
self.s.push_str(&esc(t));
|
||||
}
|
||||
/// `<name>text</name>`
|
||||
pub fn elt(&mut self, name: &str, t: &str) {
|
||||
self.open0(name);
|
||||
self.text(t);
|
||||
self.close(name);
|
||||
}
|
||||
pub fn raw(&mut self, xml: &str) {
|
||||
self.s.push_str(xml);
|
||||
}
|
||||
pub fn finish(self) -> Vec<u8> {
|
||||
self.s.into_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn literal_cr_lf_and_lone_cr_read_as_lf_but_char_ref_stays() {
|
||||
let d = parse(b"<a:p><a:t>one\r\ntwo\rthree four</a:t><a:t><![CDATA[x\r\ny]]></a:t></a:p>").expect("parse");
|
||||
let t: Vec<String> = d.root.children_named("t").map(|t| t.text()).collect();
|
||||
assert_eq!(t, vec!["one\ntwo\nthree\rfour".to_string(), "x\ny".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cr_in_text_survives_write_read() {
|
||||
assert_eq!(esc("a\rb"), "a b");
|
||||
let mut w = W::default();
|
||||
w.elt("a:t", "one\rtwo\r\nthree");
|
||||
let d = parse(w.s.as_bytes()).expect("parse");
|
||||
assert_eq!(d.root.text(), "one\rtwo\r\nthree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_basic_and_entities() {
|
||||
let d = parse(b"<?xml version=\"1.0\"?><a:p xmlns:a=\"x\"><a:r><a:t>A & B A <</a:t></a:r><a:x r:id=\"rId1\" id=\"5\"/></a:p>")
|
||||
.unwrap();
|
||||
assert_eq!(d.root.local(), "p");
|
||||
assert_eq!(d.root.find("t").map(|t| t.text()), Some("A & B A <".to_string()));
|
||||
let x = d.root.child("x").unwrap();
|
||||
assert_eq!(x.attr("id"), Some("5"));
|
||||
assert_eq!(x.attr("r:id"), Some("rId1"));
|
||||
assert_eq!(d.ns_decls().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_garbage() {
|
||||
assert!(parse(b"<a><b><c>text").is_ok());
|
||||
assert!(parse(b"").is_err());
|
||||
let deep = "<a>".repeat(MAX_DEPTH + 10);
|
||||
assert!(parse(deep.as_bytes()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_drops_control_chars() {
|
||||
assert_eq!(esc("a\u{b}b<\u{0}"), "ab<");
|
||||
assert_eq!(esc_attr("\"x\"\n"), ""x" ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_escaping_preserves_xml_wire_bytes() {
|
||||
let text = "&<>\"'\t\n\r\0\u{b}\u{fffe}\u{ffff}é😀 ";
|
||||
assert_eq!(esc(text), "&<>\"'\t\n é😀&#13;");
|
||||
assert_eq!(esc_attr(text), "&<>"'	 é😀&#13;");
|
||||
assert_eq!(esc(""), "");
|
||||
assert_eq!(esc_attr(""), "");
|
||||
for code in 0..32 {
|
||||
let c = char::from_u32(code).unwrap();
|
||||
let text = c.to_string();
|
||||
match c {
|
||||
'\t' => {
|
||||
assert_eq!(esc(&text), "\t");
|
||||
assert_eq!(esc_attr(&text), "	");
|
||||
}
|
||||
'\n' => {
|
||||
assert_eq!(esc(&text), "\n");
|
||||
assert_eq!(esc_attr(&text), " ");
|
||||
}
|
||||
'\r' => {
|
||||
assert_eq!(esc(&text), " ");
|
||||
assert_eq!(esc_attr(&text), " ");
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(esc(&text), "");
|
||||
assert_eq!(esc_attr(&text), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_serialize() {
|
||||
let d = parse(b"<p:sp a=\"1\"><p:t>x & y</p:t><e/></p:sp>").unwrap();
|
||||
assert_eq!(d.root.to_xml(), "<p:sp a=\"1\"><p:t>x & y</p:t><e/></p:sp>");
|
||||
}
|
||||
let root = craft_drawingml::xmlx::parse(bytes).map_err(|e| PptxError::Xml(e.to_string()))?;
|
||||
Ok(Doc { root: from_craft_el(root) })
|
||||
}
|
||||
|
||||
@@ -444,3 +444,33 @@ fn a_shared_notes_part_is_read_once() {
|
||||
assert_eq!(q.slides[0].notes.text(), "notes 0");
|
||||
assert!(q.slides[1..].iter().all(|s| s.notes.text().is_empty()), "a shared notes part is not copied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_master_and_handout_master_shape_count_bounds() {
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
let mut p = defaults::new_presentation(None);
|
||||
Arc::make_mut(&mut p.slides[0]).notes = deckcraft_model::text::TextBody::from_text("note");
|
||||
p.handout_master = Some(Arc::new(deckcraft_model::Master { name: "Handouts".into(), ..Default::default() }));
|
||||
let mut es = entries(&deckcraft_pptx::export(&p).expect("export"));
|
||||
let mut many = String::new();
|
||||
for i in 2..=20_050 {
|
||||
let _ = write!(many, r#"<p:sp><p:nvSpPr><p:cNvPr id="{i}" name="S{i}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr/></p:sp>"#);
|
||||
}
|
||||
for (n, d) in es.iter_mut() {
|
||||
if n == "ppt/notesMasters/notesMaster1.xml" || n == "ppt/handoutMasters/handoutMaster1.xml" {
|
||||
let xml = String::from_utf8(d.clone()).expect("utf8");
|
||||
if let Some(pos) = xml.rfind("</p:spTree>") {
|
||||
let mut patched = String::with_capacity(xml.len() + many.len());
|
||||
patched.push_str(&xml[..pos]);
|
||||
patched.push_str(&many);
|
||||
patched.push_str(&xml[pos..]);
|
||||
*d = patched.into_bytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
let q = deckcraft_pptx::import(&rezip(&es)).expect("bounded import");
|
||||
assert_eq!(q.notes_master.as_ref().expect("notes_master").shapes.len(), 20_000);
|
||||
assert_eq!(q.handout_master.as_ref().expect("handout_master").shapes.len(), 20_000);
|
||||
deckcraft_pptx::export(&q).expect("re-export");
|
||||
}
|
||||
|
||||
@@ -2347,3 +2347,62 @@ fn reflection_angles_and_skews_out_of_range_are_written_inside_the_schema() {
|
||||
let r = round(&p).slides.last().and_then(|sl| by_name(sl, "Reflected").effects.clone()).and_then(|fx| fx.reflection).expect("reflection");
|
||||
assert_eq!((r.st_pos, r.dir, r.fade_dir, r.kx, r.ky), (Some(100_000), Some(21_599_995), Some(0), Some(5_399_999), Some(-5_399_999)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pptx_potx_ppsx_export_parity_preserves_masters_charts_themes_and_timing() {
|
||||
let mut p = rich_deck();
|
||||
let m0 = Arc::make_mut(&mut p.masters[0]);
|
||||
m0.theme.name = "ParityTheme".into();
|
||||
m0.theme.colors.set(deckcraft_color::SchemeSlot::Accent1, deckcraft_color::Rgba::rgb(0x11, 0x22, 0x33));
|
||||
p.notes_master = Some(Arc::new(deckcraft_model::Master { name: "NotesParity".into(), ..Default::default() }));
|
||||
p.handout_master = Some(Arc::new(deckcraft_model::Master { name: "HandoutParity".into(), ..Default::default() }));
|
||||
|
||||
let audio = p.add_media("cue.m4a", "audio/mp4", b"audio-bytes".to_vec()).expect("media");
|
||||
let aud_id = ShapeId(p.alloc_id().expect("id"));
|
||||
Arc::make_mut(&mut p.slides[0]).shapes.push(Shape {
|
||||
id: aud_id,
|
||||
name: "Cue".into(),
|
||||
xfrm: Some(Xfrm::new(20.0, 20.0, 40.0, 40.0)),
|
||||
kind: ShapeKind::Media(deckcraft_model::MediaClip {
|
||||
media: audio,
|
||||
video: false,
|
||||
autoplay: true,
|
||||
loop_play: true,
|
||||
volume: 0.5,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let edited_values = vec![Some(111.5), Some(222.25), Some(333.75), Some(444.0)];
|
||||
let chart_slide_idx = p.slides.iter().position(|sl| sl.shapes.iter().any(|s| s.name == "Chart 0")).expect("chart slide");
|
||||
{
|
||||
let ch_shape = Arc::make_mut(&mut p.slides[chart_slide_idx]).shapes.iter_mut().find(|s| s.name == "Chart 0").expect("Chart 0");
|
||||
ch_shape.name = "Revenue Chart".into();
|
||||
let ShapeKind::Chart(ch) = &mut ch_shape.kind else { panic!("expected chart") };
|
||||
ch.series[0].values = edited_values.clone();
|
||||
}
|
||||
|
||||
for (ext, expected_ct) in [
|
||||
("pptx", "presentationml.presentation.main+xml"),
|
||||
("potx", "presentationml.template.main+xml"),
|
||||
("POTX", "presentationml.template.main+xml"),
|
||||
(".ppsx", "presentationml.slideshow.main+xml"),
|
||||
] {
|
||||
let bytes = deckcraft_pptx::export_as(&p, ext).expect("export_as");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).expect("zip");
|
||||
let ct = std::io::read_to_string(z.by_name("[Content_Types].xml").expect("content types")).expect("read");
|
||||
assert!(ct.contains(expected_ct), "{ext}: {ct}");
|
||||
let reopened = deckcraft_pptx::import(&bytes).expect("reopen");
|
||||
assert_eq!(reopened.masters[0].theme.name, "ParityTheme");
|
||||
assert_eq!(reopened.masters[0].theme.colors.get(deckcraft_color::SchemeSlot::Accent1), deckcraft_color::Rgba::rgb(0x11, 0x22, 0x33));
|
||||
assert!(reopened.notes_master.is_some());
|
||||
assert_eq!(reopened.handout_master.as_ref().map(|m| m.name.as_str()), Some("HandoutParity"));
|
||||
let cue = reopened.slides[0].shapes.iter().find(|s| s.name == "Cue").expect("cue");
|
||||
let ShapeKind::Media(clip) = &cue.kind else { panic!("expected media") };
|
||||
assert!(clip.autoplay && clip.loop_play && (clip.volume - 0.5).abs() < 1e-3);
|
||||
let chart_shape = reopened.slides[chart_slide_idx].shapes.iter().find(|s| s.name == "Revenue Chart").expect("named chart");
|
||||
let ShapeKind::Chart(chart) = &chart_shape.kind else { panic!("expected chart") };
|
||||
assert_eq!(chart.series[0].values, edited_values, "{ext}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3404,3 +3404,65 @@ fn a_shape_whose_outline_is_not_finite_is_not_drawable() {
|
||||
quad.paths[0].path = path;
|
||||
assert!(!crate::geometry::drawable(&quad, m, 100.0, 50.0));
|
||||
}
|
||||
|
||||
/// A WMF without a placeable header (the frame comes from its window records) holding `records`
|
||||
/// (function, parameter bytes).
|
||||
fn wmf_bare(records: &[(u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut body = Vec::new();
|
||||
let mut max_words = 3u32;
|
||||
for (func, params) in records {
|
||||
let words = (6 + params.len() as u32).div_ceil(2);
|
||||
max_words = max_words.max(words);
|
||||
body.extend(words.to_le_bytes());
|
||||
body.extend(func.to_le_bytes());
|
||||
body.extend(params);
|
||||
if params.len() % 2 == 1 {
|
||||
body.push(0);
|
||||
}
|
||||
}
|
||||
body.extend([3, 0, 0, 0, 0, 0]);
|
||||
let mut f = Vec::new();
|
||||
for v in [1u16, 9, 0x300] {
|
||||
f.extend(v.to_le_bytes());
|
||||
}
|
||||
f.extend((((18 + body.len()) / 2) as u32).to_le_bytes());
|
||||
f.extend(1u16.to_le_bytes());
|
||||
f.extend(max_words.to_le_bytes());
|
||||
f.extend(0u16.to_le_bytes());
|
||||
f.extend(body);
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_scaled_viewport_places_each_sub_picture_in_its_half() {
|
||||
// #2069: an 800 × 400 frame drawn as two sub-pictures. Each saves the DC, halves the viewport
|
||||
// width with SCALEVIEWPORTEXT, sets its own 400 × 400 window (the second shifted right by its
|
||||
// window origin), draws a circle and restores the DC: red on the left, blue on the right.
|
||||
let sub = |origin_x: i32, colorref: u32| {
|
||||
let mut brush = 0u16.to_le_bytes().to_vec();
|
||||
brush.extend(colorref.to_le_bytes());
|
||||
brush.extend(0u16.to_le_bytes());
|
||||
vec![
|
||||
(0x001E, vec![]), // SAVEDC
|
||||
(0x0103, i16s(&[8])), // SETMAPMODE MM_ANISOTROPIC
|
||||
(0x0412, i16s(&[1, 1, 2, 1])), // SCALEVIEWPORTEXT y 1/1, x 1/2
|
||||
(0x020B, i16s(&[0, origin_x])), // SETWINDOWORG
|
||||
(0x020C, i16s(&[400, 400])), // SETWINDOWEXT
|
||||
(0x02FC, brush), // CREATEBRUSHINDIRECT
|
||||
(0x012D, i16s(&[0])), // SELECTOBJECT
|
||||
(0x0418, i16s(&[380, 380, 20, 20])), // ELLIPSE
|
||||
(0x0127, i16s(&[-1])), // RESTOREDC
|
||||
(0x01F0, i16s(&[0])), // DELETEOBJECT
|
||||
]
|
||||
};
|
||||
let mut recs = vec![(0x020B, i16s(&[0, 0])), (0x020C, i16s(&[400, 800]))];
|
||||
recs.extend(sub(0, 0x0000_00FF));
|
||||
recs.extend(sub(-400, 0x00FF_0000));
|
||||
let img = crate::metafile::rasterize(&wmf_bare(&recs), 200).expect("raster");
|
||||
assert_eq!(img.dimensions(), (200, 100));
|
||||
let red = |p: &image::Rgba<u8>| p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200;
|
||||
let blue = |p: &image::Rgba<u8>| p[2] > 200 && p[0] < 60 && p[1] < 60 && p[3] > 200;
|
||||
assert!(red(img.get_pixel(50, 50)), "red circle in the left half: {:?}", img.get_pixel(50, 50));
|
||||
assert!(blue(img.get_pixel(150, 50)), "blue circle in the right half: {:?}", img.get_pixel(150, 50));
|
||||
assert!(img.get_pixel(100, 50)[3] < 128, "the circles don't meet in the middle: {:?}", img.get_pixel(100, 50));
|
||||
}
|
||||
|
||||
@@ -12,6 +12,36 @@ use std::fmt::Write as _;
|
||||
use serde_json::Value;
|
||||
|
||||
fn main() {
|
||||
// The compiled channel and the version the binary was built as. The desktop crate's build
|
||||
// script reads the same two variables, so the About dialog, the window name and the version
|
||||
// query agree in one build.
|
||||
println!("cargo::rerun-if-env-changed=DECKCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo::rerun-if-env-changed=DECKCRAFT_VERSION");
|
||||
println!("cargo::rustc-check-cfg=cfg(deckcraft_nightly_v1)");
|
||||
let nightly = match std::env::var("DECKCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo::rustc-cfg=deckcraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
println!("cargo::error=unsupported DECKCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let version = if nightly {
|
||||
match std::env::var("DECKCRAFT_VERSION") {
|
||||
Ok(version) if version.contains("-nightly.") => version,
|
||||
_ => {
|
||||
println!("cargo::error=nightly-v1 requires an explicit DECKCRAFT_VERSION feed identity");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo::rustc-env=DECKCRAFT_BUILT_VERSION={version}");
|
||||
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contributors");
|
||||
let json = read(&dir.join("contributors.json"), "the About window shows no contributors", |t| {
|
||||
serde_json::from_str::<Value>(t).map_err(|e| e.to_string())
|
||||
|
||||
@@ -140,7 +140,7 @@ impl SlideApp {
|
||||
|
||||
/// Start the helper of an update that is ready, so that it installs once the process has
|
||||
/// exited. The desktop shell calls it in `on_exit`, which ends the process on macOS before the
|
||||
/// app is dropped. Later calls do nothing.
|
||||
/// app is dropped. Later calls do nothing, and a Nightly launch never starts a stable update.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn start_pending_update(&mut self) {
|
||||
updates_ui::start_pending_update(self);
|
||||
|
||||
@@ -227,8 +227,9 @@ impl SlideApp {
|
||||
}
|
||||
"app.about" => self.dialog = Some(dialogs::Dialog::new("about")),
|
||||
"app.checkUpdates" => {
|
||||
// Nightly is updated by ArtCraft Launcher; its stable updater must stay idle.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::request_check(self);
|
||||
updates_ui::request_check(self)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return Err("updates are handled by the browser: reload the page".into());
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ pub fn about(_app: &mut SlideApp, ui: &mut Ui) {
|
||||
ui.vertical_centered(|ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(64.0, 64.0), Sense::hover());
|
||||
paint_logo(ui.painter(), r);
|
||||
ui.label(egui::RichText::new("DeckCraft").font(theme::bold(22.0)));
|
||||
ui.label(egui::RichText::new(crate::flavor::app_name()).font(theme::bold(22.0)));
|
||||
ui.label(egui::RichText::new(version_line()).color(t.text_dim));
|
||||
ui.add_space(6.0);
|
||||
ui.label("Presentations and slide shows, rebuilt from scratch in pure Rust.");
|
||||
@@ -38,7 +38,7 @@ pub fn about(_app: &mut SlideApp, ui: &mut Ui) {
|
||||
/// from `[workspace.package] version` (the single source of truth, `cargo xtask version`); the
|
||||
/// release workflow sets `DECKCRAFT_BUILD_SHA` / `DECKCRAFT_BUILD_DATE` at build time.
|
||||
pub fn version_line() -> String {
|
||||
let mut s = format!("Version {}", env!("CARGO_PKG_VERSION"));
|
||||
let mut s = format!("Version {}", crate::flavor::version());
|
||||
let sha = option_env!("DECKCRAFT_BUILD_SHA").map(|s| s.get(..9).unwrap_or(s)).filter(|s| !s.is_empty());
|
||||
let date = option_env!("DECKCRAFT_BUILD_DATE").filter(|s| !s.is_empty());
|
||||
match (sha, date) {
|
||||
|
||||
@@ -8,16 +8,28 @@ use crate::SlideApp;
|
||||
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// What Help > Check for Updates… answers in Nightly, which ArtCraft Launcher updates.
|
||||
pub(crate) const NIGHTLY_UPDATES: &str = "DeckCraft Nightly is updated by ArtCraft Launcher";
|
||||
|
||||
pub(crate) struct Runtime {
|
||||
updater: Updater,
|
||||
/// The desktop host turns the check at start on; tests and the web build leave it off.
|
||||
enabled: bool,
|
||||
check_requested: bool,
|
||||
/// The stable self-updater (its feed, cache and records under Stable's folders) is a stable
|
||||
/// service only. The launch identity is read once, when the UI state is built, so every entry
|
||||
/// point below agrees and no test can reselect the process-wide identity.
|
||||
stable_services: bool,
|
||||
}
|
||||
|
||||
impl Default for Runtime {
|
||||
fn default() -> Self {
|
||||
Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false }
|
||||
Self {
|
||||
updater: Updater::new(&crate::UPDATE_APP, VERSION),
|
||||
enabled: false,
|
||||
check_requested: false,
|
||||
stable_services: crate::os_window::stable_services_allowed(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,21 +37,31 @@ pub(crate) fn enable(app: &mut SlideApp) {
|
||||
app.updates_rt.enabled = true;
|
||||
}
|
||||
|
||||
/// Help > Check for Updates…: runs a check and reports the outcome either way.
|
||||
pub(crate) fn request_check(app: &mut SlideApp) {
|
||||
/// Help > Check for Updates…: runs a check and reports the outcome either way. Nightly has no
|
||||
/// update check of its own (the Launcher owns the install) and never touches Stable's updater.
|
||||
pub(crate) fn request_check(app: &mut SlideApp) -> Result<(), String> {
|
||||
if !app.updates_rt.stable_services {
|
||||
return Err(NIGHTLY_UPDATES.into());
|
||||
}
|
||||
if !matches!(app.updates_rt.updater.status(), Status::Checking) {
|
||||
app.updates_rt.check_requested = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts the helper of an update that is ready, so that it installs once the process has exited.
|
||||
/// Later calls do nothing.
|
||||
/// Later calls do nothing; Nightly has no ready stable update to start.
|
||||
pub(crate) fn start_pending_update(app: &mut SlideApp) {
|
||||
app.updates_rt.updater.start_pending_update();
|
||||
if app.updates_rt.stable_services {
|
||||
app.updates_rt.updater.start_pending_update();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn tick(app: &mut SlideApp, ctx: &egui::Context) {
|
||||
let rt = &mut app.updates_rt;
|
||||
if !rt.stable_services {
|
||||
return;
|
||||
}
|
||||
if std::mem::take(&mut rt.check_requested) {
|
||||
rt.updater.check_now(ctx);
|
||||
} else if rt.enabled {
|
||||
@@ -49,6 +71,9 @@ pub(crate) fn tick(app: &mut SlideApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
pub(crate) fn show(app: &mut SlideApp, ctx: &egui::Context) {
|
||||
if !app.updates_rt.stable_services {
|
||||
return;
|
||||
}
|
||||
// An installation starts, and a ready update asks the app to close, only while nothing is unsaved.
|
||||
let clean = !app.session.documents().iter().any(|d| d.is_dirty());
|
||||
match app.updates_rt.updater.show_if(ctx, clean) {
|
||||
@@ -103,6 +128,33 @@ mod tests {
|
||||
app
|
||||
}
|
||||
|
||||
/// Nightly is updated by ArtCraft Launcher: the stable feed, its cache and its records (all
|
||||
/// under Stable's folders) stay untouched, and Help > Check for Updates… says so.
|
||||
#[test]
|
||||
fn a_nightly_launch_never_starts_the_stable_updater() {
|
||||
let mut app = SlideApp::new(deckcraft_engine::Session::new(), crate::Services::default());
|
||||
assert!(app.updates_rt.stable_services, "the test binary is a stable launch");
|
||||
app.updates_rt.stable_services = false;
|
||||
assert_eq!(request_check(&mut app), Err(NIGHTLY_UPDATES.to_string()));
|
||||
assert!(!app.updates_rt.check_requested, "a refused check must not be queued");
|
||||
start_pending_update(&mut app);
|
||||
let ctx = egui::Context::default();
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
tick(&mut app, ui.ctx());
|
||||
show(&mut app, ui.ctx());
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
assert_eq!(app.updates_rt.updater.status(), &Status::Idle, "Nightly never drives the updater");
|
||||
}
|
||||
|
||||
/// The identity is sampled when the UI state is built, so the answer cannot drift later.
|
||||
#[test]
|
||||
fn the_updater_reads_the_launch_identity_once() {
|
||||
assert_eq!(Runtime::default().stable_services, crate::os_window::stable_services_allowed());
|
||||
assert_eq!(crate::os_window::identity(), crate::os_window::LaunchIdentity::Stable);
|
||||
}
|
||||
|
||||
fn records_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-updates-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//! The compiled channel, shared by the About dialog and the window name. The build script sets
|
||||
//! `cfg(deckcraft_nightly_v1)` and `DECKCRAFT_BUILT_VERSION` from `DECKCRAFT_BUILD_CHANNEL`, the
|
||||
//! same switch the app crate's build script reads, so both crates agree in one build.
|
||||
|
||||
/// The display name: the same string the Launcher and the macOS bundle use.
|
||||
pub const fn app_name() -> &'static str {
|
||||
if is_nightly() { "DeckCraft Nightly" } else { "DeckCraft" }
|
||||
}
|
||||
|
||||
pub const fn is_nightly() -> bool {
|
||||
cfg!(deckcraft_nightly_v1)
|
||||
}
|
||||
|
||||
/// The version the binary was built as: the workspace version for stable, the prepared Nightly
|
||||
/// feed identity for Nightly (never the bare Cargo version).
|
||||
pub const fn version() -> &'static str {
|
||||
env!("DECKCRAFT_BUILT_VERSION")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn nightly_and_stable_names_match_the_build_channel() {
|
||||
assert_eq!(super::is_nightly(), cfg!(deckcraft_nightly_v1));
|
||||
assert_eq!(super::app_name(), if cfg!(deckcraft_nightly_v1) { "DeckCraft Nightly" } else { "DeckCraft" });
|
||||
assert!(super::version().starts_with(env!("CARGO_PKG_VERSION").split('-').next().unwrap_or_default()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nightly_build_never_reports_the_bare_workspace_version() {
|
||||
if cfg!(deckcraft_nightly_v1) {
|
||||
assert_ne!(super::version(), env!("CARGO_PKG_VERSION"));
|
||||
assert!(super::version().contains("-nightly."));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,10 +22,12 @@ pub mod control;
|
||||
pub mod dialogs;
|
||||
pub mod doc_window;
|
||||
pub mod eyedropper;
|
||||
pub mod flavor;
|
||||
pub mod icons;
|
||||
pub mod media;
|
||||
pub mod menus;
|
||||
pub mod opening;
|
||||
pub mod os_window;
|
||||
pub mod presenter;
|
||||
pub mod ribbon;
|
||||
pub mod settings;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! The app id every DeckCraft OS window carries, so docks show the DeckCraft icon on them and
|
||||
//! Wayland compositors' window rules can match them.
|
||||
|
||||
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
|
||||
pub const APP_ID: &str = "ai.storyteller.deckcraft";
|
||||
|
||||
/// Immutable startup identity. The desktop selects it before any UI service is created.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LaunchIdentity {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
|
||||
|
||||
pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> {
|
||||
let value = match identity {
|
||||
LaunchIdentity::Stable => 1,
|
||||
LaunchIdentity::NightlyV1 => 2,
|
||||
};
|
||||
IDENTITY
|
||||
.compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire)
|
||||
.map(|_| ())
|
||||
.map_err(|_| "the window launch identity was already selected".into())
|
||||
}
|
||||
|
||||
pub fn identity() -> LaunchIdentity {
|
||||
if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }
|
||||
}
|
||||
|
||||
pub const fn id_for(identity: LaunchIdentity) -> &'static str {
|
||||
match identity {
|
||||
LaunchIdentity::Stable => APP_ID,
|
||||
LaunchIdentity::NightlyV1 => "ai.storyteller.deckcraft.nightly-v1",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn app_id() -> &'static str {
|
||||
id_for(identity())
|
||||
}
|
||||
|
||||
pub const fn name_for(identity: LaunchIdentity) -> &'static str {
|
||||
match identity {
|
||||
LaunchIdentity::Stable => "DeckCraft",
|
||||
LaunchIdentity::NightlyV1 => "DeckCraft Nightly",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn stable_services_for(identity: LaunchIdentity) -> bool {
|
||||
matches!(identity, LaunchIdentity::Stable)
|
||||
}
|
||||
|
||||
pub fn stable_services_allowed() -> bool {
|
||||
stable_services_for(identity())
|
||||
}
|
||||
|
||||
/// A builder for an extra OS window, carrying the selected app id.
|
||||
pub fn builder() -> egui::ViewportBuilder {
|
||||
egui::ViewportBuilder::default().with_app_id(app_id())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn extra_windows_carry_the_app_id() {
|
||||
assert_eq!(builder().app_id.as_deref(), Some(APP_ID));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_identity_is_distinct_and_never_enables_stable_services() {
|
||||
assert_eq!(id_for(LaunchIdentity::Stable), APP_ID);
|
||||
assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID);
|
||||
assert_eq!(id_for(LaunchIdentity::NightlyV1), "ai.storyteller.deckcraft.nightly-v1");
|
||||
assert_eq!(name_for(LaunchIdentity::NightlyV1), "DeckCraft Nightly");
|
||||
assert!(stable_services_for(LaunchIdentity::Stable));
|
||||
assert!(!stable_services_for(LaunchIdentity::NightlyV1));
|
||||
}
|
||||
}
|
||||
@@ -73,4 +73,7 @@ pub struct Services {
|
||||
pub audio_out: Option<Box<dyn deckcraft_media::AudioOut>>,
|
||||
/// How many displays are connected, when the host can tell: Presenter View needs a second.
|
||||
pub displays: Option<Box<dyn FnMut() -> Option<usize>>>,
|
||||
/// Work that must finish on a clean quit. `eframe::App::on_exit` takes and runs it once: on
|
||||
/// macOS ⌘Q ends the process inside AppKit's terminate, so nothing after `run_native` runs.
|
||||
pub at_exit: Option<Box<dyn FnOnce()>>,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity with PowerPoint
|
||||
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-11 · **Change:** minor (empty notes slides are preserved on save and reopen, #2025; previous: minor, PowerPoint 97–2003 `.ppt`/`.pot`/`.pps` import; previous: trivial, a slide whose relationship is missing is reported in `lostSlides`; previous: minor (cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233))) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-20 · **Change:** trivial (WMF scale and offset mapping records place sub-pictures, #2069; previous: minor, empty notes slides are preserved on save and reopen, #2025; previous: minor, PowerPoint 97–2003 `.ppt`/`.pot`/`.pps` import; previous: trivial, a slide whose relationship is missing is reported in `lostSlides`; previous: minor (cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233))) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
|
||||
Every format PowerPoint reads or writes, DeckCraft's support, fidelity and how it is tested.
|
||||
Gaps are itemized in [gaps.md](gaps.md#file-formats). Dimension score: **~58% ready**
|
||||
@@ -54,7 +54,7 @@ intermediate build that required inline `bytes` cannot read the new referenced r
|
||||
|---|---|---|---|
|
||||
| PNG, JPEG, GIF (animated), BMP, TIFF, WebP | yes | yes | `image` 0.25; animated GIFs play since #39 |
|
||||
| SVG | yes (with PNG fallback) | **no** | The PNG fallback shows; SVG files can't be inserted |
|
||||
| EMF / WMF | yes | partial | Drawn as vectors (paths, pens, pattern and hatch brushes, bitmaps, text in the document's fonts with the file's character advances). Rectangle clip regions (`INTERSECTCLIPRECT`, `EXCLUDECLIPRECT`, `EXTSELECTCLIPRGN`) limit later drawing. EMF+ only pictures play every EMF+ drawing record (brushes incl. gradients and textures, pens, paths, curves, images, strings, transforms, clipping; see `crates/metafile/src/emfplus.rs` for the few exceptions). Legacy OLE objects (VML preview) and ActiveX controls show their pictures |
|
||||
| EMF / WMF | yes | partial | Drawn as vectors (paths, pens, pattern and hatch brushes, bitmaps, text in the document's fonts with the file's character advances). Rectangle clip regions (`INTERSECTCLIPRECT`, `EXCLUDECLIPRECT`, `EXTSELECTCLIPRGN`) limit later drawing. WMF scale and offset mapping records (`SCALEVIEWPORTEXT`, `SCALEWINDOWEXT`, `OFFSETVIEWPORTORG`, `OFFSETWINDOWORG`) place sub-pictures in their part of the frame (#2069). EMF+ only pictures play every EMF+ drawing record (brushes incl. gradients and textures, pens, paths, curves, images, strings, transforms, clipping; see `crates/metafile/src/emfplus.rs` for the few exceptions). Legacy OLE objects (VML preview) and ActiveX controls show their pictures |
|
||||
| HEIC | yes (macOS) | no | |
|
||||
| Audio: MP3, AAC/M4A, ALAC, WAV, AIFF, CAF, FLAC, Ogg Vorbis, Opus | yes (Ogg/Opus partly) | yes | Pure-Rust decoders in `crates/media`; Opus from craft-audio (craft-libs) |
|
||||
| WMA | yes (Windows) | embedded, not playable | |
|
||||
@@ -119,6 +119,7 @@ the round trip even though DeckCraft doesn't model it.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | trivial | WMF scale and offset mapping records place sub-pictures in their part of the frame: craft-metafile pinned past craft-libs #1816 (#2069) |
|
||||
| 2026-11-09 | minor | PowerPoint 97–2003 `.ppt`/`.pot`/`.pps` open (import only): masters, layouts from title masters, slides, text and styles, shapes, pictures, notes. Saving asks for a new name |
|
||||
| 2026-11-07 | trivial | A slide-list entry whose relationship is missing is reported in `lostSlides` like an unreadable slide part, so the deck opens as a repaired copy; slide lists over 10,000 entries are refused with an import-limit error rather than silently truncated (#1910) |
|
||||
| 2026-11-02 | minor | Optional table RTL direction is read and written as `a:tblPr/@rtl`; native and two PPTX saves preserve true, false and absent values with distinguishable column text |
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# Windows, Linux and macOS release-ref nightly: supervised manual go-live
|
||||
|
||||
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the
|
||||
signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed
|
||||
manual actors dispatches them. There is no schedule and no automatic dispatch transport yet. The installed
|
||||
policy [`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the real v3
|
||||
policy. Once `nightly.yml` lands on `main`, populate `producer_workflow_id` with its registration ID:
|
||||
|
||||
```bash
|
||||
gh api repos/storytold/deckcraft/actions/workflows/nightly.yml --jq .id
|
||||
```
|
||||
|
||||
The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation
|
||||
permissions are for its isolated attester; its compiler narrows to contents and Actions read
|
||||
only, with no OIDC, attestation write, release environment or platform signing secrets.
|
||||
Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions
|
||||
main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded
|
||||
lineage compares and an issue reread at the end of candidate admission) on top of
|
||||
[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input
|
||||
and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed
|
||||
source availability, not provider, queue, native signing or crypto qualification.
|
||||
Existing stable workflows are unchanged.
|
||||
|
||||
**The shared-workflow port is a prerequisite.** At this pin both reusable workflows admit only
|
||||
PhotoCraft: `nightly-unsigned.yml` requires `inputs.app-name == 'photocraft'` and
|
||||
`github.repository == 'storytold/photocraft'` on its build jobs, and `nightly-release.yml` requires the
|
||||
same repository in `validate` and every signing job (its concurrency group is
|
||||
`craft-release-ref-signer-photocraft`). A DeckCraft dispatch therefore builds and signs nothing until
|
||||
`storytold/craft-common-actions` admits `storytold/deckcraft`. No dispatch can produce a release before
|
||||
that port, and both callers' `uses`, `tooling-revision` and the policy pins must move to the same
|
||||
reviewed revision together.
|
||||
|
||||
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
|
||||
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that
|
||||
producer run ID and attempt, by a listed manual actor.
|
||||
|
||||
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
|
||||
producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers
|
||||
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes.
|
||||
|
||||
**Admission timing.** The candidate check reads the newest CI run on the candidate commit and
|
||||
main's latest finished Sonar analysis, so pick a quiet `main`, wait for its CI and SonarCloud analysis
|
||||
to finish green, then dispatch the producer and, once it succeeds, the signer, before another `main`
|
||||
push lands a newer analysis.
|
||||
|
||||
**Platform rows.** The producer caller lists
|
||||
`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer
|
||||
run builds every listed platform for one all-or-nothing release (one failed or skipped platform stops
|
||||
that night's release), and the release-ref signer admits platforms only from the protected policy, so
|
||||
there is no separate Linux or macOS caller job and the signer caller has no platform input.
|
||||
|
||||
## Installed policy values and their sources
|
||||
|
||||
Read on 2026-11-24; re-read anything that may have moved before the policy is promoted to `release`.
|
||||
|
||||
| Field | Value | Source |
|
||||
|---|---|---|
|
||||
| `repository_id` | `1408294296` | `gh api repos/storytold/deckcraft --jq .id` |
|
||||
| `producer_workflow_id` | `null` (populate after `nightly.yml` reaches `main`) | `gh api repos/storytold/deckcraft/actions/workflows/nightly.yml --jq .id` |
|
||||
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin |
|
||||
| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` |
|
||||
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
|
||||
| `platforms` | three rows | Storytold stable signing identities (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) |
|
||||
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `377160704`), 2 jobs | Workflow list API; jobs that succeeded on recent `main` push runs |
|
||||
| `candidate_policy.sonar` | `storytold` / `storytold_deckcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on `main` commits |
|
||||
| Sonar conditions | `new_security_rating` accepted (max 5); the other five required | Standard Storytold SonarCloud quality gate |
|
||||
| Sonar `issue_types` / `debt` | `VULNERABILITY` / `[]` | Update before promotion if any unresolved `main` vulnerabilities exist |
|
||||
|
||||
## Ownership and interface
|
||||
|
||||
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
|
||||
`DeckCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets
|
||||
may be passed or inherited.
|
||||
- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch,
|
||||
and identical on `main` and `release` after reviewed promotion. It rejects wrong repository/event/actual
|
||||
branch, including same-name tags. Its constant whole-run concurrency is distinct from stable,
|
||||
cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no
|
||||
credentials; only the shared callee's sign jobs bind the `release` environment.
|
||||
- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in
|
||||
`storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable
|
||||
commit**; the defining workflow SHA and tooling input must match.
|
||||
|
||||
## Local regression checks
|
||||
|
||||
`python3 packaging/nightly-release-tests.py` verifies the installed v3 policy, exact context guards
|
||||
on `nightly.yml` and `nightly-sign.yml`, manual actor alignment, platform list and trust anchors,
|
||||
shared tooling pin alignment, no-cache/no-platform-secret boundaries, and root concurrency
|
||||
serialization (`deckcraft-nightly-release`, `queue: max`, `cancel-in-progress: false`).
|
||||
@@ -1,6 +1,6 @@
|
||||
# DeckCraft vs Microsoft PowerPoint: parity assessment
|
||||
|
||||
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-02 · **Change:** trivial (reused slide contents fit the destination size; thumbnails remain; parity estimates unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-15 · **Change:** trivial (DeckCraft v0.19.0 version preparation; the SmartArt and WordArt display names become Diagram and Decorative Text in DeckCraft's own feature labels — commands, contextual tab labels and messages — with the neutral labels guarded by tests (the PowerPoint-matching empty-diagram placeholder prompt still reads "Click icon to add SmartArt graphic", and saved control-channel identifiers such as the tab id "SmartArt Design" keep their keys); the wasm32 build no longer refers to the native-only opening generation; the control-protocol method reference is corrected; previous: reused slide contents fit the destination size; thumbnails remain; parity estimates unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
|
||||
The authoritative answer to "how close is DeckCraft to PowerPoint, and how much work is left?".
|
||||
[ROADMAP.md](../ROADMAP.md) summarizes it; [gaps.md](gaps.md) itemizes every shortfall;
|
||||
@@ -288,6 +288,7 @@ scored done (16 open issues).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | trivial | DeckCraft v0.19.0 version preparation; the SmartArt and WordArt display names become Diagram and Decorative Text in DeckCraft's own labels (#1981; the PowerPoint-matching empty-placeholder prompt still reads "Click icon to add SmartArt graphic"); wasm32 build fix (#1954); control-protocol method reference corrected (#2132). Parity estimates unchanged, not re-measured |
|
||||
| 2026-11-02 | trivial | Reused slide content scales to the destination; picker thumbnails remain; parity estimates unchanged |
|
||||
| 2026-10-22 | trivial | Animations shortfall: preview from the selected effect (Play From) is in. Percentages unchanged |
|
||||
| 2026-10-17 | trivial | A word no longer breaks after `?`, `!`, `}` or `+` (a URL's query wraps at the edge as in PowerPoint 2016 for Windows), as it already didn't after `/` and `\`. Headline percentages unchanged |
|
||||
|
||||
@@ -17,6 +17,12 @@ set -euo pipefail
|
||||
. "$(dirname "${BASH_SOURCE[0]}")/../common.sh"
|
||||
HERE="$ROOT/packaging/linux"
|
||||
APP_ID=ai.storyteller.deckcraft
|
||||
FLATPAK_ID="$APP_ID"
|
||||
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
|
||||
FLATPAK_BRANCH=stable
|
||||
if [[ "${DECKCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
|
||||
FLATPAK_ID="$APP_ID.nightly"
|
||||
fi
|
||||
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
TEST=1
|
||||
@@ -51,30 +57,78 @@ WORK="$CARGO_TARGET_DIR/flatpak-bundle"
|
||||
rm -rf "$WORK"
|
||||
mkdir -p "$WORK/stage"
|
||||
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
|
||||
[[ -x "$WORK/stage/bin/deckcraft" ]] || { echo "error: $TARBALL has no bin/deckcraft" >&2; exit 1; }
|
||||
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
|
||||
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
|
||||
# The nightly tarball already carries its launcher and a GUI named for it, so the bundle
|
||||
# installs both rather than generating a sixth wrapper.
|
||||
[[ -x "$WORK/stage/bin/deckcraft-bin" && -x "$WORK/stage/bin/deckcraft-nightly" ]] \
|
||||
|| { echo "error: the nightly $TARBALL has no bin/deckcraft-bin and bin/deckcraft-nightly" >&2; exit 1; }
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/deckcraft-nightly.png"
|
||||
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
# Two ids meet here on purpose. The bundle id is the Flatpak app id (`$APP_ID.nightly`), so the
|
||||
# exported desktop entry, its basename and the icon carry it. The window keeps the flavor id
|
||||
# (`$APP_ID.nightly-v1`) that every other Linux format's desktop entry is renamed to, so
|
||||
# StartupWMClass names the window id: that is what ties this launcher to the running window.
|
||||
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
|
||||
-e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \
|
||||
-e "s#^Exec=deckcraft\\([[:space:]]\\|$\\)#Exec=deckcraft-nightly\\1#" \
|
||||
-e "s|^TryExec=deckcraft$|TryExec=deckcraft-nightly|" \
|
||||
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.deckcraft.nightly-v1|' \
|
||||
-e '/^MimeType=/d' \
|
||||
"$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop"
|
||||
rm -f "$WORK/stage/share/applications/$APP_ID.desktop"
|
||||
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
|
||||
-e "s|<name>DeckCraft</name>|<name>DeckCraft Nightly</name>|g" \
|
||||
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$FLATPAK_ID.desktop</launchable>|g" \
|
||||
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$FLATPAK_ID</icon>|g" \
|
||||
-e '/<mediatype>/d' \
|
||||
"$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml"
|
||||
rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml"
|
||||
mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml"
|
||||
rm -rf "$WORK/stage/share/icons/hicolor"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
|
||||
# Flatpak starts `command`, and the desktop entry's Exec names the same launcher; the GUI sits
|
||||
# beside it in /app/bin, where the launcher looks first.
|
||||
sed -e "s|ai\.storyteller\.deckcraft|$FLATPAK_ID|g" \
|
||||
-e 's|^command: deckcraft$|command: deckcraft-nightly|' \
|
||||
-e 's|^ - install -Dm755 bin/deckcraft /app/bin/deckcraft$| - install -Dm755 bin/deckcraft-bin /app/bin/deckcraft-bin\n - install -Dm755 bin/deckcraft-nightly /app/bin/deckcraft-nightly|' \
|
||||
-e 's|<binary>deckcraft</binary>|<binary>deckcraft-nightly</binary>|' \
|
||||
"$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml"
|
||||
# A template change must fail here, not as a bundle whose menu entry cannot find a program.
|
||||
for expected in 'command: deckcraft-nightly' \
|
||||
' - install -Dm755 bin/deckcraft-bin /app/bin/deckcraft-bin' \
|
||||
' - install -Dm755 bin/deckcraft-nightly /app/bin/deckcraft-nightly'; do
|
||||
grep -qxF "$expected" "$WORK/$FLATPAK_ID.yml" || {
|
||||
echo "error: the nightly Flatpak manifest lost \"$expected\"" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
else
|
||||
[[ -x "$WORK/stage/bin/deckcraft" ]] || { echo "error: $TARBALL has no bin/deckcraft" >&2; exit 1; }
|
||||
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml"
|
||||
fi
|
||||
|
||||
flatpak remote-add --user --if-not-exists flathub "$FLATHUB"
|
||||
# --disable-rofiles-fuse: no FUSE in containers and CI runners.
|
||||
flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \
|
||||
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
|
||||
--default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml"
|
||||
|
||||
OUT="$DIST/$BASENAME.flatpak"
|
||||
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
|
||||
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable
|
||||
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH"
|
||||
echo "wrote $OUT"
|
||||
if [[ "$OCI" = 1 ]]; then
|
||||
OUT_OCI="$DIST/$BASENAME-oci"
|
||||
rm -rf "$OUT_OCI"
|
||||
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
|
||||
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH"
|
||||
echo "wrote OCI layout to $OUT_OCI"
|
||||
fi
|
||||
|
||||
if [[ "$TEST" = 1 ]]; then
|
||||
flatpak install --user -y --noninteractive --reinstall "$OUT"
|
||||
flatpak info --user "$APP_ID"
|
||||
flatpak run --command=deckcraft-cli "$APP_ID" --version
|
||||
flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/256x256/apps'
|
||||
flatpak info --user "$FLATPAK_ID"
|
||||
flatpak run --command=deckcraft-cli "$FLATPAK_ID" --version
|
||||
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
|
||||
fi
|
||||
echo "==> done"
|
||||
ls -lh "$OUT"
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# exports VERSION and NFPM_ARCH.
|
||||
#
|
||||
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
|
||||
name: deckcraft
|
||||
name: ${NFPM_NAME}
|
||||
arch: ${NFPM_ARCH}
|
||||
platform: linux
|
||||
version: ${VERSION}
|
||||
@@ -58,12 +58,15 @@ overrides:
|
||||
- xdg-desktop-portal
|
||||
|
||||
contents:
|
||||
- src: ${STAGE}/usr/bin/deckcraft
|
||||
dst: /usr/bin/deckcraft
|
||||
- src: ${STAGE}/usr/bin/${NFPM_BIN}
|
||||
dst: /usr/bin/${NFPM_BIN}
|
||||
file_info: { mode: 0755 }
|
||||
- src: ${STAGE}/usr/bin/deckcraft-cli
|
||||
dst: /usr/bin/deckcraft-cli
|
||||
- src: ${STAGE}/usr/bin/${NFPM_CLI}
|
||||
dst: /usr/bin/${NFPM_CLI}
|
||||
file_info: { mode: 0755 }
|
||||
- src: ${STAGE}/usr/lib/
|
||||
dst: /usr/lib/
|
||||
type: tree
|
||||
- src: ${STAGE}/usr/share/
|
||||
dst: /usr/share/
|
||||
type: tree
|
||||
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Validate the staged Arch launcher without building or opening DeckCraft.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
stage="$work/source"
|
||||
dst="$work/dist"
|
||||
base=deckcraft-0.0.1-nightly.1-linux-x86_64
|
||||
mkdir -p "$stage/bin" "$dst" "$work/extract"
|
||||
|
||||
# A local argv recorder stands in for the compiled binaries. It never opens a UI.
|
||||
cat >"$stage/bin/deckcraft" <<'RECORDER'
|
||||
#!/bin/sh
|
||||
printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
chmod 755 "$stage/bin/deckcraft"
|
||||
cp "$stage/bin/deckcraft" "$stage/bin/deckcraft-cli"
|
||||
|
||||
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
|
||||
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
|
||||
bin="$work/extract/$base/bin"
|
||||
# Simulate the existing Arch bin-tree copy and public launcher rename.
|
||||
mkdir -p "$work/installed"
|
||||
cp -R "$bin" "$work/installed/bin"
|
||||
bin="$work/installed/bin"
|
||||
mv "$bin/deckcraft" "$bin/deckcraft-nightly"
|
||||
mv "$bin/deckcraft-cli" "$bin/deckcraft-nightly-cli"
|
||||
|
||||
[[ ! -e "$stage/bin/.deckcraft-nightly" ]]
|
||||
cmp "$stage/bin/deckcraft" "$bin/.deckcraft-nightly/deckcraft-bin"
|
||||
cmp "$stage/bin/deckcraft-cli" "$bin/deckcraft-nightly-cli"
|
||||
export HOME="$work/home"
|
||||
mkdir -p "$HOME"
|
||||
export XDG_CONFIG_HOME="$HOME/.config" XDG_DATA_HOME="$HOME/.local/share"
|
||||
expect() {
|
||||
expected="$1"
|
||||
shift
|
||||
actual=$(PATH="$bin:$PATH" deckcraft-nightly "$@")
|
||||
if [[ "$actual" != "$expected" ]]; then
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
profile="$XDG_DATA_HOME/deckcraft-nightly/launcher/profiles/deckcraft"
|
||||
nightly_argv() {
|
||||
printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" --
|
||||
}
|
||||
expect "$(nightly_argv)"
|
||||
expect "$(nightly_argv; printf '<%s>\n' 'deck with spaces.pptx' '--other-name.deckcraft')" \
|
||||
'deck with spaces.pptx' '--other-name.deckcraft'
|
||||
# A caller-written `--` is the launcher's own separator: it is never passed on as a file name.
|
||||
expect "$(nightly_argv; printf '<%s>\n' 'deck.pptx')" -- deck.pptx
|
||||
# A bare version query stays a version query, not a file name, and creates no profile.
|
||||
expect '<--version>' --version
|
||||
expect '<-V>' -V
|
||||
# The Launcher's own protocol is passed through untouched, never wrapped a second time.
|
||||
expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx')" \
|
||||
--launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx'
|
||||
test ! -e "$profile"
|
||||
# A profile needs a data folder: the launcher refuses instead of writing into /.
|
||||
status=0
|
||||
env -u XDG_DATA_HOME -u HOME PATH="$bin:$PATH" deckcraft-nightly deck.pptx >/dev/null 2>&1 || status=$?
|
||||
[[ "$status" -eq 2 ]] || { printf 'expected exit 2 without XDG_DATA_HOME/HOME, got %s\n' "$status" >&2; exit 1; }
|
||||
test ! -e "$work/home/.local/share/deckcraft-nightly"
|
||||
|
||||
echo "PASS: Arch Nightly handoff stages the hidden GUI, the shared launcher and the launch arguments"
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Stage the DeckCraft Nightly-only handoff for the Arch packager.
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
source_tree="$1"
|
||||
work="$2"
|
||||
destination="$3"
|
||||
basename="$4"
|
||||
stage="$work/$basename"
|
||||
|
||||
mkdir -p "$work"
|
||||
cp -R "$source_tree" "$stage"
|
||||
mkdir "$stage/bin/.deckcraft-nightly"
|
||||
mv "$stage/bin/deckcraft" "$stage/bin/.deckcraft-nightly/deckcraft-bin"
|
||||
cp "$here/nightly-launch.sh" "$stage/bin/deckcraft"
|
||||
chmod 755 "$stage/bin/deckcraft"
|
||||
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
|
||||
echo "wrote $destination/$basename.tar.gz"
|
||||
Executable
+105
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env bash
|
||||
# Validate the nightly launcher in every Linux placement without building or opening DeckCraft:
|
||||
# the flat nightly tar (`deckcraft` + `deckcraft-bin`), the AppImage (`AppRun` + `usr/bin/deckcraft`),
|
||||
# the distro tree (`bin/deckcraft-nightly` + `bin/deckcraft-bin`) and the /usr/bin rule that reaches
|
||||
# the fixed /usr/lib copy. A recorder binary stands in for the GUI and prints its argv.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
launcher="$HERE/nightly-launch.sh"
|
||||
export HOME="$work/home"
|
||||
mkdir -p "$HOME"
|
||||
export XDG_CONFIG_HOME="$HOME/.config" XDG_DATA_HOME="$HOME/.local/share"
|
||||
profile="$XDG_DATA_HOME/deckcraft-nightly/launcher/profiles/deckcraft"
|
||||
|
||||
recorder() {
|
||||
mkdir -p "$(dirname "$1")"
|
||||
cat >"$1" <<'RECORDER'
|
||||
#!/bin/sh
|
||||
printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
chmod 755 "$1"
|
||||
}
|
||||
|
||||
expect() {
|
||||
binary="$1"
|
||||
expected="$2"
|
||||
shift 2
|
||||
actual=$("$binary" "$@")
|
||||
if [[ "$actual" != "$expected" ]]; then
|
||||
printf '%s\nexpected:\n%s\nactual:\n%s\n' "$binary" "$expected" "$actual" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
nightly_argv() {
|
||||
printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" --
|
||||
}
|
||||
|
||||
# ---- the flat nightly tar: `deckcraft` launcher, `deckcraft-bin` GUI ----
|
||||
flat="$work/flat"
|
||||
recorder "$flat/deckcraft-bin"
|
||||
cp "$launcher" "$flat/deckcraft"
|
||||
chmod 755 "$flat/deckcraft"
|
||||
expect "$flat/deckcraft" "$(nightly_argv)"
|
||||
expect "$flat/deckcraft" "$(nightly_argv; printf '<%s>\n' 'deck with spaces.pptx' '--other-name.pptx')" \
|
||||
'deck with spaces.pptx' '--other-name.pptx'
|
||||
expect "$flat/deckcraft" "$(nightly_argv; printf '<%s>\n' 'deck.pptx')" -- deck.pptx
|
||||
expect "$flat/deckcraft" '<--version>' --version
|
||||
expect "$flat/deckcraft" '<-V>' -V
|
||||
expect "$flat/deckcraft" '<--help>' --help
|
||||
expect "$flat/deckcraft" "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx')" \
|
||||
--launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx'
|
||||
test ! -e "$profile"
|
||||
|
||||
# ---- the AppImage: AppRun at the mount root, the GUI and the entry's copy in usr/bin ----
|
||||
appdir="$work/DeckCraft.AppDir"
|
||||
recorder "$appdir/usr/bin/deckcraft-bin"
|
||||
cp "$launcher" "$appdir/AppRun"
|
||||
chmod 755 "$appdir/AppRun"
|
||||
expect "$appdir/AppRun" "$(nightly_argv; printf '<%s>\n' book.pptx)" book.pptx
|
||||
cp "$launcher" "$appdir/usr/bin/deckcraft-nightly"
|
||||
chmod 755 "$appdir/usr/bin/deckcraft-nightly"
|
||||
expect "$appdir/usr/bin/deckcraft-nightly" "$(nightly_argv; printf '<%s>\n' book.pptx)" book.pptx
|
||||
test ! -e "$profile"
|
||||
|
||||
# ---- the distro tree tarball: bin/deckcraft-nightly beside bin/deckcraft-bin ----
|
||||
tree="$work/tree/bin"
|
||||
recorder "$tree/deckcraft-bin"
|
||||
cp "$launcher" "$tree/deckcraft-nightly"
|
||||
chmod 755 "$tree/deckcraft-nightly"
|
||||
actual=$(PATH="$tree:$PATH" deckcraft-nightly book.pptx)
|
||||
[[ "$actual" == "$(nightly_argv; printf '<%s>\n' book.pptx)" ]] || { printf 'a PATH invocation printed:\n%s\n' "$actual" >&2; exit 1; }
|
||||
test ! -e "$profile"
|
||||
|
||||
# ---- a missing GUI fails closed, and so does a tree with no data folder ----
|
||||
empty="$work/empty"
|
||||
mkdir -p "$empty"
|
||||
cp "$launcher" "$empty/deckcraft"
|
||||
chmod 755 "$empty/deckcraft"
|
||||
status=0
|
||||
"$empty/deckcraft" book.pptx >/dev/null 2>&1 || status=$?
|
||||
[[ "$status" -eq 2 ]] || { printf 'a launcher with no GUI must exit 2, got %s\n' "$status" >&2; exit 1; }
|
||||
recorder "$work/nodata/deckcraft-bin"
|
||||
cp "$launcher" "$work/nodata/deckcraft"
|
||||
chmod 755 "$work/nodata/deckcraft"
|
||||
status=0
|
||||
env -u XDG_DATA_HOME -u HOME "$work/nodata/deckcraft" book.pptx >/dev/null 2>&1 || status=$?
|
||||
[[ "$status" -eq 2 ]] || { printf 'a launcher with no data folder must exit 2, got %s\n' "$status" >&2; exit 1; }
|
||||
# A query is not a launch: it answers without a data folder instead of becoming that error.
|
||||
actual=$(env -u XDG_DATA_HOME -u HOME "$work/nodata/deckcraft" --version) \
|
||||
|| { printf 'a no-data-folder --version must still answer\n' >&2; exit 1; }
|
||||
[[ "$actual" == '<--version>' ]] || { printf 'a no-data-folder --version printed:\n%s\n' "$actual" >&2; exit 1; }
|
||||
|
||||
# ---- the /usr/bin rule: the fixed /usr/lib copy is named, and no parent path is ever used ----
|
||||
# The launcher's text is searched literally, so `$here` must not expand here.
|
||||
# shellcheck disable=SC2016
|
||||
grep -Fq '[ "$here" = /usr/bin ]' "$launcher"
|
||||
grep -Fq '/usr/lib/deckcraft-nightly/deckcraft' "$launcher"
|
||||
if grep -q '\.\.' "$launcher"; then
|
||||
echo "the launcher must not reach outside its own folder or the fixed /usr/lib path" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: nightly launcher starts the GUI with the profile in every layout and refuses the rest"
|
||||
Executable
+63
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
# The DeckCraft Nightly launcher every Linux format ships: the plain nightly tar's `deckcraft`, the
|
||||
# distro tree's `bin/deckcraft-nightly`, the AppImage's `AppRun`, the Arch handoff's `bin/deckcraft`
|
||||
# and the Flatpak's `/app/bin/deckcraft-nightly`. A nightly build refuses to start without
|
||||
# `--launch-profile nightly-v1 --profile-root <dir>`, and the profile is its only data root, so
|
||||
# this is what keeps a Nightly run out of the stable app's settings, prefs, logs and recovery.
|
||||
set -eu
|
||||
|
||||
# Resolve this script's own folder from `$0`. A shell that finds it through PATH passes a bare
|
||||
# name, so ask the shell where that is instead of using the working directory.
|
||||
case "$0" in
|
||||
*/*) self="$0" ;;
|
||||
*) self="$(command -v "$0" || printf '%s' "$0")" ;;
|
||||
esac
|
||||
case "$self" in
|
||||
/*) ;;
|
||||
*) self="$PWD/$self" ;;
|
||||
esac
|
||||
here="$(CDPATH='' cd "$(dirname "$self")" && pwd -P)"
|
||||
self="$here/$(basename "$self")"
|
||||
|
||||
# The GUI each placement keeps inside its own tree, never from a parent folder: `deckcraft-bin`
|
||||
# beside the launcher (the flat nightly tar, the distro tree, the Flatpak sandbox), the same name
|
||||
# in an AppImage's `usr/bin`, and the hidden copy the Arch handoff keeps. A candidate that is this
|
||||
# same file is never started, so a launcher cannot recurse into itself.
|
||||
real=
|
||||
for candidate in "$here/deckcraft-bin" "$here/usr/bin/deckcraft-bin" "$here/.deckcraft-nightly/deckcraft-bin"; do
|
||||
if [ -f "$candidate" ] && [ -x "$candidate" ] && [ ! "$candidate" -ef "$self" ]; then
|
||||
real="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
# A distro package keeps the GUI in /usr/lib. Reach that fixed path only from /usr/bin, so a
|
||||
# writable parent folder can never plant a program for this launcher to run.
|
||||
if [ -z "$real" ] && [ "$here" = /usr/bin ] && [ -f /usr/lib/deckcraft-nightly/deckcraft ] && [ -x /usr/lib/deckcraft-nightly/deckcraft ]; then
|
||||
real=/usr/lib/deckcraft-nightly/deckcraft
|
||||
fi
|
||||
if [ -z "$real" ]; then
|
||||
echo "deckcraft-nightly: no DeckCraft binary beside $self" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# A bare version/help query and the Launcher's own protocol pass straight through: they are not
|
||||
# file names, need no data folder, and a profile the caller already supplied is never wrapped
|
||||
# twice. This runs before the data-folder check, so `deckcraft-nightly --version` still answers
|
||||
# where HOME and XDG_DATA_HOME are both unset.
|
||||
case "${1-}" in
|
||||
--launch-profile | --profile-root | --version | -V | --help | -h) exec "$real" "$@" ;;
|
||||
esac
|
||||
|
||||
if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then
|
||||
echo "deckcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2
|
||||
exit 2
|
||||
fi
|
||||
# The same root as every other format's launcher: beside the fenced stable `deckcraft` folder,
|
||||
# never inside it.
|
||||
profile="${XDG_DATA_HOME:-$HOME/.local/share}/deckcraft-nightly/launcher/profiles/deckcraft"
|
||||
# A caller-written `--` is the separator this launcher adds below. Drop it, so it can never reach
|
||||
# the app as a file name.
|
||||
if [ "${1-}" = "--" ]; then
|
||||
shift
|
||||
fi
|
||||
exec "$real" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env bash
|
||||
# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks.
|
||||
set -euo pipefail
|
||||
ARCH=
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
|
||||
-h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;;
|
||||
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; }
|
||||
# shellcheck source=../nightly-common.sh
|
||||
. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh"
|
||||
nightly_init linux "$ARCH" x86_64-unknown-linux-gnu
|
||||
OUTPUT="$DIST/deckcraft-$VERSION-linux-x86_64-nightly.tar.gz"
|
||||
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
|
||||
nightly_build_gui
|
||||
STAGE="$NIGHTLY_WORK/stage"
|
||||
mkdir -p "$STAGE"
|
||||
# The kit's flat tar layout: `deckcraft` is the launcher people run and `deckcraft-bin` the GUI it
|
||||
# starts with this channel's own launch profile, so an unpacked copy never writes stable's data.
|
||||
cp "$NIGHTLY_GUI" "$STAGE/deckcraft-bin"
|
||||
chmod 755 "$STAGE/deckcraft-bin"
|
||||
cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/deckcraft"
|
||||
chmod 755 "$STAGE/deckcraft"
|
||||
ICON_SRC="$ROOT/assets/app-icon/deckcraft-nightly.png"
|
||||
[[ -f "$ICON_SRC" ]] || ICON_SRC="$ROOT/assets/app-icon/deckcraft-1024.png"
|
||||
cp "$ICON_SRC" "$STAGE/deckcraft-nightly.png"
|
||||
nightly_copy_notices "$STAGE"
|
||||
# The private mktemp cwd is the helper authority root, not a CLI path parent.
|
||||
(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz)
|
||||
nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT"
|
||||
+141
-9
@@ -7,7 +7,7 @@
|
||||
# $DIST/deckcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
|
||||
# $DIST/deckcraft-<version>-linux-<arch>.tar.gz plain FHS-style tree (bin/, share/)
|
||||
#
|
||||
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"]
|
||||
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY]
|
||||
#
|
||||
# Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage
|
||||
# (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04,
|
||||
@@ -27,10 +27,16 @@ verify_sha256() {
|
||||
|
||||
SKIP_BUILD=0
|
||||
FORMATS="appimage deb rpm tar"
|
||||
ARCH_TAR_DIR=
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1; shift ;;
|
||||
--formats) FORMATS="$2"; shift 2 ;;
|
||||
--arch-tar-dir)
|
||||
[[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; }
|
||||
ARCH_TAR_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h | --help) sed -n '2,17p' "$0"; exit 0 ;;
|
||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -44,9 +50,20 @@ case "$ARCH" in
|
||||
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
|
||||
esac
|
||||
export DECKCRAFT_MAINTAINER="${DECKCRAFT_MAINTAINER:-DeckCraft maintainers <[email protected]>}"
|
||||
IS_NIGHTLY=0
|
||||
if [[ "${DECKCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
|
||||
IS_NIGHTLY=1
|
||||
export DECKCRAFT_BUILD_CHANNEL=nightly-v1
|
||||
export DECKCRAFT_OVERRIDE_VERSION="$VERSION"
|
||||
fi
|
||||
BASENAME="deckcraft-$VERSION-linux-$ARCH"
|
||||
|
||||
echo "==> DeckCraft $VERSION for Linux $ARCH ($FORMATS)"
|
||||
if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then
|
||||
echo "error: --arch-tar-dir is only for Nightly builds" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "==> DeckCraft $VERSION for Linux $ARCH ($FORMATS, channel=${DECKCRAFT_BUILD_CHANNEL:-stable})"
|
||||
|
||||
if [[ "$SKIP_BUILD" = 0 ]]; then
|
||||
if [[ -n "${CROSS_TARGET:-}" ]]; then
|
||||
@@ -65,6 +82,11 @@ install -Dm755 "$BIN/deckcraft" "$STAGE/usr/bin/deckcraft"
|
||||
install -Dm755 "$BIN/deckcraft-cli" "$STAGE/usr/bin/deckcraft-cli"
|
||||
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/deckcraft" "$STAGE/usr/bin/deckcraft-cli" 2>/dev/null || true
|
||||
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.deckcraft.nightly-v1|' \
|
||||
"$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp"
|
||||
mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
fi
|
||||
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
|
||||
mkdir -p "$STAGE/usr/share/metainfo"
|
||||
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$DECKCRAFT_BUILD_DATE/g" \
|
||||
@@ -90,17 +112,88 @@ has() {
|
||||
if has tar; then
|
||||
mkdir -p "$WORK/tar"
|
||||
cp -R "$STAGE/usr" "$WORK/tar/$BASENAME"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
# An unpacked nightly tree is isolated too: bin/deckcraft-nightly starts the GUI (here
|
||||
# bin/deckcraft-bin), because the binary alone refuses to run without a launch profile.
|
||||
install -Dm755 "$WORK/tar/$BASENAME/bin/deckcraft" "$WORK/tar/$BASENAME/bin/deckcraft-bin"
|
||||
rm -f "$WORK/tar/$BASENAME/bin/deckcraft"
|
||||
install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/deckcraft-nightly"
|
||||
TAR_DESK="$WORK/tar/$BASENAME/share/applications/$APP_ID.desktop"
|
||||
sed -e "s#^Exec=deckcraft\([[:space:]]\|$\)#Exec=deckcraft-nightly\1#" \
|
||||
-e "s|^TryExec=deckcraft$|TryExec=deckcraft-nightly|" \
|
||||
-e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \
|
||||
-e '/^MimeType=/d' \
|
||||
"$TAR_DESK" >"$TAR_DESK.tmp"
|
||||
mv "$TAR_DESK.tmp" "$TAR_DESK"
|
||||
fi
|
||||
tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME"
|
||||
echo "wrote $DIST/$BASENAME.tar.gz"
|
||||
fi
|
||||
|
||||
# The Arch handoff keeps the same basename as the plain tarball in a separate directory. It is
|
||||
# built from the staged tree, not from the nightly tar beside it (whose bin/deckcraft is already
|
||||
# the launcher and whose bin/deckcraft-bin is the GUI).
|
||||
if [[ -n "$ARCH_TAR_DIR" ]]; then
|
||||
mkdir -p "$ARCH_TAR_DIR"
|
||||
if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then
|
||||
echo "error: the Arch tar directory must differ from the release directory" >&2
|
||||
exit 2
|
||||
fi
|
||||
bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME"
|
||||
fi
|
||||
|
||||
# ---- .deb / .rpm --------------------------------------------------------------------------------
|
||||
if has deb || has rpm; then
|
||||
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
|
||||
export VERSION
|
||||
export NFPM_ARCH="$DEB_ARCH"
|
||||
NFPM_STAGE="$STAGE"
|
||||
export NFPM_NAME="deckcraft"
|
||||
export NFPM_BIN="deckcraft"
|
||||
export NFPM_CLI="deckcraft-cli"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/deckcraft-nightly.png"
|
||||
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
export NFPM_NAME="deckcraft-nightly"
|
||||
export NFPM_BIN="deckcraft-nightly"
|
||||
export NFPM_CLI="deckcraft-nightly-cli"
|
||||
NFPM_STAGE="$WORK/nfpm-root"
|
||||
rm -rf "$NFPM_STAGE"
|
||||
cp -R "$STAGE" "$NFPM_STAGE"
|
||||
# The GUI keeps its name under /usr/lib; /usr/bin/deckcraft-nightly is the launcher, whose
|
||||
# /usr/bin gate is what reaches that fixed path (the same file as the tar and AppImage use).
|
||||
install -Dm755 "$NFPM_STAGE/usr/bin/deckcraft" "$NFPM_STAGE/usr/lib/deckcraft-nightly/deckcraft"
|
||||
install -Dm755 "$HERE/nightly-launch.sh" "$NFPM_STAGE/usr/bin/$NFPM_BIN"
|
||||
rm -f "$NFPM_STAGE/usr/bin/deckcraft"
|
||||
mv "$NFPM_STAGE/usr/bin/deckcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
|
||||
mv "$NFPM_STAGE/usr/share/doc/deckcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
|
||||
sed -e "s#^Exec=deckcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
|
||||
-e "s|^TryExec=deckcraft$|TryExec=$NFPM_BIN|" \
|
||||
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
|
||||
-e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \
|
||||
-e '/^MimeType=/d' \
|
||||
"$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop"
|
||||
rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
sed -e "s|<id>$APP_ID</id>|<id>$NIGHTLY_DESK_ID</id>|g" \
|
||||
-e "s|<name>DeckCraft</name>|<name>DeckCraft Nightly</name>|g" \
|
||||
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$NIGHTLY_DESK_ID.desktop</launchable>|g" \
|
||||
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$NIGHTLY_DESK_ID</icon>|g" \
|
||||
-e "s|<binary>deckcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
|
||||
-e '/<mediatype>/d' \
|
||||
"$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml"
|
||||
rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
|
||||
rm -rf "$NFPM_STAGE/usr/share/mime"
|
||||
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
|
||||
fi
|
||||
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
|
||||
sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
|
||||
DROP_LIB_TREE=
|
||||
# shellcheck disable=SC2016
|
||||
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
|
||||
# shellcheck disable=SC2016
|
||||
sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
|
||||
for fmt in deb rpm; do
|
||||
if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi
|
||||
done
|
||||
@@ -127,10 +220,40 @@ if has appimage; then
|
||||
fi
|
||||
APPDIR="$WORK/DeckCraft.AppDir"
|
||||
cp -R "$STAGE" "$APPDIR"
|
||||
ln -s usr/bin/deckcraft "$APPDIR/AppRun"
|
||||
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
|
||||
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
|
||||
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
# Not a symlink: the nightly AppImage starts the app with its launch profile, so an AppImage
|
||||
# run is isolated like the distro package even without the ArtCraft Launcher. The GUI takes
|
||||
# the name the launcher looks for, and the entry names the launcher for integrations that
|
||||
# read it.
|
||||
install -Dm755 "$APPDIR/usr/bin/deckcraft" "$APPDIR/usr/bin/deckcraft-bin"
|
||||
rm -f "$APPDIR/usr/bin/deckcraft"
|
||||
install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/AppRun"
|
||||
install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/usr/bin/deckcraft-nightly"
|
||||
else
|
||||
ln -s usr/bin/deckcraft "$APPDIR/AppRun"
|
||||
fi
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
APPIMAGE_ID="$APP_ID.nightly-v1"
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/deckcraft-nightly.png"
|
||||
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
sed -e "s#^Exec=deckcraft\([[:space:]]\|$\)#Exec=deckcraft-nightly\1#" \
|
||||
-e "s|^TryExec=deckcraft$|TryExec=deckcraft-nightly|" \
|
||||
-e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
|
||||
-e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \
|
||||
-e '/^MimeType=/d' \
|
||||
"$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop"
|
||||
rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop"
|
||||
cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop"
|
||||
rm -rf "$APPDIR/usr/share/icons/hicolor"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
|
||||
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
|
||||
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
|
||||
else
|
||||
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
|
||||
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
|
||||
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
|
||||
fi
|
||||
|
||||
TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
|
||||
if [[ -z "$TOOL" ]]; then
|
||||
@@ -171,11 +294,20 @@ if has appimage; then
|
||||
# each AppImage on GitHub Releases. `latest` is the newest published release that is not a
|
||||
# pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY.
|
||||
REPO="${GITHUB_REPOSITORY:-storytold/deckcraft}"
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|deckcraft-*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=()
|
||||
if [[ "$IS_NIGHTLY" = 0 ]]; then
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|deckcraft-*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=(-u "$UPDATE_INFO")
|
||||
else
|
||||
# Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point
|
||||
# zsync update metadata at `latest-pre` using the same asset naming pattern as `BASENAME`.
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|deckcraft-*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=(-u "$UPDATE_INFO")
|
||||
fi
|
||||
# Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime,
|
||||
# so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync
|
||||
# package) appimagetool also writes the .zsync, into its working directory, hence the cd.
|
||||
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT")
|
||||
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT")
|
||||
echo "wrote $OUT"
|
||||
if [[ -s "$OUT.zsync" ]]; then
|
||||
echo "wrote $OUT.zsync"
|
||||
|
||||
Executable
+110
@@ -0,0 +1,110 @@
|
||||
# shellcheck shell=bash
|
||||
# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh).
|
||||
# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output
|
||||
# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS.
|
||||
|
||||
MAC_NIGHTLY_APP='DeckCraft Nightly.app'
|
||||
MAC_NIGHTLY_ID='ai.storyteller.deckcraft.nightly'
|
||||
# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh).
|
||||
MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID)
|
||||
|
||||
mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
|
||||
|
||||
# The exact prepared version from the feed asset name, or failure.
|
||||
mac_nightly_version_from_asset() {
|
||||
local name="$1" version
|
||||
[[ "$name" =~ ^deckcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1
|
||||
version="${BASH_REMATCH[1]}"
|
||||
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1
|
||||
printf '%s\n' "$version"
|
||||
}
|
||||
|
||||
# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback.
|
||||
mac_nightly_require_secrets() {
|
||||
local name
|
||||
for name in "${MAC_NIGHTLY_SECRETS[@]}"; do
|
||||
[[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback"
|
||||
done
|
||||
[[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID'
|
||||
if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then
|
||||
mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)'
|
||||
fi
|
||||
}
|
||||
|
||||
# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team.
|
||||
mac_nightly_identity_is_team() {
|
||||
local line="$1" identity="$2" team="$3"
|
||||
[[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]]
|
||||
}
|
||||
|
||||
# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the
|
||||
# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict).
|
||||
mac_nightly_check_signature() {
|
||||
local details="$1" team="$2" ok=0
|
||||
grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; }
|
||||
grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; }
|
||||
grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; }
|
||||
grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; }
|
||||
grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; }
|
||||
return "$ok"
|
||||
}
|
||||
|
||||
# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized.
|
||||
mac_nightly_check_assessment() {
|
||||
grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1"
|
||||
}
|
||||
|
||||
# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly
|
||||
# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file.
|
||||
mac_nightly_check_zip_entries() {
|
||||
python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file'
|
||||
import stat, sys, zipfile
|
||||
archive, app = sys.argv[1:]
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
for info in z.infolist():
|
||||
name = info.filename
|
||||
parts = name.rstrip("/").split("/")
|
||||
mode = info.external_attr >> 16
|
||||
if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app
|
||||
or any(part in ("", ".", "..") for part in parts)
|
||||
or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)):
|
||||
sys.exit(f"refused entry: {name!r}")
|
||||
PY
|
||||
}
|
||||
|
||||
# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 DeckCraft
|
||||
# executable, the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special
|
||||
# files, no document or URL types.
|
||||
mac_nightly_check_bundle() {
|
||||
local payload="$1" version="$2" app entries plist key value
|
||||
app="$payload/$MAC_NIGHTLY_APP"
|
||||
entries="$(ls -A "$payload")"
|
||||
[[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP"
|
||||
[[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files'
|
||||
[[ "$(ls -A "$app/Contents/MacOS")" == DeckCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the DeckCraft GUI (no CLI)'
|
||||
[[ -f "$app/Contents/MacOS/DeckCraft" && -x "$app/Contents/MacOS/DeckCraft" ]] || mac_nightly_die 'missing executable GUI'
|
||||
[[ "$(lipo -archs "$app/Contents/MacOS/DeckCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64'
|
||||
plist="$app/Contents/Info.plist"
|
||||
for key in CFBundleIdentifier CFBundleExecutable DeckCraftVersion; do
|
||||
value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key"
|
||||
case "$key" in
|
||||
CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;;
|
||||
CFBundleExecutable) [[ "$value" == DeckCraft ]] ;;
|
||||
DeckCraftVersion) [[ "$value" == "$version" ]] ;;
|
||||
esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity"
|
||||
done
|
||||
for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do
|
||||
if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi
|
||||
done
|
||||
}
|
||||
|
||||
# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68)
|
||||
# though the ticket is there (verify.sh).
|
||||
mac_nightly_validate_staple() {
|
||||
local target="$1" attempt
|
||||
for attempt in 1 2 3 4 5; do
|
||||
xcrun stapler validate "$target" && return 0
|
||||
[[ "$attempt" = 5 ]] || sleep $((attempt * 20))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
Executable
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env bash
|
||||
# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route
|
||||
# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps):
|
||||
#
|
||||
# nightly-sign.sh --arch aarch64 --input /abs/deckcraft-<version>-macos-aarch64-nightly.zip \
|
||||
# --output /abs/<dir>/deckcraft-<version>-macos-aarch64-nightly.zip
|
||||
#
|
||||
# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and
|
||||
# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended
|
||||
# attributes. Writes only that file, never replacing one; the temporary keychain and work directory
|
||||
# are removed on every exit.
|
||||
#
|
||||
# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD,
|
||||
# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must
|
||||
# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base).
|
||||
#
|
||||
# Never compiles, and never runs anything from the payload: the version query runs on the signed
|
||||
# bundle in a job without secrets (nightly-verify.sh).
|
||||
set -euo pipefail
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=nightly-lib.sh
|
||||
. "$HERE/nightly-lib.sh"
|
||||
# shellcheck source=../nightly-common.sh
|
||||
. "$HERE/../nightly-common.sh"
|
||||
|
||||
ARCH='' INPUT='' OUTPUT=''
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--arch | --input | --output)
|
||||
[[ $# -ge 2 ]] || mac_nightly_die "missing $1 value"
|
||||
case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac
|
||||
shift 2 ;;
|
||||
-h | --help) sed -n '2,18p' "$0"; exit 0 ;;
|
||||
*) mac_nightly_die "unsupported argument: $1" ;;
|
||||
esac
|
||||
done
|
||||
[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported'
|
||||
[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths'
|
||||
NAME="$(basename -- "$INPUT")"
|
||||
VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name'
|
||||
[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name'
|
||||
[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file'
|
||||
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output'
|
||||
[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist'
|
||||
mac_nightly_require_secrets
|
||||
[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)'
|
||||
|
||||
BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}"
|
||||
WORK="$(mktemp -d "${BASE%/}/deckcraft-nightly-sign.XXXXXX")"
|
||||
# import-cert.sh creates the keychain under RUNNER_TEMP, in a private subdirectory of its own; the
|
||||
# path is taken from its output below and must stay inside this run's WORK.
|
||||
KEYCHAIN=""
|
||||
cleanup() {
|
||||
if [[ -n "$KEYCHAIN" && -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi
|
||||
rm -rf -- "$WORK"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# ---- identity: import-cert.sh, into this run's private directory ------------------------------
|
||||
# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps.
|
||||
imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")"
|
||||
IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")"
|
||||
KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")"
|
||||
[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ && "$KEYCHAIN" == "$WORK"/* && -f "$KEYCHAIN" && ! -L "$KEYCHAIN" ]] \
|
||||
|| mac_nightly_die 'import-cert.sh did not import a signing identity into the work directory'
|
||||
mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \
|
||||
|| mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID"
|
||||
echo "==> DeckCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY"
|
||||
|
||||
# ---- the unsigned bundle ---------------------------------------------------------------------------
|
||||
mac_nightly_check_zip_entries "$INPUT"
|
||||
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
|
||||
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
|
||||
APP="$WORK/payload/$MAC_NIGHTLY_APP"
|
||||
|
||||
# ---- package.sh's signing and notarization, with a required Developer ID ---------------------------
|
||||
sign() {
|
||||
codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@"
|
||||
}
|
||||
|
||||
notarize() {
|
||||
local file="$1" out id status
|
||||
echo "==> notarizing $(basename "$file") (this can take a few minutes)"
|
||||
out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true
|
||||
echo "$out"
|
||||
id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)"
|
||||
status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)"
|
||||
if [[ "$status" != "Accepted" ]]; then
|
||||
if [[ -n "$id" ]]; then
|
||||
# Capped: the shared signer bounds a step's output at 256 KiB.
|
||||
xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true
|
||||
fi
|
||||
echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the
|
||||
# connection right after notarization (error 68), so retry the pair (package.sh).
|
||||
staple() {
|
||||
local file="$1" attempt
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then
|
||||
return
|
||||
fi
|
||||
if [[ "$attempt" = 5 ]]; then
|
||||
echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2
|
||||
sleep $((attempt * 20))
|
||||
done
|
||||
}
|
||||
|
||||
# Inside-out: the executable, then the bundle (no --deep on the final signature).
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/DeckCraft"
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
ditto -c -k --keepParent "$APP" "$WORK/notarize.zip"
|
||||
notarize "$WORK/notarize.zip"
|
||||
# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs.
|
||||
staple "$APP"
|
||||
|
||||
# ---- the final archive, checked as the Launcher unpacks it -----------------------------------------
|
||||
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip"
|
||||
ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check"
|
||||
mac_nightly_check_bundle "$WORK/check" "$VERSION"
|
||||
CHECK="$WORK/check/$MAC_NIGHTLY_APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$CHECK"
|
||||
mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \
|
||||
|| mac_nightly_die 'the signed bundle is not the required Developer ID signature'
|
||||
mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
|
||||
# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh).
|
||||
for attempt in 1 2 3 4 5; do
|
||||
assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true
|
||||
mac_nightly_check_assessment "$assessment" && break
|
||||
[[ "$attempt" = 5 ]] || sleep 10
|
||||
done
|
||||
printf '%s\n' "$assessment"
|
||||
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
|
||||
|
||||
nightly_publish_archive "$WORK/final.zip" "$OUTPUT"
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env bash
|
||||
# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version.
|
||||
# For a job without signing material (it refuses to run with any), after nightly-sign.sh:
|
||||
#
|
||||
# nightly-verify.sh --input /abs/deckcraft-<version>-macos-aarch64-nightly.zip --expect signed [--team ID]
|
||||
# nightly-verify.sh --input /abs/deckcraft-<version>-macos-aarch64-nightly.zip --expect unsigned
|
||||
#
|
||||
# Both: the archive holds only the GUI-only Nightly bundle with the exact DeckCraftVersion, unpacked
|
||||
# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else
|
||||
# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as
|
||||
# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature.
|
||||
# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the
|
||||
# Launcher's form `--launch-profile nightly-v1 --profile-root <fresh dir> --version` (the shared producer
|
||||
# smoke): each must exit 0 within 15 seconds, print exactly `DeckCraft <version> (nightly-v1)` and
|
||||
# write nothing to standard error.
|
||||
set -euo pipefail
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=nightly-lib.sh
|
||||
. "$HERE/nightly-lib.sh"
|
||||
|
||||
INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}"
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--input | --expect | --team)
|
||||
[[ $# -ge 2 ]] || mac_nightly_die "missing $1 value"
|
||||
case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac
|
||||
shift 2 ;;
|
||||
-h | --help) sed -n '2,15p' "$0"; exit 0 ;;
|
||||
*) mac_nightly_die "unsupported argument: $1" ;;
|
||||
esac
|
||||
done
|
||||
for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do
|
||||
[[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)"
|
||||
done
|
||||
[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned'
|
||||
[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)'
|
||||
[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file'
|
||||
VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name'
|
||||
[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac'
|
||||
|
||||
WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/deckcraft-nightly-verify.XXXXXX")"
|
||||
trap 'rm -rf -- "$WORK"' EXIT
|
||||
mac_nightly_check_zip_entries "$INPUT"
|
||||
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
|
||||
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
|
||||
APP="$WORK/payload/$MAC_NIGHTLY_APP"
|
||||
|
||||
if [[ "$EXPECT" == signed ]]; then
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \
|
||||
|| mac_nightly_die 'the bundle is not the required Developer ID signature'
|
||||
mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
|
||||
for attempt in 1 2 3 4 5; do
|
||||
assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true
|
||||
mac_nightly_check_assessment "$assessment" && break
|
||||
[[ "$attempt" = 5 ]] || sleep 10
|
||||
done
|
||||
printf '%s\n' "$assessment"
|
||||
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
|
||||
fi
|
||||
|
||||
# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say).
|
||||
query() {
|
||||
local out
|
||||
out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \
|
||||
/usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/DeckCraft" "$@" 2>"$WORK/stderr")" \
|
||||
|| mac_nightly_die "the version query ($*) failed or did not finish within 15 s"
|
||||
[[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")"
|
||||
[[ "$out" == "DeckCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not DeckCraft $VERSION (nightly-v1)"
|
||||
}
|
||||
mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile"
|
||||
query --version
|
||||
query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version
|
||||
echo "==> verified ($EXPECT): DeckCraft $VERSION (nightly-v1), plain and in the Launcher's profile form"
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material):
|
||||
#
|
||||
# $DIST/deckcraft-<version>-macos-aarch64-nightly.zip DeckCraft Nightly.app, unsigned
|
||||
#
|
||||
# Usage: packaging/macos/nightly.sh --arch aarch64
|
||||
#
|
||||
# Required env (nightly-common.sh): DECKCRAFT_BUILD_CHANNEL=nightly-v1, DECKCRAFT_VERSION,
|
||||
# DECKCRAFT_BUILD_SHA, DECKCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional.
|
||||
#
|
||||
# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI,
|
||||
# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query
|
||||
# runs on the signed bundle (nightly-verify.sh).
|
||||
set -euo pipefail
|
||||
ARCH=
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
|
||||
-h|--help) sed -n '2,13p' "$0"; exit 0 ;;
|
||||
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; }
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
. "$HERE/../nightly-common.sh"
|
||||
. "$HERE/nightly-lib.sh"
|
||||
nightly_refuse_signing_env
|
||||
nightly_init macos "$ARCH" aarch64-apple-darwin
|
||||
# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh).
|
||||
export MACOSX_DEPLOYMENT_TARGET=11.0
|
||||
OUTPUT="$DIST/deckcraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/DeckCraft"
|
||||
chmod 755 "$APP/Contents/MacOS/DeckCraft"
|
||||
cp "$ROOT/assets/app-icon/deckcraft-nightly.icns" "$APP/Contents/Resources/deckcraft-nightly.icns"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
--output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$DECKCRAFT_BUILD_SHA")
|
||||
plutil -lint "$APP/Contents/Info.plist"
|
||||
printf 'APPL????' >"$APP/Contents/PkgInfo"
|
||||
mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION"
|
||||
|
||||
# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them.
|
||||
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip"
|
||||
nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT"
|
||||
Executable
+69
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Nightly metadata: run from a private owned build cwd with a staged template.
|
||||
|
||||
All file arguments must stay beneath that cwd; this is not native/signing acceptance.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
# The shared helper location is fixed by this script, not by CLI file arguments.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from nightly_paths import OwnedBuildRoot
|
||||
|
||||
MAX_TEMPLATE_BYTES = 256 * 1024
|
||||
|
||||
IDENTIFIER = "ai.storyteller.deckcraft.nightly"
|
||||
ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations")
|
||||
VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z")
|
||||
|
||||
|
||||
def render(template: bytes, version: str, commit: str) -> bytes:
|
||||
match = VERSION.fullmatch(version)
|
||||
if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]:
|
||||
raise ValueError("exact prepared Nightly version and matching source commit are required")
|
||||
datetime.datetime.strptime(match[2], "%Y%m%d")
|
||||
data = plistlib.loads(template)
|
||||
if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL":
|
||||
raise ValueError("expected the app-owned application plist template")
|
||||
for key in ASSOCIATIONS:
|
||||
data.pop(key, None)
|
||||
data.update(
|
||||
CFBundleDisplayName="DeckCraft Nightly",
|
||||
CFBundleName="DeckCraft Nightly",
|
||||
CFBundleIdentifier=IDENTIFIER,
|
||||
CFBundleExecutable="DeckCraft",
|
||||
CFBundleIconFile="deckcraft-nightly",
|
||||
CFBundleShortVersionString=match[1],
|
||||
CFBundleVersion=match[1],
|
||||
DeckCraftVersion=version,
|
||||
DeckCraftBuildCommit=commit,
|
||||
)
|
||||
return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False)
|
||||
|
||||
|
||||
def write_plist(template: Path, destination: Path, version: str, commit: str) -> None:
|
||||
with OwnedBuildRoot() as root:
|
||||
content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit)
|
||||
with root.create(destination) as stream:
|
||||
stream.write(content)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--template", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--source-commit", required=True)
|
||||
args = parser.parse_args()
|
||||
write_plist(args.template, args.output, args.version, args.source_commit)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+202
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import runpy
|
||||
import sys
|
||||
from unittest import mock
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py")
|
||||
POLICY = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(POLICY)
|
||||
COMMIT = "a" * 40
|
||||
VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12]
|
||||
|
||||
|
||||
class NightlyMetadata(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.root = Path(self.directory.name).resolve()
|
||||
previous = Path.cwd()
|
||||
os.chdir(self.root)
|
||||
self.addCleanup(os.chdir, previous)
|
||||
self.template = self.root / "Info.plist.in"
|
||||
self.original = (HERE / "Info.plist.in").read_bytes()
|
||||
self.template.write_bytes(self.original)
|
||||
self.output = self.root / "Info.plist"
|
||||
|
||||
def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self):
|
||||
stable = plistlib.loads(self.original)
|
||||
stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}]
|
||||
prepared = plistlib.dumps(stable)
|
||||
self.template.write_bytes(prepared)
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
rendered = plistlib.loads(self.output.read_bytes())
|
||||
for key in POLICY.ASSOCIATIONS:
|
||||
self.assertNotIn(key, rendered)
|
||||
self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"])
|
||||
self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.deckcraft.nightly")
|
||||
self.assertEqual(rendered["CFBundleExecutable"], "DeckCraft")
|
||||
self.assertEqual(rendered["DeckCraftVersion"], VERSION)
|
||||
self.assertEqual(rendered["DeckCraftBuildCommit"], COMMIT)
|
||||
self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly."))
|
||||
for key in ("LSMinimumSystemVersion", "LSApplicationCategoryType", "NSHighResolutionCapable", "NSHumanReadableCopyright", "CFBundlePackageType"):
|
||||
self.assertEqual(rendered[key], stable[key])
|
||||
self.assertEqual(self.template.read_bytes(), prepared)
|
||||
self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original)
|
||||
|
||||
def test_bad_identity_or_template_refuses_before_creating_output(self):
|
||||
for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)):
|
||||
with self.subTest(version=version, commit=commit):
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, version, commit)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"}))
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_cli_writes_the_requested_identity_without_replacing_the_template(self):
|
||||
helper = HERE / "nightly_plist.py"
|
||||
argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT]
|
||||
with mock.patch.object(sys, "argv", argv):
|
||||
runpy.run_path(str(helper), run_name="__main__")
|
||||
result = plistlib.loads(self.output.read_bytes())
|
||||
self.assertEqual(result["DeckCraftVersion"], VERSION)
|
||||
self.assertEqual(result["DeckCraftBuildCommit"], COMMIT)
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
|
||||
def test_template_alias_or_nonfile_refuses_before_output(self):
|
||||
alias = self.root / "template-alias"
|
||||
alias.symlink_to(self.template)
|
||||
for template in (alias, self.root, self.root / "missing-template"):
|
||||
with self.subTest(template=template), self.assertRaises(ValueError):
|
||||
POLICY.write_plist(template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
|
||||
def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self):
|
||||
sentinel = b"generated replacement artifact"
|
||||
for disposition in ("owned", "missing", "replacement"):
|
||||
with self.subTest(disposition=disposition):
|
||||
if self.output.exists():
|
||||
self.output.unlink()
|
||||
|
||||
def fail_sync(_descriptor):
|
||||
# macOS/Linux allow unlink of an open file: exercise the real
|
||||
# cleanup ownership check, not a mocked inode comparison.
|
||||
if disposition != "owned":
|
||||
self.output.unlink()
|
||||
if disposition == "replacement":
|
||||
self.output.write_bytes(sentinel)
|
||||
raise OSError("generated fsync failure")
|
||||
|
||||
with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
if disposition == "replacement":
|
||||
self.assertEqual(self.output.read_bytes(), sentinel)
|
||||
else:
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
|
||||
def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self):
|
||||
sentinel = b"generated owned sentinel, not an existing app or user file"
|
||||
self.output.write_bytes(sentinel)
|
||||
with self.assertRaises(FileExistsError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertEqual(self.output.read_bytes(), sentinel)
|
||||
self.output.unlink()
|
||||
external = self.root / "sentinel"
|
||||
external.write_bytes(sentinel)
|
||||
self.output.symlink_to(external)
|
||||
with self.assertRaisesRegex(ValueError, "symlinks or aliases"):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertEqual(external.read_bytes(), sentinel)
|
||||
self.assertTrue(self.output.is_symlink())
|
||||
|
||||
|
||||
def test_template_outside_build_root_refuses_before_output(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
template = Path(external) / "Info.plist.in"
|
||||
template.write_bytes(self.original)
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(template.read_bytes(), self.original)
|
||||
|
||||
def test_output_outside_build_root_refuses_before_write(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
output = Path(external) / "Info.plist"
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, output, VERSION, COMMIT)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_parent_traversal_refuses_even_to_an_owned_sibling(self):
|
||||
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
|
||||
output = Path("..") / Path(external).name / "Info.plist"
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, output, VERSION, COMMIT)
|
||||
self.assertFalse((Path(external) / "Info.plist").exists())
|
||||
|
||||
def test_symlinked_output_parent_refuses(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
alias = self.root / "alias"
|
||||
alias.symlink_to(external, target_is_directory=True)
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT)
|
||||
self.assertFalse((Path(external) / "Info.plist").exists())
|
||||
|
||||
def test_template_read_is_bounded_before_output(self):
|
||||
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000}))
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_nonprivate_build_root_refuses(self):
|
||||
self.root.chmod(0o755)
|
||||
try:
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
finally:
|
||||
self.root.chmod(0o700)
|
||||
|
||||
|
||||
def test_output_keeps_normal_new_file_permissions_inside_private_root(self):
|
||||
previous = os.umask(0o022)
|
||||
try:
|
||||
reference = self.root / "reference"
|
||||
reference.write_bytes(b"generated ordinary output")
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
finally:
|
||||
os.umask(previous)
|
||||
self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777)
|
||||
|
||||
def test_open_parent_anchor_prevents_a_later_alias_redirect(self):
|
||||
parent = self.root / "stage"
|
||||
parent.mkdir()
|
||||
retained = self.root / "retained-stage"
|
||||
destination = parent / "Info.plist"
|
||||
original = POLICY.OwnedBuildRoot._parent
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
def swap_after_parent_open(root, path):
|
||||
descriptor, name = original(root, path)
|
||||
if Path(path) == destination:
|
||||
parent.rename(retained)
|
||||
parent.symlink_to(external, target_is_directory=True)
|
||||
return descriptor, name
|
||||
with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open):
|
||||
POLICY.write_plist(self.template, destination, VERSION, COMMIT)
|
||||
self.assertFalse((Path(external) / "Info.plist").exists())
|
||||
self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["DeckCraftVersion"], VERSION)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+425
@@ -0,0 +1,425 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
|
||||
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
|
||||
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
|
||||
real signature, notarization or Mac run."""
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import time
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py")
|
||||
PLIST = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(PLIST)
|
||||
COMMIT = "b" * 40
|
||||
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
|
||||
ASSET = f"deckcraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
APP = "DeckCraft Nightly.app"
|
||||
TEAM = "ABCDE12345"
|
||||
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SECRETS = {
|
||||
"APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(),
|
||||
"APPLE_CERTIFICATE_PASSWORD": "generated-fixture",
|
||||
"KEYCHAIN_PASSWORD": "generated-fixture",
|
||||
"APPLE_ID": "[email protected]",
|
||||
"APPLE_PASSWORD": "generated-fixture",
|
||||
"APPLE_TEAM_ID": TEAM,
|
||||
}
|
||||
|
||||
# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line.
|
||||
SHIM = r"""
|
||||
import json, os, plistlib, sys, zipfile
|
||||
from pathlib import Path
|
||||
name = Path(sys.argv[0]).name
|
||||
args = sys.argv[1:]
|
||||
with open(os.environ["SHIM_LOG"], "a") as log:
|
||||
log.write(json.dumps([name] + args) + "\n")
|
||||
team = os.environ.get("SHIM_TEAM", "")
|
||||
if name == "uname":
|
||||
print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin"))
|
||||
elif name == "lipo":
|
||||
print("arm64")
|
||||
elif name == "ditto":
|
||||
paths = [a for a in args if not a.startswith("-")]
|
||||
src, dst = paths
|
||||
if "-x" in args:
|
||||
with zipfile.ZipFile(src) as z:
|
||||
for info in z.infolist():
|
||||
target = Path(dst) / info.filename
|
||||
if info.is_dir():
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
continue
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(z.read(info))
|
||||
mode = (info.external_attr >> 16) & 0o777
|
||||
if mode:
|
||||
target.chmod(mode)
|
||||
else:
|
||||
root = Path(src)
|
||||
with zipfile.ZipFile(dst, "x") as z:
|
||||
for path in sorted([root] + list(root.rglob("*"))):
|
||||
arc = (Path(root.name) / path.relative_to(root)).as_posix()
|
||||
if path.is_dir():
|
||||
z.writestr(zipfile.ZipInfo(arc + "/"), b"")
|
||||
else:
|
||||
info = zipfile.ZipInfo(arc)
|
||||
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
|
||||
z.writestr(info, path.read_bytes())
|
||||
elif name == "plutil":
|
||||
if args[0] == "-lint":
|
||||
sys.exit(0)
|
||||
key, fmt, source = args[1], args[2], args[-1]
|
||||
data = sys.stdin.read() if source == "-" else Path(source).read_bytes()
|
||||
value = json.loads(data) if source == "-" else plistlib.loads(data)
|
||||
if key not in value:
|
||||
sys.exit(1)
|
||||
print(value[key] if fmt == "raw" else "<present/>")
|
||||
elif name == "security":
|
||||
verb = args[0]
|
||||
if verb == "create-keychain":
|
||||
Path(args[-1]).write_bytes(b"keychain")
|
||||
elif verb == "find-identity":
|
||||
print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team))
|
||||
print(" 1 valid identities found")
|
||||
elif verb == "delete-keychain":
|
||||
Path(args[-1]).unlink()
|
||||
elif name == "codesign":
|
||||
target = Path(args[-1])
|
||||
if "--sign" in args and target.suffix == ".app":
|
||||
(target / "Contents/_CodeSignature").mkdir(exist_ok=True)
|
||||
(target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed")
|
||||
if "-d" in args:
|
||||
sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.deckcraft.nightly\n"
|
||||
"CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n"
|
||||
"Authority=Developer ID Application: Generated Fixture (%s)\n"
|
||||
"Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team))
|
||||
elif name == "xcrun":
|
||||
if args[:2] == ["notarytool", "submit"]:
|
||||
print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")}))
|
||||
elif args[:2] == ["stapler", "staple"]:
|
||||
(Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket")
|
||||
elif args[:2] == ["stapler", "validate"]:
|
||||
sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1)
|
||||
elif name == "spctl":
|
||||
sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1])
|
||||
elif name == "cargo":
|
||||
sys.exit(1)
|
||||
# sleep: the retry waits pass at once.
|
||||
"""
|
||||
|
||||
TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep")
|
||||
|
||||
|
||||
class Fixture:
|
||||
def __init__(self, test):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
test.addCleanup(self.directory.cleanup)
|
||||
self.root = Path(self.directory.name).resolve()
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
shim = self.bin / "shim.py"
|
||||
shim.write_text(SHIM)
|
||||
for tool in TOOLS:
|
||||
path = self.bin / tool
|
||||
path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n")
|
||||
path.chmod(0o755)
|
||||
self.log = self.root / "tools.log"
|
||||
self.ran = self.root / "payload-ran"
|
||||
self.temp = self.root / "runner-temp"
|
||||
self.temp.mkdir()
|
||||
self.dist = self.root / "unsigned"
|
||||
self.dist.mkdir()
|
||||
self.signed = self.root / "signed"
|
||||
self.signed.mkdir()
|
||||
self.input = self.dist / ASSET
|
||||
self.output = self.signed / ASSET
|
||||
# Every script runs from a directory with modules a Python helper must not import (-I).
|
||||
self.cwd = self.root / "cwd"
|
||||
self.cwd.mkdir()
|
||||
self.hijacked = self.root / "hijacked"
|
||||
for module in ("shutil", "zipfile", "stat"):
|
||||
(self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n")
|
||||
|
||||
def add_entry(self, info, data=b""):
|
||||
"""Append one raw entry to the input archive."""
|
||||
with zipfile.ZipFile(self.input, "a") as z:
|
||||
z.writestr(info, data)
|
||||
|
||||
def bundle(self, version=VERSION, extra=None, gui=None):
|
||||
"""The archive nightly.sh makes: the real template through the real plist helper."""
|
||||
stage = self.root / "stage"
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
app = stage / APP
|
||||
(app / "Contents/MacOS").mkdir(parents=True)
|
||||
(app / "Contents/Resources").mkdir()
|
||||
exe = app / "Contents/MacOS/DeckCraft"
|
||||
exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'DeckCraft {version} (nightly-v1)'\n")
|
||||
exe.chmod(0o755)
|
||||
(app / "Contents/Resources/deckcraft-nightly.icns").write_bytes(b"generated icon")
|
||||
rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT)
|
||||
(app / "Contents/Info.plist").write_bytes(rendered)
|
||||
for relative, data in (extra or {}).items():
|
||||
(app / relative).write_bytes(data)
|
||||
(app / relative).chmod(0o755)
|
||||
if self.input.exists():
|
||||
self.input.unlink()
|
||||
with zipfile.ZipFile(self.input, "x") as z:
|
||||
for path in sorted([app] + list(app.rglob("*"))):
|
||||
arc = (Path(APP) / path.relative_to(app)).as_posix()
|
||||
info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else ""))
|
||||
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
|
||||
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
|
||||
return self.input
|
||||
|
||||
def env(self, **changes):
|
||||
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
|
||||
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
|
||||
env.update(changes)
|
||||
return {key: value for key, value in env.items() if value is not None}
|
||||
|
||||
def run(self, script, *args, **env):
|
||||
if self.log.exists():
|
||||
self.log.unlink()
|
||||
return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
|
||||
|
||||
def sign(self, **env):
|
||||
return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env)
|
||||
|
||||
def calls(self):
|
||||
if not self.log.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
|
||||
|
||||
def lib(function, *args):
|
||||
"""Run one nightly-lib.sh function; returns (exit status, stdout)."""
|
||||
script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"'
|
||||
result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
return result.returncode, result.stdout.strip()
|
||||
|
||||
|
||||
DETAILS = (f"Identifier=ai.storyteller.deckcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n"
|
||||
f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n"
|
||||
f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n")
|
||||
|
||||
|
||||
class Checks(unittest.TestCase):
|
||||
def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self):
|
||||
self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION))
|
||||
for name in (f"deckcraft-0.23.1-macos-aarch64.zip", f"deckcraft-{VERSION}-macos-universal-nightly.zip",
|
||||
f"deckcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET):
|
||||
with self.subTest(name=name):
|
||||
self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0)
|
||||
|
||||
def test_signature_needs_every_part_of_the_developer_id_signature(self):
|
||||
self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0)
|
||||
for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"),
|
||||
DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"),
|
||||
"Identifier=deckcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n",
|
||||
DETAILS.replace("ai.storyteller.deckcraft.nightly", "ai.storyteller.deckcraft"),
|
||||
DETAILS.replace("ai.storyteller.deckcraft.nightly", "aiXstorytellerXdeckcraftXnightly")):
|
||||
with self.subTest(broken=broken):
|
||||
self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0)
|
||||
self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team")
|
||||
|
||||
def test_gatekeeper_must_accept_the_bundle_as_notarized(self):
|
||||
self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0)
|
||||
for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"):
|
||||
with self.subTest(text=text):
|
||||
self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0)
|
||||
|
||||
def test_the_imported_identity_must_be_a_developer_id_of_the_team(self):
|
||||
line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"'
|
||||
self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0)
|
||||
self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0)
|
||||
self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0)
|
||||
|
||||
|
||||
class Sign(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.f = Fixture(self)
|
||||
self.f.bundle()
|
||||
self.unsigned = self.f.input.read_bytes()
|
||||
|
||||
def assert_refused_untouched(self, result, signed=False):
|
||||
self.assertNotEqual(result.returncode, 0, result.stdout)
|
||||
self.assertFalse(self.f.output.exists())
|
||||
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
|
||||
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
|
||||
names = [call[0] for call in self.f.calls()]
|
||||
self.assertNotIn("cargo", names)
|
||||
if not signed:
|
||||
self.assertNotIn("codesign", names)
|
||||
self.assertNotIn("xcrun", names)
|
||||
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
|
||||
|
||||
def test_signs_notarizes_and_staples_without_running_the_payload(self):
|
||||
result = self.f.sign()
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets")
|
||||
calls = self.f.calls()
|
||||
names = [call[0] for call in calls]
|
||||
self.assertNotIn("cargo", names)
|
||||
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
|
||||
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
|
||||
signs = [call for call in calls if call[0] == "codesign" and "--sign" in call]
|
||||
self.assertEqual([Path(call[-1]).name for call in signs], ["DeckCraft", APP], "inside-out: executable, then bundle")
|
||||
for call in signs:
|
||||
for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY):
|
||||
self.assertIn(flag, call)
|
||||
order = [" ".join(call[:3]) for call in calls]
|
||||
submit = order.index("xcrun notarytool submit")
|
||||
staple = order.index("xcrun stapler staple")
|
||||
self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit)
|
||||
self.assertLess(submit, staple)
|
||||
final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1]
|
||||
self.assertLess(staple, final, "the final archive carries the stapled ticket")
|
||||
self.assertIn("--noextattr", calls[final])
|
||||
self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls])
|
||||
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
|
||||
with zipfile.ZipFile(self.f.output) as z:
|
||||
names = set(z.namelist())
|
||||
self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle")
|
||||
self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names)
|
||||
self.assertTrue(all(name.startswith(APP) for name in names))
|
||||
mode = z.getinfo(f"{APP}/Contents/MacOS/DeckCraft").external_attr >> 16
|
||||
self.assertTrue(mode & stat.S_IXUSR)
|
||||
|
||||
def test_every_signing_and_notarization_secret_is_required(self):
|
||||
for name in SECRETS:
|
||||
with self.subTest(missing=name):
|
||||
self.assert_refused_untouched(self.f.sign(**{name: None}))
|
||||
self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete")
|
||||
self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999"))
|
||||
self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team"))
|
||||
|
||||
def test_refuses_another_team_s_identity(self):
|
||||
self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999"))
|
||||
|
||||
def test_never_replaces_an_output_or_renames_the_asset(self):
|
||||
self.f.output.write_bytes(b"generated existing artifact")
|
||||
result = self.f.sign()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact")
|
||||
self.f.output.unlink()
|
||||
renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip")
|
||||
self.assertNotEqual(renamed.returncode, 0)
|
||||
relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output)
|
||||
self.assertNotEqual(relative.returncode, 0)
|
||||
self.assertEqual(list(self.f.signed.iterdir()), [])
|
||||
|
||||
def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self):
|
||||
cases = {
|
||||
"cli": dict(extra={"Contents/MacOS/deckcraft-cli": b"generated cli"}),
|
||||
"version": dict(version=VERSION.replace("4567", "4568")),
|
||||
}
|
||||
for label, change in cases.items():
|
||||
with self.subTest(label=label):
|
||||
self.f.bundle(**change)
|
||||
self.unsigned = self.f.input.read_bytes()
|
||||
self.assert_refused_untouched(self.f.sign())
|
||||
|
||||
def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self):
|
||||
link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link")
|
||||
link.external_attr = (stat.S_IFLNK | 0o777) << 16
|
||||
fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo")
|
||||
fifo.external_attr = (stat.S_IFIFO | 0o644) << 16
|
||||
for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")),
|
||||
("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))):
|
||||
with self.subTest(label=label):
|
||||
self.f.bundle()
|
||||
self.f.add_entry(info, b"/etc/passwd")
|
||||
self.unsigned = self.f.input.read_bytes()
|
||||
result = self.f.sign()
|
||||
self.assert_refused_untouched(result)
|
||||
self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking")
|
||||
|
||||
def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self):
|
||||
result = self.f.sign(SHIM_NOTARY="Invalid")
|
||||
self.assert_refused_untouched(result, signed=True)
|
||||
self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()])
|
||||
self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()])
|
||||
|
||||
|
||||
class Verify(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.f = Fixture(self)
|
||||
|
||||
def verify(self, *args, **env):
|
||||
return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env)
|
||||
|
||||
def test_asks_the_gui_its_version_with_an_empty_environment(self):
|
||||
self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'DeckCraft {VERSION} (nightly-v1)'\n")
|
||||
result = self.verify("--expect", "unsigned", INHERITED="generated")
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
self.f.bundle(gui="#!/bin/sh\necho 'DeckCraft 0.23.1 (stable)'\n")
|
||||
self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0)
|
||||
|
||||
def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self):
|
||||
answer = f"echo 'DeckCraft {VERSION} (nightly-v1)'"
|
||||
# The shared producer smoke's exact form, with a fresh profile directory.
|
||||
exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n'
|
||||
' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n'
|
||||
f'fi\n{answer}\n')
|
||||
self.f.bundle(gui=exact)
|
||||
result = self.verify("--expect", "unsigned")
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n'
|
||||
self.f.bundle(gui=hangs)
|
||||
started = time.monotonic()
|
||||
result = self.verify("--expect", "unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("within 15 s", result.stdout)
|
||||
self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for")
|
||||
noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n'
|
||||
self.f.bundle(gui=noisy)
|
||||
result = self.verify("--expect", "unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("standard error", result.stdout)
|
||||
|
||||
def test_a_signed_check_needs_the_signature_ticket_and_team(self):
|
||||
self.f.bundle()
|
||||
self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against")
|
||||
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket")
|
||||
self.f.bundle(extra={"Contents/CodeResources": b"ticket"})
|
||||
self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0)
|
||||
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0)
|
||||
|
||||
def test_refuses_to_run_the_payload_beside_signing_material(self):
|
||||
self.f.bundle()
|
||||
for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"):
|
||||
with self.subTest(name=name):
|
||||
result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned",
|
||||
**{**{key: None for key in SECRETS}, name: "generated"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.f.ran.exists())
|
||||
self.assertEqual(self.f.calls(), [])
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_compilation_refuses_signing_material_before_building(self):
|
||||
f = Fixture(self)
|
||||
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
|
||||
with self.subTest(name=name):
|
||||
result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"},
|
||||
DECKCRAFT_BUILD_CHANNEL="nightly-v1", DECKCRAFT_VERSION=VERSION)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn(name, result.stdout)
|
||||
self.assertNotIn("cargo", [call[0] for call in f.calls()])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Flat Linux archive policy, invoked from its private owned build cwd.
|
||||
|
||||
The stage and archive must both remain under that independently chosen root.
|
||||
No native build, platform signing, or malicious-same-UID sandbox is implied.
|
||||
"""
|
||||
import grp
|
||||
import gzip
|
||||
import os
|
||||
import pathlib
|
||||
import pwd
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
from nightly_paths import OwnedBuildRoot
|
||||
|
||||
APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"}
|
||||
MAX_MEMBER_BYTES = 512 * 1024 * 1024
|
||||
MAX_TOTAL_BYTES = 1024 * 1024 * 1024
|
||||
MAX_MEMBERS = 128
|
||||
|
||||
|
||||
def notice(name):
|
||||
return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None
|
||||
|
||||
|
||||
def checked_entries(root, stage):
|
||||
entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name)
|
||||
folded = set()
|
||||
total = 0
|
||||
for entry in entries:
|
||||
name = entry.name
|
||||
# `deckcraft` is the launcher and `deckcraft-bin` the GUI it starts (nightly.sh); the icon
|
||||
# and the notices are the rest of the flat archive.
|
||||
if name not in {"deckcraft", "deckcraft-bin", "deckcraft-nightly.png"} and not notice(name):
|
||||
raise ValueError(f"unexpected nightly member: {name}")
|
||||
if len(name.encode("utf-8")) > 100:
|
||||
raise ValueError(f"nightly member must be a short regular file: {name}")
|
||||
with root.reader(entry, MAX_MEMBER_BYTES) as stream:
|
||||
total += os.fstat(stream.fileno()).st_size
|
||||
if total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("nightly stage exceeds its read bound")
|
||||
if name.casefold() in folded:
|
||||
raise ValueError(f"case-colliding nightly member: {name}")
|
||||
folded.add(name.casefold())
|
||||
required = {"deckcraft", "deckcraft-bin", "deckcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
|
||||
if not required.issubset({item.name for item in entries}):
|
||||
raise ValueError("required GUI/icon/notices missing")
|
||||
return entries
|
||||
|
||||
|
||||
def member_info(stage_root, name, incoming):
|
||||
"""Header for one stage file, built from the file this run opened rather than from the archive.
|
||||
|
||||
Members are flat names that resolve directly inside the stage they came from.
|
||||
"""
|
||||
if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."):
|
||||
raise ValueError(f"nightly member name must be a flat file name: {name}")
|
||||
destination = os.path.realpath(os.path.join(stage_root, name))
|
||||
if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root:
|
||||
raise ValueError(f"nightly member resolves outside its stage: {name}")
|
||||
status = os.fstat(incoming.fileno())
|
||||
if not stat.S_ISREG(status.st_mode):
|
||||
raise ValueError(f"nightly member must be a regular file: {name}")
|
||||
# The same fields TarFile.gettarinfo records for a regular file.
|
||||
# The header keeps the validated stage name, not the resolved one: a stage symlink must
|
||||
# never rename a member or leave a required name out of the archive.
|
||||
info = tarfile.TarInfo(name)
|
||||
info.type = tarfile.REGTYPE
|
||||
info.mode = stat.S_IMODE(status.st_mode)
|
||||
info.uid, info.gid = status.st_uid, status.st_gid
|
||||
info.size = status.st_size
|
||||
info.mtime = status.st_mtime
|
||||
try:
|
||||
info.uname = pwd.getpwuid(status.st_uid).pw_name
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
info.gname = grp.getgrgid(status.st_gid).gr_name
|
||||
except KeyError:
|
||||
pass
|
||||
return info
|
||||
|
||||
|
||||
def verify_headers(root, output):
|
||||
# Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader.
|
||||
total = 0
|
||||
count = 0
|
||||
with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream:
|
||||
while True:
|
||||
header = stream.read(512)
|
||||
if header == b"\0" * 512:
|
||||
break
|
||||
if len(header) != 512 or header[156:157] not in {b"0", b"\0"}:
|
||||
raise ValueError("non-ordinary TAR record was emitted")
|
||||
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
|
||||
count += 1
|
||||
total += size
|
||||
if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("archive exceeds its bounded member budget")
|
||||
remaining = ((size + 511) // 512) * 512
|
||||
while remaining:
|
||||
chunk = stream.read(min(remaining, 1024 * 1024))
|
||||
if not chunk:
|
||||
raise ValueError("truncated TAR member")
|
||||
remaining -= len(chunk)
|
||||
|
||||
|
||||
def linux_archive(stage, output):
|
||||
with OwnedBuildRoot() as root:
|
||||
entries = checked_entries(root, stage)
|
||||
stage_root = os.path.realpath(os.path.join(root.directory, stage))
|
||||
total = 0
|
||||
with root.create(output) as outgoing:
|
||||
with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive:
|
||||
for entry in entries:
|
||||
with root.reader(entry, MAX_MEMBER_BYTES) as incoming:
|
||||
info = member_info(stage_root, entry.name, incoming)
|
||||
total += info.size
|
||||
if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("nightly stage grew beyond its read bound")
|
||||
archive.addfile(info, incoming)
|
||||
outgoing.flush()
|
||||
os.fsync(outgoing.fileno())
|
||||
verify_headers(root, output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 4 or sys.argv[1] != "linux":
|
||||
raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)")
|
||||
linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3]))
|
||||
@@ -0,0 +1,95 @@
|
||||
# shellcheck shell=bash
|
||||
# Shared setup for app-owned native nightly archives; stable packaging does not source this file.
|
||||
|
||||
nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
|
||||
|
||||
nightly_init() {
|
||||
local os="$1" arch="$2" target="$3" date_digits
|
||||
[[ "${DECKCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'DECKCRAFT_BUILD_CHANNEL must be nightly-v1'
|
||||
[[ "${DECKCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required'
|
||||
[[ "${DECKCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required'
|
||||
[[ "${DECKCRAFT_VERSION##*.g}" == "${DECKCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch'
|
||||
[[ "${DECKCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required'
|
||||
date_digits="${DECKCRAFT_VERSION#*-nightly.}"
|
||||
date_digits="${date_digits%%.*}"
|
||||
[[ "${DECKCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch'
|
||||
[[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required'
|
||||
[[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required'
|
||||
[[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal'
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DECKCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit'
|
||||
[[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source'
|
||||
if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then
|
||||
nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory'
|
||||
fi
|
||||
# common.sh retains the established notice copier. Required values above prohibit its stable fallbacks.
|
||||
# shellcheck source=common.sh
|
||||
. "$ROOT/packaging/common.sh"
|
||||
export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch"
|
||||
NIGHTLY_RUST_TARGET="$target"
|
||||
mkdir -p "$CARGO_TARGET_DIR"
|
||||
NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")"
|
||||
trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT
|
||||
}
|
||||
|
||||
# Compile only: macOS runs the version query after signing.
|
||||
nightly_compile_gui() {
|
||||
# The guard sits here as well as in the entrypoints: no caller may compile with signing material.
|
||||
nightly_refuse_signing_env
|
||||
(cd "$ROOT" && cargo build --release --locked -p deckcraft --target "$NIGHTLY_RUST_TARGET")
|
||||
NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/deckcraft"
|
||||
[[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable'
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DECKCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build'
|
||||
}
|
||||
|
||||
nightly_build_gui() {
|
||||
nightly_compile_gui
|
||||
local actual
|
||||
actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed'
|
||||
# The desktop's version query answers `DeckCraft <version> (nightly-v1)`; the exact line, not a
|
||||
# prefix, so a stable or mismatched build cannot pass.
|
||||
[[ "$actual" == "DeckCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity'
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DECKCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query'
|
||||
}
|
||||
|
||||
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
|
||||
nightly_refuse_signing_env() {
|
||||
local name
|
||||
# The signing names release.yml passes, for every platform, and import-cert.sh's outputs.
|
||||
for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \
|
||||
MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \
|
||||
AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do
|
||||
[[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step"
|
||||
done
|
||||
}
|
||||
|
||||
nightly_copy_notices() {
|
||||
local destination="$1" required
|
||||
for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do
|
||||
[[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required"
|
||||
done
|
||||
copy_docs "$destination"
|
||||
cp "$ROOT/ATTRIBUTION.md" "$destination/"
|
||||
}
|
||||
|
||||
nightly_publish_archive() {
|
||||
# Exclusive creation: never replace an existing artifact, even if another writer raced the preflight.
|
||||
python3 -I - "$1" "$2" <<'PY'
|
||||
import os, shutil, sys
|
||||
source, destination = sys.argv[1:]
|
||||
created = False
|
||||
try:
|
||||
# Open the input first: a missing source must not leave an empty final artifact.
|
||||
with open(source, 'rb') as incoming:
|
||||
with open(destination, 'xb') as output:
|
||||
created = True
|
||||
shutil.copyfileobj(incoming, output, length=1024 * 1024)
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
except BaseException:
|
||||
if created:
|
||||
os.unlink(destination)
|
||||
raise
|
||||
PY
|
||||
printf 'Nightly artifact: %s\n' "$2"
|
||||
}
|
||||
Executable
+356
@@ -0,0 +1,356 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local regression checks for DeckCraft nightly workflow and policy contracts."""
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
# Each platform's one trust field in policy v3, and the public stable identity it must name.
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
"CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"),
|
||||
"linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"),
|
||||
"macos-aarch64": ("apple_team_id", "DJ6XS33FX8"),
|
||||
}
|
||||
|
||||
# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot.
|
||||
# Update by PR, in the caller and the policy, when the team changes.
|
||||
RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"]
|
||||
|
||||
|
||||
def assert_nightly_serialization(source):
|
||||
"""Fail closed unless this app's plain root concurrency block retains its contract."""
|
||||
lines = source.splitlines()
|
||||
roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")]
|
||||
if len(roots) != 1 or lines[roots[0]] != "concurrency:":
|
||||
raise ValueError("one plain root concurrency block is required")
|
||||
values = {}
|
||||
for line in lines[roots[0] + 1:]:
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
if not line[0].isspace():
|
||||
break
|
||||
row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line)
|
||||
if row is None or row[1] in values:
|
||||
raise ValueError("malformed or duplicate nightly concurrency entry")
|
||||
values[row[1]] = row[2].rstrip()
|
||||
if values != {"group": "deckcraft-nightly-release", "cancel-in-progress": "false"}:
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def job_conditions(jobs):
|
||||
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
|
||||
lines = jobs.splitlines()
|
||||
found = []
|
||||
for index, line in enumerate(lines):
|
||||
head = re.fullmatch(r" if:(?: (.*))?", line)
|
||||
if head is None:
|
||||
continue
|
||||
value = (head[1] or "").strip()
|
||||
continuation = []
|
||||
for follow in lines[index + 1:]:
|
||||
if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4:
|
||||
break
|
||||
continuation.append(follow.strip())
|
||||
indicator = value if re.fullmatch(r"[>|][+-]?", value) else None
|
||||
parts = continuation if indicator else [value] + continuation
|
||||
found.append((indicator, " ".join(part for part in parts if part)))
|
||||
return found
|
||||
|
||||
|
||||
def producer_platforms(source):
|
||||
"""Read the one producer job's literal platform list; a narrow source guard, not YAML."""
|
||||
rows = re.findall(r"(?m)^ platforms: (.*)$", source)
|
||||
if len(rows) != 1:
|
||||
raise ValueError("exactly one producer platform list is required")
|
||||
literal = re.fullmatch(r"'(\[[^']*\])'", rows[0])
|
||||
if literal is None:
|
||||
raise ValueError("the platform list must be one single-quoted literal")
|
||||
platforms = json.loads(literal[1])
|
||||
if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]:
|
||||
raise ValueError("the platform list must be compact JSON")
|
||||
if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS):
|
||||
raise ValueError("platforms must be distinct known nightly targets")
|
||||
if "windows-x86_64" not in platforms:
|
||||
raise ValueError("the Windows row stays in the producer")
|
||||
return platforms
|
||||
|
||||
|
||||
def reviewed_manual_actors(caller_source, policy):
|
||||
"""The one reviewed manual-actor list, identical in the producer caller and the policy."""
|
||||
rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source)
|
||||
if len(rows) != 1:
|
||||
raise ValueError("exactly one literal manual-actors list is required")
|
||||
caller = json.loads(rows[0])
|
||||
if caller != policy["manual_actors"]:
|
||||
raise ValueError("caller and policy must grant the same actors in the same order")
|
||||
if caller != RELEASE_MANAGERS:
|
||||
raise ValueError("manual actors must be exactly the reviewed release managers")
|
||||
if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller):
|
||||
raise ValueError("manual actors must be distinct and sorted case-insensitively")
|
||||
if set(caller) & {login for login in policy["automatic_signer_actors"]}:
|
||||
raise ValueError("manual and automatic actors overlap")
|
||||
return caller
|
||||
|
||||
|
||||
def caller_pin(name):
|
||||
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0]
|
||||
|
||||
|
||||
class TrustedSourcePreparation(unittest.TestCase):
|
||||
def test_one_producer_and_one_signer_job_carry_every_platform(self):
|
||||
for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")):
|
||||
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job],
|
||||
"a platform is a list entry, not a separately activatable job")
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms")
|
||||
|
||||
def test_malformed_or_narrowed_platform_lists_are_rejected(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'"
|
||||
self.assertIn(current, source)
|
||||
for new in ("platforms: '[\"linux-x86_64\"]'",
|
||||
"platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'",
|
||||
"platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'",
|
||||
"platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'",
|
||||
"platforms: '[\"windows-x86_64\",\"linux-arm64\"]'",
|
||||
"platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'",
|
||||
"platforms: [\"windows-x86_64\",\"linux-x86_64\"]",
|
||||
"platforms: ${{ vars.NIGHTLY_PLATFORMS }}",
|
||||
"platforms: '{\"windows-x86_64\":1}'",
|
||||
current + "\n " + current):
|
||||
with self.subTest(change=new), self.assertRaises(ValueError):
|
||||
producer_platforms(source.replace(current, new))
|
||||
with self.assertRaises(ValueError):
|
||||
producer_platforms(source.replace(" " + current + "\n", ""))
|
||||
|
||||
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
|
||||
for name in ("nightly.yml", "nightly-sign.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
expected = NightlyEnabledCallers.GUARDS[name]
|
||||
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
|
||||
for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"):
|
||||
jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1]
|
||||
with self.subTest(workflow=name, replacement=replacement[-30:]):
|
||||
(indicator, expression), = job_conditions(jobs)
|
||||
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
|
||||
|
||||
def test_no_nightly_schedule_is_registered(self):
|
||||
for name, event in (("nightly.yml", "workflow_dispatch"),
|
||||
("nightly-sign.yml", "workflow_dispatch")):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
|
||||
triggers = [line for line in events.splitlines() if line.startswith(" ")
|
||||
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
|
||||
|
||||
def test_signer_serialization_contract_is_enforced(self):
|
||||
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
|
||||
|
||||
def test_the_producer_declares_no_serialization_of_its_own(self):
|
||||
# Only the signer serializes, because one protected release at a time is what the policy
|
||||
# needs. The producer is a manual, stateless dispatch, so a concurrency block there would
|
||||
# be a second, unreviewed gate; this keeps one from slipping in unnoticed.
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
executable = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#"))
|
||||
self.assertNotRegex(executable, r"(?m)^\s*concurrency:")
|
||||
self.assertNotIn("cancel-in-progress", executable)
|
||||
|
||||
def test_weakened_or_malformed_serialization_is_rejected(self):
|
||||
source = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
for old, new in (
|
||||
("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"),
|
||||
("cancel-in-progress: false", "cancel-in-progress: true"),
|
||||
("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"),
|
||||
("cancel-in-progress: false\n", ""),
|
||||
("group: deckcraft-nightly-release", "group: ${{ github.run_id }}"),
|
||||
("group: deckcraft-nightly-release", "group: release-${{ github.ref }}"),
|
||||
("concurrency:\n", "concurrency: ${{ github.run_id }}\n"),
|
||||
("concurrency:\n", " concurrency:\n"),
|
||||
):
|
||||
with self.subTest(change=new), self.assertRaises(ValueError):
|
||||
assert_nightly_serialization(source.replace(old, new))
|
||||
|
||||
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
|
||||
for name in ("nightly.yml", "nightly-sign.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
executable = "\n".join(line for line in source.splitlines()
|
||||
if not line.lstrip().startswith("#"))
|
||||
with self.subTest(workflow=name):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
|
||||
def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self):
|
||||
pins = set()
|
||||
for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/"
|
||||
+ re.escape(callee) + r"@(\S+)$", source)
|
||||
tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source)
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(len(uses), 1)
|
||||
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
|
||||
pins.update(uses)
|
||||
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
|
||||
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
|
||||
|
||||
|
||||
class NightlyEnabledCallers(unittest.TestCase):
|
||||
"""Producer and signer run only in their exact context, for the reviewed manual actor."""
|
||||
|
||||
GUARDS = {
|
||||
"nightly.yml": "github.repository == 'storytold/deckcraft' && github.ref == 'refs/heads/main' && "
|
||||
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
|
||||
"github.event_name == 'workflow_dispatch')",
|
||||
"nightly-sign.yml": "github.repository == 'storytold/deckcraft' && github.event_name == 'workflow_dispatch' && "
|
||||
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
|
||||
}
|
||||
|
||||
def test_enabled_jobs_keep_exact_context_guards(self):
|
||||
for name, expected in self.GUARDS.items():
|
||||
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
|
||||
guards = job_conditions(jobs)
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(len(guards), 1)
|
||||
indicator, expression = guards[0]
|
||||
self.assertEqual(indicator, ">-")
|
||||
self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review")
|
||||
|
||||
def test_manual_actors_are_the_release_managers_in_caller_and_policy(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
|
||||
def test_an_actor_outside_the_release_managers_is_refused(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":"))
|
||||
widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower)
|
||||
for change in ("caller", "policy", "both", "order", "case"):
|
||||
mutated_source, mutated_policy = source, copy.deepcopy(policy)
|
||||
if change in ("caller", "both"):
|
||||
mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":")))
|
||||
if change in ("policy", "both"):
|
||||
mutated_policy["manual_actors"] = widened
|
||||
if change == "order":
|
||||
mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS))
|
||||
if change == "case":
|
||||
mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS]
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
reviewed_manual_actors(mutated_source, mutated_policy)
|
||||
|
||||
|
||||
class NightlyInstalledPolicy(unittest.TestCase):
|
||||
"""The installed v3 policy matches the callers, the repository and its documented sources."""
|
||||
|
||||
def setUp(self):
|
||||
self.assertFalse(INSTALLED_POLICY.is_symlink())
|
||||
self.policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
|
||||
def test_exact_v3_fields_and_repository_identity(self):
|
||||
expected = {"schema", "repository", "repository_id", "producer_workflow_id",
|
||||
"producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref",
|
||||
"signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors",
|
||||
"automatic_signer_actors", "max_age_seconds", "candidate_policy",
|
||||
"max_artifact_bytes", "platforms"}
|
||||
self.assertEqual(set(self.policy), expected)
|
||||
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
|
||||
self.assertEqual(self.policy["repository"], "storytold/deckcraft")
|
||||
self.assertEqual(self.policy["release_branch"], "release")
|
||||
self.assertIs(type(self.policy["repository_id"]), int)
|
||||
self.assertGreater(self.policy["repository_id"], 0)
|
||||
# producer_workflow_id is null until nightly.yml is registered on main; once set, it must be a positive int.
|
||||
if self.policy["producer_workflow_id"] is not None:
|
||||
self.assertIs(type(self.policy["producer_workflow_id"]), int)
|
||||
self.assertGreater(self.policy["producer_workflow_id"], 0)
|
||||
self.assertNotEqual(self.policy["producer_workflow_id"],
|
||||
self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"],
|
||||
"the producer is not its own quality workflow")
|
||||
|
||||
def test_paths_and_tooling_match_the_callers(self):
|
||||
pin = caller_pin("nightly.yml")
|
||||
self.assertEqual(caller_pin("nightly-sign.yml"), pin)
|
||||
self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml")
|
||||
self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml")
|
||||
self.assertEqual(self.policy["producer_tooling_revision"], pin)
|
||||
self.assertEqual(self.policy["signer_tooling_revision"], pin)
|
||||
self.assertEqual(self.policy["producer_workflow_ref"],
|
||||
"storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin)
|
||||
|
||||
def test_platforms_and_trust_anchors(self):
|
||||
built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text())
|
||||
self.assertEqual(built, list(NIGHTLY_PLATFORMS))
|
||||
self.assertEqual(set(self.policy["platforms"]), set(built))
|
||||
for platform, (field, value) in NIGHTLY_TRUST.items():
|
||||
row = self.policy["platforms"][platform]
|
||||
with self.subTest(platform=platform):
|
||||
self.assertEqual(set(row), {"unsigned_artifact_name", "trust"})
|
||||
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}")
|
||||
self.assertEqual(row["trust"], {field: value})
|
||||
|
||||
def test_bounds(self):
|
||||
self.assertIs(type(self.policy["max_age_seconds"]), int)
|
||||
self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800)
|
||||
self.assertIs(type(self.policy["max_artifact_bytes"]), int)
|
||||
self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3)
|
||||
|
||||
def test_candidate_workflows_run_on_every_main_push(self):
|
||||
candidate = self.policy["candidate_policy"]
|
||||
self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"})
|
||||
self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3")
|
||||
self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/deckcraft", "main"))
|
||||
self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128)
|
||||
rows = candidate["required_workflows"]
|
||||
self.assertTrue(rows)
|
||||
for row in rows:
|
||||
with self.subTest(workflow=row["workflow_path"]):
|
||||
self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"})
|
||||
self.assertIs(type(row["workflow_id"]), int)
|
||||
self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"])
|
||||
source = (ROOT / row["workflow_path"]).read_text()
|
||||
push = re.search(r"(?m)^ push:\n((?: .*\n)+)", source)
|
||||
self.assertIsNotNone(push, "a required workflow must run on main pushes")
|
||||
self.assertIn(" branches: [main]\n", push[1])
|
||||
self.assertNotRegex(push[1], r"paths", "a path filter would leave candidates without a run")
|
||||
names = [job["name"] for job in row["jobs"]]
|
||||
self.assertEqual(len(names), len(set(names)))
|
||||
for job in row["jobs"]:
|
||||
self.assertEqual(set(job), {"name", "app_id", "applicability"})
|
||||
self.assertEqual((job["app_id"], job["applicability"]), (15368, "required"))
|
||||
|
||||
def test_sonar_identity_and_reviewed_scope(self):
|
||||
sonar = self.policy["candidate_policy"]["sonar"]
|
||||
properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines()
|
||||
if line and not line.startswith("#"))
|
||||
self.assertEqual(sonar["organization"], properties["sonar.organization"])
|
||||
self.assertEqual(sonar["project"], properties["sonar.projectKey"])
|
||||
self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis"))
|
||||
self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main")
|
||||
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
|
||||
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
|
||||
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]))
|
||||
metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]]
|
||||
self.assertEqual(len(metrics), len(set(metrics)))
|
||||
keys = [item["key"] for item in sonar["debt"]]
|
||||
self.assertEqual(len(keys), len(set(keys)))
|
||||
for item in sonar["debt"]:
|
||||
with self.subTest(issue=item["key"]):
|
||||
self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"})
|
||||
self.assertTrue(item["component"].startswith(sonar["project"] + ":"))
|
||||
self.assertIn(item["type"], sonar["issue_types"])
|
||||
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the existing synthetic packaging suites together; no app build or signing."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
class LinuxLauncherContractTests(unittest.TestCase):
|
||||
"""The launchers' argv contract, proven by a recorder binary instead of a build."""
|
||||
|
||||
def test_every_linux_launcher_passes_the_profile(self):
|
||||
for script in ("linux/nightly-launch-test.sh", "linux/nightly-arch-tar-test.sh"):
|
||||
result = subprocess.run(["bash", str(HERE / script)], capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(result.returncode, 0, f"{script}\n{result.stdout}\n{result.stderr}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
suite = unittest.TestSuite()
|
||||
for name, relative in (
|
||||
("deck_plist_suite", "macos/nightly_plist_tests.py"),
|
||||
("deck_release_dispatch_suite", "nightly-release-tests.py"),
|
||||
("deck_mac_sign_suite", "macos/nightly_sign_tests.py"),
|
||||
):
|
||||
spec = importlib.util.spec_from_file_location(name, HERE / relative)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
|
||||
suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(LinuxLauncherContractTests))
|
||||
return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,139 @@
|
||||
"""POSIX packaging I/O rooted at a caller-owned private working directory.
|
||||
|
||||
The build launcher chooses cwd independently of file arguments (Linux uses its
|
||||
mktemp directory). This is not a sandbox against root or a malicious same-UID
|
||||
caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive.
|
||||
"""
|
||||
import contextlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
|
||||
|
||||
def _component(name):
|
||||
# A descriptor-relative open must name exactly one entry in its directory.
|
||||
if not name or name in (".", "..") or os.path.basename(name) != name:
|
||||
raise ValueError("build path components must be single names")
|
||||
return os.path.basename(name)
|
||||
|
||||
|
||||
class OwnedBuildRoot:
|
||||
def __enter__(self):
|
||||
self.directory = Path.cwd()
|
||||
self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
info = os.fstat(self.fd)
|
||||
if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077:
|
||||
os.close(self.fd)
|
||||
raise ValueError("packaging cwd must be an owned private build directory")
|
||||
return self
|
||||
|
||||
def __exit__(self, *_error):
|
||||
os.close(self.fd)
|
||||
|
||||
def _relative(self, path):
|
||||
path = Path(path)
|
||||
try:
|
||||
relative = path.relative_to(self.directory) if path.is_absolute() else path
|
||||
except ValueError as error:
|
||||
raise ValueError("path is outside the owned build directory") from error
|
||||
if not relative.parts or ".." in relative.parts:
|
||||
raise ValueError("empty or parent-traversing build path")
|
||||
# Check an independently selected root, never the supplied filename's parent.
|
||||
try:
|
||||
parent = (self.directory / relative).parent.resolve(strict=True)
|
||||
except OSError as error:
|
||||
raise ValueError("build path parent must exist") from error
|
||||
if not parent.is_relative_to(self.directory):
|
||||
raise ValueError("resolved path escapes the owned build directory")
|
||||
return relative
|
||||
|
||||
def _checked_parts(self, path):
|
||||
relative = self._relative(path)
|
||||
root = os.path.realpath(self.directory)
|
||||
lexical = os.path.join(root, *relative.parts)
|
||||
target = os.path.realpath(lexical)
|
||||
if target == root or os.path.commonpath([root, target]) != root:
|
||||
raise ValueError("resolved path escapes the owned build directory")
|
||||
if target != lexical:
|
||||
raise ValueError("build path must not pass through symlinks or aliases")
|
||||
return [_component(part) for part in os.path.relpath(target, root).split(os.sep)]
|
||||
|
||||
def _parent(self, path):
|
||||
parts = self._checked_parts(path)
|
||||
current = os.dup(self.fd)
|
||||
try:
|
||||
for part in parts[:-1]:
|
||||
next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current)
|
||||
os.close(current)
|
||||
current = next_fd
|
||||
return current, parts[-1]
|
||||
except OSError as error:
|
||||
os.close(current)
|
||||
raise ValueError("build path parents must be non-symlink directories") from error
|
||||
|
||||
@contextlib.contextmanager
|
||||
def reader(self, path, limit):
|
||||
parent, name = self._parent(path)
|
||||
try:
|
||||
try:
|
||||
descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
||||
except OSError as error:
|
||||
raise ValueError("build input must be a regular file without aliases") from error
|
||||
finally:
|
||||
os.close(parent)
|
||||
info = os.fstat(descriptor)
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
|
||||
os.close(descriptor)
|
||||
raise ValueError("build input must be a regular file within its read bound")
|
||||
with os.fdopen(descriptor, "rb") as stream:
|
||||
yield stream
|
||||
|
||||
def read_bytes(self, path, limit):
|
||||
with self.reader(path, limit) as stream:
|
||||
data = stream.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise ValueError("build input grew beyond its read bound")
|
||||
return data
|
||||
|
||||
def children(self, path, limit):
|
||||
relative = self._relative(path)
|
||||
parent, name = self._parent(path)
|
||||
try:
|
||||
try:
|
||||
descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
|
||||
except OSError as error:
|
||||
raise ValueError("build stage must be a non-symlink directory") from error
|
||||
finally:
|
||||
os.close(parent)
|
||||
try:
|
||||
entries = []
|
||||
with os.scandir(descriptor) as iterator:
|
||||
for entry in iterator:
|
||||
if len(entries) >= limit:
|
||||
raise ValueError("too many build stage members")
|
||||
entries.append(self.directory / relative / entry.name)
|
||||
return entries
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def create(self, path):
|
||||
parent, name = self._parent(path)
|
||||
name = _component(name)
|
||||
try:
|
||||
descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent)
|
||||
info = os.fstat(descriptor)
|
||||
identity = (info.st_dev, info.st_ino)
|
||||
try:
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
yield stream
|
||||
except BaseException:
|
||||
try:
|
||||
current = os.stat(name, dir_fd=parent, follow_symlinks=False)
|
||||
if (current.st_dev, current.st_ino) == identity:
|
||||
os.unlink(_component(name), dir_fd=parent)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
os.close(parent)
|
||||
@@ -0,0 +1,95 @@
|
||||
param([Parameter(Mandatory=$true)][string] $FixtureRoot)
|
||||
. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly
|
||||
function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
|
||||
$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64'
|
||||
Assert ($spec.Archive -eq 'deckcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name'
|
||||
Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'deckcraft.exe') 'nightly must not ship the unqualified CLI'
|
||||
Assert ($spec.AppId -eq 'ai.storyteller.deckcraft.nightly-v1') 'nightly identity is not distinct'
|
||||
foreach ($arch in @('x86', 'arm64')) {
|
||||
$refused = $false
|
||||
try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true }
|
||||
Assert $refused 'unsupported target was accepted'
|
||||
}
|
||||
foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) {
|
||||
$refused = $false
|
||||
try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true }
|
||||
Assert $refused 'unsafe artifact version was accepted'
|
||||
}
|
||||
Assert-NightlyFlavor 'DeckCraft Nightly' 'DeckCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345'
|
||||
foreach ($pair in @(@('DeckCraft', 'DeckCraft 0.23.1 (nightly-v1)'), @('DeckCraft Nightly', 'DeckCraft 0.23.1'))) {
|
||||
$refused = $false
|
||||
try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true }
|
||||
Assert $refused 'stable or mismatched build flavor was accepted'
|
||||
}
|
||||
$sha = 'abcdef0123456789abcdef0123456789abcdef01'
|
||||
$good = '0.23.1-nightly.20261120.17.1.gabcdef012345'
|
||||
Assert-NightlySource $good $sha '2026-11-20' $sha ''
|
||||
$cases = @(
|
||||
@('missing commit', $good, '', '2026-11-20', $sha, ''),
|
||||
@('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''),
|
||||
@('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''),
|
||||
@('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''),
|
||||
@('missing date', $good, $sha, '', $sha, ''),
|
||||
@('date differs from version', $good, $sha, '2026-11-21', $sha, ''),
|
||||
@('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''),
|
||||
@('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/deckcraft/src/main.rs')
|
||||
)
|
||||
foreach ($case in $cases) {
|
||||
$refused = $false
|
||||
try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true }
|
||||
Assert $refused "source identity accepted: $($case[0])"
|
||||
}
|
||||
Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed'
|
||||
|
||||
# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP.
|
||||
if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' }
|
||||
$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
$repo = Join-Path $testRoot 'app'
|
||||
$fontRepo = Join-Path $testRoot 'craft-fonts'
|
||||
$family = Join-Path $fontRepo 'fonts\ExampleFamily'
|
||||
$stage = Join-Path $testRoot 'stage'
|
||||
New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null
|
||||
$rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md')
|
||||
foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" }
|
||||
Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example'
|
||||
Copy-NightlyNotices $repo $fontRepo $stage
|
||||
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) {
|
||||
Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name"
|
||||
}
|
||||
$zip = Join-Path $testRoot 'notices.zip'
|
||||
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip
|
||||
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
|
||||
try {
|
||||
$names = @($archive.Entries | ForEach-Object { $_.FullName })
|
||||
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" }
|
||||
foreach ($forbidden in @('portable.txt', 'deckcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" }
|
||||
$entry = $archive.GetEntry('OFL-ExampleFamily.txt')
|
||||
$reader = [IO.StreamReader]::new($entry.Open())
|
||||
try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() }
|
||||
} finally { $archive.Dispose() }
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force }
|
||||
}
|
||||
Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP'
|
||||
|
||||
# The source state comes from git itself: the checked-out commit, then a dirty tree.
|
||||
$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null
|
||||
git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' }
|
||||
$head = (git -C $gitRoot rev-parse HEAD).Trim()
|
||||
$state = Get-NightlySourceState $gitRoot
|
||||
Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD'
|
||||
$version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12)
|
||||
Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status
|
||||
Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty'
|
||||
$state = Get-NightlySourceState $gitRoot
|
||||
$refused = $false
|
||||
try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true }
|
||||
Assert $refused 'a dirty checkout was accepted'
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force }
|
||||
}
|
||||
Write-Output 'nightly source state is read from git and a dirty checkout is refused'
|
||||
@@ -0,0 +1,90 @@
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string] $FixtureRoot,
|
||||
[string] $PackagingRoot = $PSScriptRoot,
|
||||
[switch] $PhaseGuardOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly
|
||||
$sign = Join-Path $PackagingRoot 'sign.ps1'
|
||||
$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE')
|
||||
function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } }
|
||||
function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
|
||||
function Invoke-Refusal([scriptblock] $Operation, [string] $Message) {
|
||||
$errorText = ''
|
||||
try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message }
|
||||
Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText"
|
||||
}
|
||||
function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' }
|
||||
function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' }
|
||||
$global:SigningFixtureCargoCalls = 0
|
||||
if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' }
|
||||
$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $root | Out-Null
|
||||
# The fixture mocks Cargo, but nightly.ps1 checks the same source identity a packaging run does:
|
||||
# the version names this checkout's commit and the run's UTC date, and the tree is clean. Deriving
|
||||
# them here keeps the fixture reaching the mocked compiler instead of failing in source validation.
|
||||
$sha = "$(git -C $PSScriptRoot rev-parse HEAD)".Trim()
|
||||
$runDate = (Get-Date).ToUniversalTime().ToString('yyyyMMdd')
|
||||
$version = "0.23.1-nightly.$runDate.12345.1.g$($sha.Substring(0, 12))"
|
||||
$env:DECKCRAFT_VERSION = $version
|
||||
$env:DECKCRAFT_BUILD_SHA = $sha
|
||||
$env:DECKCRAFT_BUILD_DATE = "$($runDate.Substring(0, 4))-$($runDate.Substring(4, 2))-$($runDate.Substring(6, 2))"
|
||||
function Invoke-Build([switch] $BuildOnly) {
|
||||
$arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')}
|
||||
if ($BuildOnly) { $arguments.BuildOnly = $true }
|
||||
& (Join-Path $PackagingRoot 'nightly.ps1') @arguments
|
||||
}
|
||||
try {
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { Invoke-Build } 'requires -BuildOnly'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo'
|
||||
Write-Output 'PASS: explicit-build-phase-required'
|
||||
if ($PhaseGuardOnly) { return }
|
||||
|
||||
foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) {
|
||||
Clear-SigningFixtures
|
||||
[Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret')
|
||||
Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo'
|
||||
}
|
||||
Write-Output 'PASS: credentials-rejected-before-compilation'
|
||||
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary'
|
||||
Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact'
|
||||
Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary'
|
||||
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
|
||||
$env:AZURE_CLIENT_SECRET = 'generated-partial-fixture'
|
||||
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
|
||||
Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration'
|
||||
|
||||
Clear-SigningFixtures
|
||||
$env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate'
|
||||
& $sign -Required -CheckOnly
|
||||
Clear-SigningFixtures
|
||||
foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') }
|
||||
& $sign -Required -CheckOnly
|
||||
Clear-SigningFixtures
|
||||
Write-Output 'PASS: supported-configuration-presence-without-signing'
|
||||
|
||||
# Load the policy function without signing. These objects are not crypto evidence.
|
||||
. $sign -CheckOnly
|
||||
foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) {
|
||||
Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature'
|
||||
}
|
||||
Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'})
|
||||
Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer'
|
||||
|
||||
$file = Join-Path $root 'owned-sentinel.exe'
|
||||
[IO.File]::WriteAllText($file, 'generated sentinel, not a real executable')
|
||||
$before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
|
||||
& $sign -Files $file
|
||||
Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes'
|
||||
Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes'
|
||||
} finally {
|
||||
Clear-SigningFixtures
|
||||
Remove-Item -LiteralPath $root -Recurse -Force
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #>
|
||||
param(
|
||||
[string] $Arch = 'x64',
|
||||
[string] $Version,
|
||||
[string] $Target,
|
||||
[string] $TargetDir,
|
||||
[string] $Dist,
|
||||
[switch] $SkipBuild,
|
||||
[switch] $BuildOnly,
|
||||
[switch] $FunctionsOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) {
|
||||
if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' }
|
||||
if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
|
||||
return @{
|
||||
Archive = "deckcraft-$Version-windows-x86_64-nightly.zip"
|
||||
UnsignedArchive = "deckcraft-$Version-windows-x86_64-nightly.unsigned.zip"
|
||||
Executables = @('deckcraft.exe')
|
||||
Channel = 'nightly-v1'
|
||||
AppId = 'ai.storyteller.deckcraft.nightly-v1'
|
||||
}
|
||||
}
|
||||
|
||||
# The same source identity the Linux helper enforces (nightly-common.sh): the version names the
|
||||
# commit being built, the date is the original run's, and the tree is clean.
|
||||
function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) {
|
||||
if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (DECKCRAFT_BUILD_SHA)' }
|
||||
if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
|
||||
if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' }
|
||||
if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (DECKCRAFT_BUILD_DATE)' }
|
||||
$versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8)
|
||||
if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' }
|
||||
if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' }
|
||||
if ($Status) { throw 'nightly packaging requires the frozen clean source' }
|
||||
}
|
||||
|
||||
function Get-NightlySourceState([string] $RepositoryRoot) {
|
||||
$head = git -C $RepositoryRoot rev-parse HEAD
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' }
|
||||
$status = git -C $RepositoryRoot status --porcelain
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' }
|
||||
return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() }
|
||||
}
|
||||
|
||||
function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) {
|
||||
if ($ProductName -ne 'DeckCraft Nightly' -or $VersionOutput -cne "DeckCraft $ExpectedVersion (nightly-v1)") {
|
||||
throw 'the executable is not the compiled nightly-v1 flavor'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) {
|
||||
foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') {
|
||||
$source = Join-Path $RepositoryRoot $name
|
||||
if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination }
|
||||
}
|
||||
if ($FontRepository) {
|
||||
$fonts = Join-Path $FontRepository 'fonts'
|
||||
if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' }
|
||||
foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) {
|
||||
$license = Join-Path $family.FullName 'OFL.txt'
|
||||
if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($FunctionsOnly) { return }
|
||||
if (-not $env:DECKCRAFT_VERSION -or $Version -cne $env:DECKCRAFT_VERSION) { throw 'nightly-v1 requires explicit DECKCRAFT_VERSION, not the Cargo version fallback' }
|
||||
$Spec = Get-NightlyArchiveSpec $Version $Arch
|
||||
if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' }
|
||||
if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' }
|
||||
if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' }
|
||||
# No key values may enter compilation. This produces an internal intermediate, not a feed artifact.
|
||||
& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment
|
||||
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
$Source = Get-NightlySourceState $Root
|
||||
Assert-NightlySource $Version $env:DECKCRAFT_BUILD_SHA $env:DECKCRAFT_BUILD_DATE $Source.Head $Source.Status
|
||||
$oldChannel = $env:DECKCRAFT_BUILD_CHANNEL
|
||||
try {
|
||||
# DECKCRAFT_VERSION is the prepared identity the build script embeds; there is no separate
|
||||
# version-override variable (DeckCraft's format layer uses the Cargo version).
|
||||
$env:DECKCRAFT_BUILD_CHANNEL = 'nightly-v1'
|
||||
$env:DECKCRAFT_REQUIRE_WINRES = '1'
|
||||
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static'
|
||||
# The same directory the packaging steps below read from, so a custom -TargetDir cannot leave
|
||||
# Cargo writing somewhere else and the steps reading a stale executable.
|
||||
cargo build --release --locked -p deckcraft --target $Target --target-dir $TargetDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" }
|
||||
} finally {
|
||||
$env:DECKCRAFT_BUILD_CHANNEL = $oldChannel
|
||||
}
|
||||
$Source = Get-NightlySourceState $Root
|
||||
try { Assert-NightlySource $Version $env:DECKCRAFT_BUILD_SHA $env:DECKCRAFT_BUILD_DATE $Source.Head $Source.Status }
|
||||
catch { throw "source changed during the build: $_" }
|
||||
$Exe = Join-Path $TargetDir "$Target\release\deckcraft.exe"
|
||||
$pe = [System.IO.File]::ReadAllBytes($Exe)
|
||||
if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' }
|
||||
$offset = [BitConverter]::ToInt32($pe, 0x3C)
|
||||
if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' }
|
||||
if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) {
|
||||
throw 'nightly executable must be x86_64 Windows GUI'
|
||||
}
|
||||
$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo
|
||||
$ProductName = $VersionInfo.ProductName
|
||||
if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' }
|
||||
# Check the embedded build flavor before invoking even the side-effect-free version query.
|
||||
if ($ProductName -ne 'DeckCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' }
|
||||
$VersionOutput = (& $Exe --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' }
|
||||
Assert-NightlyFlavor $ProductName $VersionOutput $Version
|
||||
$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64'
|
||||
if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
|
||||
Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'deckcraft.exe')
|
||||
# Signing happens only in the separate trusted step, using sign.ps1 -Required.
|
||||
# The intermediate's filename cannot satisfy the feed-ready archive contract.
|
||||
Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage
|
||||
if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) {
|
||||
throw 'nightly stage contains an unexpected executable or portable fallback marker'
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
|
||||
$Zip = Join-Path $Dist $Spec.UnsignedArchive
|
||||
if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' }
|
||||
Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip
|
||||
$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip)
|
||||
try {
|
||||
$Names = @($Archive.Entries | ForEach-Object { $_.FullName })
|
||||
if ('deckcraft.exe' -notin $Names -or 'deckcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) {
|
||||
throw 'nightly ZIP payload violates the GUI-only profile contract'
|
||||
}
|
||||
} finally { $Archive.Dispose() }
|
||||
Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)"
|
||||
@@ -21,9 +21,12 @@
|
||||
#>
|
||||
param(
|
||||
[ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64',
|
||||
[switch] $SkipBuild
|
||||
[switch] $SkipBuild,
|
||||
[switch] $Nightly,
|
||||
[switch] $BuildOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' }
|
||||
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
|
||||
function Invoke-Native([string] $What, [scriptblock] $Block) {
|
||||
@@ -50,12 +53,21 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' }
|
||||
$TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' }
|
||||
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
|
||||
|
||||
if (-not $env:DECKCRAFT_BUILD_SHA) { $env:DECKCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
|
||||
if (-not $env:DECKCRAFT_BUILD_DATE) { $env:DECKCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
|
||||
# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both.
|
||||
if (-not $Nightly) {
|
||||
if (-not $env:DECKCRAFT_BUILD_SHA) { $env:DECKCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
|
||||
if (-not $env:DECKCRAFT_BUILD_DATE) { $env:DECKCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
|
||||
}
|
||||
|
||||
Write-Output "DeckCraft $Version for Windows $Arch ($Target)"
|
||||
|
||||
if ($Nightly) {
|
||||
& (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly
|
||||
return
|
||||
}
|
||||
|
||||
if (-not $SkipBuild) {
|
||||
$env:DECKCRAFT_BUILD_CHANNEL = 'stable'
|
||||
# Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and
|
||||
# proc-macros are unaffected.
|
||||
$flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS'
|
||||
@@ -83,6 +95,9 @@ foreach ($check in @(@('deckcraft.exe', 2), @('deckcraft-cli.exe', 3))) {
|
||||
if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" }
|
||||
Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)"
|
||||
}
|
||||
if ((Get-Item -LiteralPath (Join-Path $Bin 'deckcraft.exe')).VersionInfo.ProductName -eq 'DeckCraft Nightly') {
|
||||
throw 'a nightly executable cannot be packaged as stable'
|
||||
}
|
||||
|
||||
# The Start menu shortcut is not advertised and names no MSI icon, so it shows the icon embedded in
|
||||
# deckcraft.exe (#1114). -SkipBuild takes whatever binary is already there, which may come from a
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net),
|
||||
AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE
|
||||
With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds
|
||||
still produce installers.
|
||||
still produce installers. Nightly callers require signing with -Required and can
|
||||
check signing configuration with -Required -CheckOnly. Compilation uses the
|
||||
separate -CheckBuildEnvironment mode, without importing signing keys.
|
||||
|
||||
This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different
|
||||
timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe).
|
||||
@@ -18,8 +20,11 @@
|
||||
pwsh packaging/windows/sign.ps1 dist/deckcraft.exe dist/Deckcraft.msi
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
|
||||
[string[]] $Files
|
||||
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
|
||||
[string[]] $Files,
|
||||
[switch] $Required,
|
||||
[switch] $CheckOnly,
|
||||
[switch] $CheckBuildEnvironment
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
@@ -27,6 +32,12 @@ function Write-Warn([string] $Message) {
|
||||
if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message }
|
||||
}
|
||||
|
||||
function Assert-AuthenticodeSignature($Signature) {
|
||||
if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) {
|
||||
throw 'Required signing must produce a valid Authenticode signature and signer certificate'
|
||||
}
|
||||
}
|
||||
|
||||
function Find-SignTool {
|
||||
if ($env:SIGNTOOL) { return $env:SIGNTOOL }
|
||||
$onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue
|
||||
@@ -44,11 +55,28 @@ function Invoke-SignTool([string[]] $Arguments) {
|
||||
if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" }
|
||||
}
|
||||
|
||||
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
|
||||
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
|
||||
$azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE'
|
||||
if ($CheckBuildEnvironment) {
|
||||
if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' }
|
||||
$names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars
|
||||
if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) {
|
||||
throw 'Compilation must not receive signing credentials; use a separate trusted signing step'
|
||||
}
|
||||
return
|
||||
}
|
||||
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
|
||||
$haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) })
|
||||
|
||||
if ($Required -and -not $haveCert -and -not $haveAzure) {
|
||||
throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration'
|
||||
}
|
||||
if ($CheckOnly) {
|
||||
if ($Files) { throw '-CheckOnly does not sign files' }
|
||||
return
|
||||
}
|
||||
if (-not $Files) { throw 'At least one file is required for signing' }
|
||||
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
|
||||
|
||||
if (-not $haveCert -and -not $haveAzure) {
|
||||
Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')"
|
||||
exit 0
|
||||
@@ -96,6 +124,9 @@ try {
|
||||
Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files)
|
||||
}
|
||||
Invoke-SignTool (@('verify', '/pa', '/v') + $Files)
|
||||
if ($Required) {
|
||||
foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) }
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
|
||||
|
||||
@@ -9,3 +9,14 @@ sonar.organization=storytold
|
||||
sonar.issue.ignore.multicriteria=gha-lockfile
|
||||
sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637
|
||||
sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/**
|
||||
# Coverage counts only code a test run executes. These are process entrypoints and build scripts:
|
||||
# `cargo llvm-cov` starts the test binaries, never `main`, and cargo runs each build script in its
|
||||
# own process, so their lines can never be covered however much the modules they call are (the
|
||||
# wordcraft learning). Keep the logic they call in measured modules.
|
||||
sonar.coverage.exclusions=packaging/**,apps/deckcraft/src/main.rs,apps/deckcraft/build.rs,crates/ui-egui/build.rs
|
||||
# Setting test roots disables the CLI default; keep all production sources analyzed.
|
||||
sonar.sources=.
|
||||
# These exact fixture runners are tests, not production code. Do not exclude helpers.
|
||||
sonar.tests=packaging
|
||||
sonar.test.inclusions=packaging/nightly-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py
|
||||
sonar.python.coverage.reportPaths=python-coverage.xml
|
||||
|
||||
Reference in New Issue
Block a user