Compare commits

..
Author SHA1 Message Date
Brandon ThomasandClaude Opus 5.5 3e7bb60c80 Docs: text in scaled groups is drawn (#340)
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-12 23:28:32 -04:00
660 changed files with 43446 additions and 146295 deletions
-6
View File
@@ -1,6 +0,0 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
reviews:
auto_review:
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
ignore_usernames:
- "dependabot[bot]"
-3
View File
@@ -1,3 +0,0 @@
# Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI
# installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET).
nextest-version = "0.9.150"
-30
View File
@@ -1,30 +0,0 @@
version: 2
updates:
# Maintain Rust / Cargo dependencies
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
# Consolidate updates into a single PR rather than one PR per crate
groups:
cargo-dependencies:
patterns:
- "*"
commit-message:
prefix: "chore(deps)"
# Maintain GitHub Actions workflows
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
groups:
actions:
patterns:
- "*"
commit-message:
prefix: "ci(deps)"
+36 -47
View File
@@ -1,65 +1,54 @@
name: CI
name: ci
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
# suite's shared gate workflow in craft-common-actions.
# Quality gates for every push to main and every pull request: rustfmt, clippy (-D warnings),
# tests, asset attribution, crate layering and the wasm32 check — `cargo xtask ci`.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
contents: read
# A newer push to a PR branch cancels its older run; every push to main runs to the end.
concurrency:
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
CARGO_TERM_COLOR: always
# Same craft-fonts commit as release.yml (Latin presentation fonts).
CRAFT_FONTS_REF: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
jobs:
# Keep the early manifest preflight separate from the reusable workflow. The shared gate
# also runs with require-craft-fonts: true, so the build script enforces actual required faces.
# Keep this pin identical to gate, freebsd.yml and release.yml.
font-pin:
runs-on: ubuntu-latest
env:
# Same craft-fonts commit as release.yml.
CRAFT_FONTS_REF: 37827adc41fd165f9a9234ac40f94dbad353aa69
gates:
name: gates (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
# No macOS on PRs or main: the org's 5 macOS slots are kept for release builds, and
# release.yml builds macOS (a failing release is fixed and rebuilt).
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Check out craft-fonts
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: ${{ env.CRAFT_FONTS_REF }}
path: craft-fonts
- name: Font pin gate
env:
# The only pin allowed to predate the reviewed Chinese manifest. It is a sentinel, not
# a proposed future SHA; update it together with all three workflow pins.
PENDING_CRAFT_FONTS_PIN: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
- name: Linux build dependencies
if: runner.os == 'Linux'
run: |
manifest="$GITHUB_WORKSPACE/craft-fonts/fonts/simplified-chinese-manifest.txt"
if [ -f "$manifest" ]; then
echo "craft-fonts pin carries the reviewed simplified-Chinese manifest."
elif [ "$CRAFT_FONTS_REF" = "$PENDING_CRAFT_FONTS_PIN" ]; then
echo "::warning title=craft-fonts pin pending::The pinned craft-fonts commit has no fonts/simplified-chinese-manifest.txt, so CJK checks may skip. Advance ci.yml, freebsd.yml and release.yml together to the reviewed immutable SHA before claiming shipped Chinese fonts."
else
echo "::error title=craft-fonts pin missing Chinese manifest::CRAFT_FONTS_REF advanced past the known pending pin ($PENDING_CRAFT_FONTS_PIN) but still has no fonts/simplified-chinese-manifest.txt. Update the pin to the reviewed commit that carries it."
exit 1
fi
gate:
needs: font-pin
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
require-craft-fonts: true
packages: >-
libasound2-dev libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev
libgl1-mesa-dev
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libasound2-dev libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: ci-${{ matrix.os }}
- name: cargo xtask ci
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
run: cargo xtask ci
+6 -11
View File
@@ -2,17 +2,16 @@
# (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter.
name: FreeBSD
# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every pull
# request: a drifted dependency still shows up within a day, and always before a release ships.
# PRs that change the FreeBSD workflow itself still run it.
on:
push:
branches: [release]
branches: [main]
pull_request:
paths:
- Cargo.toml
- Cargo.lock
- "**/Cargo.toml"
- "crates/fonts/**"
- .github/workflows/freebsd.yml
schedule:
- cron: "27 2 * * *"
workflow_dispatch:
concurrency:
@@ -27,8 +26,4 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
# Keep identical to ci.yml and release.yml. The shared FreeBSD workflow passes
# CRAFT_FONTS_DIR to its tests but has no CRAFT_FONTS_REQUIRED input yet, so it does not
# qualify the required Chinese input after the pin advances; that gate stays explicitly
# pending in docs/egui-037-migration-plan.md section 5.1.
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
craft-fonts-ref: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
-28
View File
@@ -1,28 +0,0 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
-23
View File
@@ -1,23 +0,0 @@
# Evaluates the Nix flake (no build, about a minute): `nix build` / `nix develop` stop at evaluation
# when Cargo.lock gains something nix/package.nix can't vendor, and nothing else would notice.
name: Nix
on:
push:
branches: [main]
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
pull_request:
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nix-${{ github.ref }}
cancel-in-progress: true
jobs:
nix:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
-28
View File
@@ -21,31 +21,3 @@ jobs:
lint:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
windows-install-policy:
timeout-minutes: 10
name: Windows installation policy (no app build)
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the pinned packaging toolchain
shell: pwsh
run: |
$tools = Join-Path $env:RUNNER_TEMP 'craft-install-policy-wix'
dotnet tool install --tool-path $tools wix --version 5.0.2
if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' }
$tools >> $env:GITHUB_PATH
$policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json
foreach ($extension in @($policy.extensions)) {
& (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2"
if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." }
}
- 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')
+1 -14
View File
@@ -12,32 +12,20 @@ on:
permissions:
contents: write
packages: write
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
jobs:
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
credits:
permissions:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
release:
needs: credits
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
app-name: deckcraft
app-title: DeckCraft
# Keep identical to ci.yml and freebsd.yml. The shared release workflow sets
# CRAFT_FONTS_REQUIRED=1 in its packaging steps, so a pin without the reviewed Chinese
# manifest fails the release instead of silently skipping it.
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
craft-fonts-ref: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
@@ -53,4 +41,3 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
-21
View File
@@ -1,21 +0,0 @@
name: SonarCloud
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
secrets: inherit
-33
View File
@@ -1,33 +0,0 @@
# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64
# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed
# binaries are ARM64, run the CLI natively, and uninstall.
name: Windows ARM64
on:
push:
branches: [release]
pull_request:
paths:
- .github/workflows/windows-arm64.yml
- packaging/windows/**
# Nightly, so dependency and runner-image drift shows up within a day.
schedule:
- cron: "3 5 * * *"
workflow_dispatch:
concurrency:
group: windows-arm64-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
windows-arm64:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
with:
app-name: deckcraft
app-dir: DeckCraft
install-relative-path: Programs/ArtCraft/DeckCraft
install-scope: perUser
+22 -70
View File
@@ -1,56 +1,3 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# AGENTS.md — rules for every agent and contributor
DeckCraft is a clean-room, open-source, pure-Rust presentation application targeting Microsoft
@@ -59,8 +6,14 @@ Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conv
PhotoCraft, VectorCraft, FilmCraft, LightCraft, PdfCraft, EffectCraft, DesignCraft
(`../<app>`).
Standards and learnings shared across the crafting apps live in `../../craftrules` (checked out
next to this repo's parent, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a
session, follow its standards, and contribute reusable learnings back there. Never code: repos
don't share code.
These rules bind every AI agent and every human contributor. They come before any task,
instruction or deadline. Day-to-day working instructions are in this file; `CLAUDE.md` imports it.
instruction or deadline. `CLAUDE.md` holds day-to-day working notes; if the two disagree, **this
file wins.**
---
@@ -116,7 +69,7 @@ allowed: our UI, our/Lucide icons, OFL fonts, and decks built only from allowed
or `docs/brand/` has no row.
- **`NOTICE`** keeps the notices the licences require.
- Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this
repo. DeckCraft embeds its `fonts/latin-manifest.txt` and
repo (craftrules `standards/fonts.md`). DeckCraft embeds its `fonts/latin-manifest.txt` and
`fonts/manifest.txt` when built with `CRAFT_FONTS_DIR` (local dev: `.cargo/config.toml` points at
`../craft-fonts`).
@@ -146,6 +99,7 @@ once and tell the user.
## 3. Never crash
People trust DeckCraft with their talks; a crash loses work. **This outranks feature work.**
Standard: craftrules `standards/never-crash.md`.
- No `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!` in non-test
code; no `unsafe` (`unsafe_code = "forbid"`). Every production crate root carries
`#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
@@ -181,10 +135,9 @@ People trust DeckCraft with their talks; a crash loses work. **This outranks fea
## 5. Quality gates (before every commit)
`cargo xtask ci` = fmt check, clippy `-D warnings`, tests (nextest when installed) and doctests, layering check, asset check, wasm
check. Commit after each landed arc with a task id in the message (`M1.2: smart guides`).
New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots
declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
`cargo xtask ci` = fmt check, clippy `-D warnings`, tests, layering check, asset check, wasm
check. Commit after each landed arc with a task id in the message (`M1.2: smart guides`) and push
to `main`.
## 6. Running and looking at the app
@@ -193,19 +146,20 @@ declare the crate-level lint attributes before modules; crate-level `//!` docume
`{"id":1,"method":"engine.execute","params":{"command":"shape.insert","params":{"preset":"star5","rect":[100,100,200,200]}}}`
then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods:
`crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`.
- **For UI work, look at the result** (screenshot, read the PNG). If available, compare with the observations
in `plan/powerpoint/01-observed-ui.md`. Otherwise verify the intended behaviour against the task and
committed documentation; the optional notebook is not a prerequisite.
- **For UI work, look at the result** (screenshot, read the PNG) and compare with the observations
in `plan/powerpoint/01-observed-ui.md`.
- Headless: `deckcraft-cli render --sample --all --scale 1 out/`,
`deckcraft-cli run --sample --cmd 'slide.new={"title":"Hi"}' --export out.png`.
- MCP: `deckcraft-cli mcp` (headless) or `deckcraft-cli mcp --connect 7990` (drive the app).
See `docs/mcp.md`.
- Shell gotcha on the dev machine: `mv`/`cp` are aliased interactive; use `/bin/mv -f`, `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own.
## 7. Planning
`plan/` is an optional gitignored notebook (status, execution notes, `powerpoint/` observations). Do not ask for it and do not stop when it is absent. The committed progress
docs:
`plan/` (gitignored) holds the local plan: `README.md`, `architecture.md`, `execution-plan.md`,
`STATUS.md` (start every session there) and `powerpoint/` observations. The committed progress
docs follow craftrules `standards/progress-docs.md`:
| File | Holds |
|---|---|
@@ -229,13 +183,11 @@ the `ROADMAP.md` progress log, and update each touched doc's status line and rev
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
whether they want to be credited by more than their username: a real name, a display name, and/or
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
(copy the template at the top of the file)
(copy the template at the top of the file, or run
`python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`)
and include it in their PR, committed as them. If no, change nothing: they are credited as
`@username` anyway.
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
GitHub profiles). Never hand-edit `contributors.json`.
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
+6 -41
View File
@@ -7,8 +7,6 @@ fails if a file under `assets/`, `docs/images/` or `docs/brand/` is missing from
DeckCraft contains **no Microsoft, Adobe, Avid or Autodesk iconography, images, fonts, themes,
templates or other assets**. Its themes, colour schemes, layouts, preset-shape geometry, sample
deck and UI icons are original work of the DeckCraft contributors (drawn or generated in code).
Icons placed from Insert › Icons are Lucide paths (ISC; Feather-derived icons MIT), not Microsoft
artwork. The ribbon and menu icons stay original drawings.
## In this repository
@@ -18,7 +16,7 @@ artwork. The ribbon and menu icons stay original drawings.
| `docs/brand/artcraft-logo-white.svg`, `docs/brand/artcraft-logo-white.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | README header (dark mode) |
| `docs/brand/artcraft-mark.svg`, `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | README footer, About |
| `docs/brand/artcraft-mark-black.svg`, `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Mark for light backgrounds |
| `docs/brand/LICENSE-brand.txt` | ArtCraft Team | ArtCraft brand kit | — (licence text) | Terms for the ArtCraft marks |
| `docs/brand/LICENSE-brand.txt` | ArtCraft Team | craftrules `standards/license-files` | — (licence text) | Terms for the ArtCraft marks |
| `assets/app-icon/deckcraft-1024.png`, `assets/app-icon/hicolor/*/apps/ai.storyteller.deckcraft.png` | DeckCraft contributors | rendered by DeckCraft from `assets/app-icon/icon-source.deckcraft` (shapes only) | MIT OR Apache-2.0 | Placeholder app icon (presentation board) until the mascot icon is drawn |
| `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") |
@@ -27,23 +25,19 @@ artwork. The ribbon and menu icons stay original drawings.
| `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 |
| `crates/media/tests/fixtures/tone*` (`tone.mp3`, `.m4a`, `.aac`, `.ogg`, `.opus`, `.flac`, `.wma`, `tone-alac.m4a`) | DeckCraft contributors | synthesised 0.5 s 440 Hz sine, encoded by `crates/media/tests/fixtures/make.sh` (ffmpeg as the encoder only) | CC0-1.0 | Audio decoding tests |
| `crates/media/tests/fixtures/clip-*` (`clip-h264.mp4`, `clip-h264.mov`, `clip-hevc.mp4`, `clip-vp8.webm`, `clip-vp9.webm`, `clip-av1.mkv`) | DeckCraft contributors | 6 frames of a colour gradient generated by `make.sh` (python3), encoded by ffmpeg (x264 / x265 / libvpx / libvpx-vp9 / SVT-AV1 as encoders only) | CC0-1.0 | Video decoding tests |
| `crates/media/tests/fixtures/damaged/*` (`ebml-header.mkv`, `ebml-position.webm`, `demux-loop.mp4`, `demux-loop.m4a`) | DeckCraft contributors | the `clip-*` and `tone*` fixtures above with bytes changed by a mutation fuzzer | CC0-1.0 | Damaged media must not panic or hang |
| `crates/media/tests/fixtures/damaged/*` (`stsc-count.m4a`, `stsz-size.m4a`) | DeckCraft contributors | `tone.m4a` above with bytes changed by a mutation fuzzer | CC0-1.0 | Damaged MP4 sample tables must not abort |
| `crates/media/tests/fixtures/clip-*` (`clip-h264.mp4`, `clip-h264.mov`, `clip-hevc.mp4`, `clip-vp9.webm`, `clip-av1.mkv`) | DeckCraft contributors | 6 frames of a colour gradient generated by `make.sh` (python3), encoded by ffmpeg (x264 / x265 / libvpx / SVT-AV1 as encoders only) | CC0-1.0 | Video decoding tests |
| `crates/media/tests/fixtures/make.sh` | DeckCraft contributors | this repository | MIT OR Apache-2.0 | Regenerates the media fixtures |
| `crates/render/tests/fixtures/colr-squares.ttf` | DeckCraft contributors | two squares as a COLRv0/CPAL test font, built by `make_colr_font.py` (fontTools as the builder only) | CC0-1.0 | Colour glyph rendering tests |
| `crates/fonts/tests/fixtures/legacy-semibold.ttf` | DeckCraft contributors | a one-glyph Semibold face named like Segoe UI Semibold (its Windows family differs from the typographic one), built by `make_legacy_font.py` (fontTools as the builder only) | CC0-1.0 | Font lookup by Windows family name tests |
| `crates/fonts/tests/fixtures/legacy-regular.ttf` | DeckCraft contributors | the same family's one-glyph Regular face, built by `make_legacy_font.py` (fontTools as the builder only) | CC0-1.0 | Font lookup by Windows family name tests |
| `crates/render/tests/fixtures/make_colr_font.py` | DeckCraft contributors | this repository | MIT OR Apache-2.0 | Regenerates the COLR test font |
| Lucide icon paths in `crates/engine/src/icon_data.rs` (Insert › Icons) | Lucide Contributors; Feather icons by Cole Bemis | https://github.com/lucide-icons/lucide/tree/440a1e1dfb1e712505308da46bead3c28b1f1398/icons (release 1.56.0, 2026-10-13) | ISC; MIT for the Feather-derived icons named in that commit's LICENSE | Stroke icons inserted as shapes |
## Bundled through dependencies
| Asset | Author | Source | Licence | Used for |
|---|---|---|---|---|
| Ubuntu Light (`Ubuntu-Light.ttf`, via the `epaint_default_fonts` crate 0.37) | Dalton Maag Ltd for Canonical | https://crates.io/crates/epaint_default_fonts | Ubuntu Font Licence 1.0 | Last-resort text face when no other font is available; UI fallback |
| Hack Regular, Noto Emoji (via `epaint_default_fonts` / egui) | Source Foundry; Google | https://crates.io/crates/epaint_default_fonts | MIT / Bitstream-Vera, OFL-1.1 | egui UI fallback glyphs |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 6d518fc7](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset, included by default_fonts independently of monochrome_emoji_fonts; emoji-icon-font.ttf is the full monochrome fallback. Dependency assets unmodified here; no font file copied into this repository. |
| Ubuntu Light (`Ubuntu-Light.ttf`, via the `epaint_default_fonts` crate 0.36) | Dalton Maag Ltd for Canonical | https://crates.io/crates/epaint_default_fonts | Ubuntu Font Licence 1.0 | Last-resort text face when no other font is available; UI fallback |
| Hack Regular, Noto Emoji, emoji-icon-font (via `epaint_default_fonts` / egui) | Source Foundry; Google; Jakub Steiner et al. | https://crates.io/crates/epaint_default_fonts | MIT / Bitstream-Vera, OFL-1.1, MIT | egui UI fallback glyphs |
## Embedded at build time from craft-fonts (`CRAFT_FONTS_DIR`)
@@ -59,35 +53,6 @@ families excluded by `crates/fonts/build.rs`:
| Carlito, Caladea | OFL-1.1 | Metric-compatible stand-ins for documents that ask for Calibri / Cambria |
| Liberation Sans, Serif, Mono | OFL-1.1 | Metric-compatible stand-ins for Arial, Times New Roman, Courier New |
| Montserrat, Lato, Open Sans, Roboto, Merriweather, Playfair Display, Poppins, Nunito Sans | OFL-1.1 | Theme fonts |
| BIZ UDPGothic, BIZ UDMincho, Shippori Mincho | OFL-1.1 | Japanese text |
| Noto Sans Arabic, Noto Sans Hebrew | OFL-1.1 | Arabic and Hebrew text |
| Noto Sans Thai, Noto Sans Georgian | OFL-1.1 | Thai and Georgian text |
| NanumGothic | OFL-1.1 | Korean text and interface fallback |
| Noto Sans Symbols, Noto Sans Symbols 2 | OFL-1.1 | Interface symbol fallback |
| BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans Arabic | OFL-1.1 | Japanese and Arabic text |
Web (wasm32) builds embed only Inter Regular/Bold (and a Variable face where the Latin manifest
provides one) and BIZ UDPGothic Regular.
## PDF writer colour profiles
`craft-pdf` is used with only its `write` feature and default features disabled. Krilla
0.8.2 embeds the following profiles; these were already reachable through the direct Krilla
exporter. No interpreter fallback fonts or CMaps are enabled, and no profile or font binary
is copied into this repository. The licence text is in `licenses/pdf-writer/LICENSE-ICC.txt`.
| Asset | Author | Source | Licence | SHA-256 | Used for |
|---|---|---|---|---|---|
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` | Clinton Ingram (Compact ICC Profiles) | https://github.com/LaurenzV/krilla/blob/3ffdf0588cf98050aad6edba51ca70162e1fb5b5/crates/krilla/icc/sGrey-v2-magic.icc | CC0-1.0 | `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481` | PDF export colour profiles |
| `krilla 0.8.2 / icc/sGrey-v4.icc` | Clinton Ingram (Compact ICC Profiles) | https://github.com/LaurenzV/krilla/blob/3ffdf0588cf98050aad6edba51ca70162e1fb5b5/crates/krilla/icc/sGrey-v4.icc | CC0-1.0 | `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d` | PDF export colour profiles |
| `krilla 0.8.2 / icc/sRGB-v2-magic.icc` | Clinton Ingram (Compact ICC Profiles) | https://github.com/LaurenzV/krilla/blob/3ffdf0588cf98050aad6edba51ca70162e1fb5b5/crates/krilla/icc/sRGB-v2-magic.icc | CC0-1.0 | `af4efe28f6d311799865f325ba39184a2e978b113ca74124d60af7de22b105f4` | PDF export colour profiles |
| `krilla 0.8.2 / icc/sRGB-v4.icc` | Clinton Ingram (Compact ICC Profiles) | https://github.com/LaurenzV/krilla/blob/3ffdf0588cf98050aad6edba51ca70162e1fb5b5/crates/krilla/icc/sRGB-v4.icc | CC0-1.0 | `c56e1685d888f5edb92fe07f2750f387f8fe8e91b32ff8fb0b56bfbbb9458353` | PDF export colour profiles |
### Optional native Chinese fallback
Native builds also read craft-fonts' `fonts/simplified-chinese-manifest.txt` when present.
This opt-in does not enter the wasm font allowlist. Font bytes and the full licence remain
in craft-fonts, including the LXGW Reserved Font Names and original Klee notice.
| Family | Author | Source | Licence | Use |
|---|---|---|---|---|
| LXGW WenKai Lite Regular 1.530 | LXGW; original Klee Project Authors / Fontworks | https://github.com/lxgw/LxgwWenKai-Lite/tree/b712c83d98acf977bacfb7fb010207802808bda9 | OFL-1.1, unmodified upstream font | Native Chinese glyph fallback after existing UI faces; font SHA256 `f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea`, OFL SHA256 `0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e` |
Web (wasm32) builds embed only Inter Regular/Bold and BIZ UDPGothic Regular.
+17 -1
View File
@@ -1 +1,17 @@
@AGENTS.md
# DeckCraft — working notes for Claude
Read [AGENTS.md](AGENTS.md) first: its rules (asset policy, clean room, never crash) bind you and
win over anything here.
## Start every session
1. Read `plan/STATUS.md`, then the current milestone in `plan/execution-plan.md`.
2. Read `../../craftrules/AGENTS.md` and the standards it lists for your task.
3. Run `cargo xtask ci` before you change anything, so you know the tree is green.
## Habits
- Every user-visible action is a command with tests (`crates/engine/src/cmd/*`).
- Look at UI changes: `deckcraft --sample --control 7990` + `ui.screenshot`, or
`deckcraft-cli render`.
- Commit after each landed arc (`M<n>.<k>: what`) and push to `origin main`.
- Keep `ROADMAP.md`, the progress docs in `docs/` (AGENTS.md §7) and `plan/STATUS.md` current.
- Don't ask the user questions; record genuinely-theirs decisions in `plan/STATUS.md`.
Generated
+426 -1112
View File
File diff suppressed because it is too large Load Diff
+15 -45
View File
@@ -4,10 +4,10 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/deckcraft", "apps/deckcraft-cli"]
[workspace.package]
version = "0.18.1"
version = "0.6.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
rust-version = "1.90"
repository = "https://github.com/storytold/deckcraft"
[workspace.dependencies]
@@ -27,12 +27,16 @@ deckcraft-engine = { path = "crates/engine" }
deckcraft-mcp = { path = "crates/mcp" }
deckcraft-ui-egui = { path = "crates/ui-egui" }
deckcraft-media = { path = "crates/media" }
# video codecs (ported from FilmCraft, same owner and licence)
# codecs (ported from FilmCraft, same owner and licence)
deckcraft-bitstream = { path = "crates/bitstream" }
deckcraft-h264 = { path = "crates/h264" }
deckcraft-hevc = { path = "crates/hevc" }
deckcraft-vp9 = { path = "crates/vp9" }
deckcraft-av1 = { path = "crates/av1" }
deckcraft-isobmff = { path = "crates/isobmff" }
deckcraft-matroska = { path = "crates/matroska" }
deckcraft-ogg = { path = "crates/ogg" }
deckcraft-opus = { path = "crates/opus" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -45,9 +49,7 @@ rayon = "1"
unicode-bidi = "0.3"
unicode-segmentation = "1"
unicode-linebreak = "0.1"
# Base features are wasm-safe (`std` only). The non-wasm `clock` feature is requested
# per-crate for targets that read the local clock (see crates/text).
chrono = { version = "0.4", default-features = false, features = ["std"] }
chrono = { version = "0.4", default-features = false, features = ["clock"] }
# text / rendering / formats
skrifa = "0.47"
@@ -55,23 +57,16 @@ harfrust = "0.13"
vello_cpu = "0.2"
vello_common = { version = "0.2", default-features = false }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] }
# craft-media and craft-audio share types and stay on one rev.
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "75895c0321d8cb6e175a42466cba050352b117c5", version = "=0.1.0", default-features = false }
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "75895c0321d8cb6e175a42466cba050352b117c5", version = "=0.1.0", default-features = false, features = ["opus-decode"] }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", 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 = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0" }
krilla = { version = "0.8", features = ["pdf"] }
i_overlay = "9"
quick-xml = "0.41"
quick-xml = "0.38"
zip = { version = "3", default-features = false, features = ["deflate"] }
# ui
egui = { version = "0.37", default-features = false }
egui_extras = { version = "0.37", default-features = false }
eframe = { version = "0.37", default-features = false }
egui_kittest = "0.37"
web-time = "1.1"
egui = "0.36"
egui_extras = { version = "0.36", default-features = false }
eframe = { version = "0.36", default-features = false }
egui_kittest = "0.36"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -79,47 +74,22 @@ arboard = { version = "3.6", default-features = false }
unsafe_code = "forbid"
[workspace.lints.clippy]
cognitive_complexity = "deny"
too_many_arguments = "deny"
wildcard_imports = "deny"
dbg_macro = "warn"
todo = "warn"
too_many_arguments = "allow"
type_complexity = "allow"
self_named_constructors = "allow"
large_enum_variant = "allow"
result_large_err = "allow"
# Line tables keep file and line in panics and backtraces; full debug info
# for every test binary and dependency would multiply the target dir size.
# The test profile inherits both settings.
[profile.dev.package."*"]
opt-level = 2
debug = false
[profile.dev]
opt-level = 1
debug = "line-tables-only"
[profile.release]
opt-level = 3
lto = "thin"
codegen-units = 16
debug = 0
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.8.2" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+3 -80
View File
@@ -18,89 +18,12 @@ list (author, source, license) is in ATTRIBUTION.md.
- Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) embed the fonts listed in
ATTRIBUTION.md (Inter, Carlito, Caladea, Liberation, Montserrat, Lato, Open Sans, Roboto,
Merriweather, Playfair Display, Poppins, Nunito Sans, BIZ UD, Shippori Mincho, Noto Sans
Arabic, Noto Sans Thai, Noto Sans Georgian, NanumGothic, Noto Sans Symbols, Noto Sans Symbols 2,
Noto Sans Hebrew) under the SIL Open Font License 1.1; their licence texts ship with release
packages (the exact font files and OFL texts are retained in craft-fonts releases). Native
builds may additionally read craft-fonts' separate Simplified Chinese manifest and embed LXGW
WenKai Lite 1.530 under OFL-1.1; its OFL text ships with release packages, and the exact font
and licence files are retained in craft-fonts with the LXGW Reserved Font Names. That face is
not in the web payload.
- Lucide icon paths embedded in crates/engine/src/icon_data.rs (Insert › Icons), release 1.56.0,
commit 440a1e1dfb1e712505308da46bead3c28b1f1398, https://github.com/lucide-icons/lucide.
ISC License, Copyright (c) 2026 Lucide Icons and Contributors. Icons Lucide derives from Feather
are MIT, Copyright (c) 2013-present Cole Bemis; which names those are is the list in Lucide's
LICENSE at that commit. Among the paths embedded here, the Feather-derived names are arrow-down,
arrow-left, arrow-right, arrow-up, at-sign, calendar, check, chevron-right, clipboard, clock,
compass, download, info, key, link, lock, minus, moon, move, music, plus, search, target and x.
ISC License
Copyright (c) 2026 Lucide Icons and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
The MIT License (MIT) (for the Feather-derived icons)
Copyright (c) 2013-present Cole Bemis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Arabic) under the SIL Open Font License 1.1; their licence texts ship with release packages.
Code dependencies
- symphonia (audio decoding for MP3, AAC, ALAC, FLAC, Vorbis, WAV, AIFF, CAF) is used unmodified
under the Mozilla Public License 2.0; its source is available at
https://github.com/pdeljanov/Symphonia.
- The H.264, HEVC, VP9 and AV1 crates under crates/ are ported from FilmCraft (same owner,
MIT OR Apache-2.0). The Opus decoder (craft-audio) and the MP4, Matroska and Ogg demuxers
(craft-media) come from craft-libs (same owner, MIT OR Apache-2.0).
- Krilla 0.8.2 (https://github.com/LaurenzV/krilla) is used through craft-pdf under
MIT OR Apache-2.0. craft-libs vendors that version with page/surface unwind recovery
and rejection of serialization after failed cleanup. Its upstream licence files are
retained in craft-libs/licenses/pdf-writer. Its bundled Compact ICC Profiles by Clinton Ingram
(https://github.com/saucecontrol/Compact-ICC-Profiles) are CC0-1.0; the profile
licence is retained in licenses/pdf-writer/LICENSE-ICC.txt and exact files, sources
and hashes are in ATTRIBUTION.md.
egui icon font subset (dependency asset)
----------------------------------------
epaint_default_fonts 0.37 embeds egui-icons.ttf, a five-glyph subset of
emoji-icon-font by John Slegers. The full monochrome emoji-icon-font fallback
uses the same MIT license. Upstream license text follows unchanged.
MIT License
Copyright (c) 2014 John Slegers
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- The H.264, HEVC, VP9, AV1, Opus, MP4, Matroska and Ogg crates under crates/ are ported from
FilmCraft (same owner, MIT OR Apache-2.0).
+12 -68
View File
@@ -7,19 +7,15 @@
</a>
</p>
<p align="center">
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png" width="128" height="128" alt="DeckCraft icon: a presentation screen with a bar chart on an orange tile">
</p>
<h1 align="center">DeckCraft</h1>
<p align="center">
<b>Presentations and slide shows; an open-source, modern presentation and slide designer, built in pure Rust.</b>
<b>Presentations and slide shows; an open-source, clean-room reimplementation of Microsoft PowerPoint, rebuilt in pure Rust.</b>
</p>
<p align="center">
Build decks with themes, layouts, shapes, pictures, tables, charts, transitions and animations,
open and save .pptx presentation files, and present them full screen. Native on macOS, Windows, Linux
open and save PowerPoint files, and present them full screen. Native on macOS, Windows, Linux
and FreeBSD, and in the browser. Every button is also a command that the CLI and AI agents
(through MCP) can drive.
</p>
@@ -28,10 +24,7 @@
<img alt="Status: early development" src="https://img.shields.io/badge/status-early%20development-f26b1d?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue?style=flat-square">
<img alt="Written in Rust" src="https://img.shields.io/badge/written%20in-Rust-b7410e?style=flat-square">
<img alt="Platforms" src="https://img.shields.io/badge/platforms-macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20BSD%20%C2%B7%20Web-555?style=flat-square">
<br>
<a href="https://sonarcloud.io/project/overview?id=storytold_deckcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/deckcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
<img alt="Platforms" src="https://img.shields.io/badge/platforms-macOS%20·%20Windows%20·%20Linux%20·%20BSD%20·%20Web-555?style=flat-square">
</p>
<p align="center">
@@ -81,8 +74,8 @@ Today it can:
audio and video (MP3, AAC, FLAC, ALAC, Ogg, Opus, WAV, AIFF; H.264, HEVC, VP9, AV1).
- **Present**: transitions (including Morph), entrance/emphasis/exit and motion-path animations,
by-paragraph builds, full-screen slide show, presenter view, pen, rehearse timings, media playback.
- **Exchange files**: open and save .pptx presentations, export PDF (slides, notes pages, handouts
with selectable text), PNG/JPEG, an animated GIF of the deck and outlines. Unsaved work is kept by AutoRecover.
- **Exchange files**: open and save PowerPoint `.pptx`, export PDF (slides, notes pages, handouts
with selectable text), PNG/JPEG and outlines. Unsaved work is kept by AutoRecover.
- **Automate**: 200+ commands with undo, all scriptable from the CLI, a JSON control channel and an
MCP server for AI agents.
@@ -104,9 +97,6 @@ Today it can:
## Getting started
PDF export uses the shared `craft-pdf` writer with import features disabled. See
[`crates/pdf/README.md`](crates/pdf/README.md) for the dependency and validation requirements.
```sh
git clone https://github.com/storytold/deckcraft
cd deckcraft
@@ -139,7 +129,7 @@ settings directory, beside `ui.json` and `prefs.json` (Linux `~/.config/deckcraf
`$XDG_CONFIG_HOME/deckcraft/logs/`; macOS `~/Library/Application Support/DeckCraft/logs/`; Windows
`%APPDATA%\DeckCraft\logs\`). A start from a desktop menu or the Dock has no terminal, so this file
is what to attach to a bug report: the crash guard's panic report, a failed crash-recovery save,
Parts skipped on import and audio output problems land there. Each launch moves the
PowerPoint parts skipped on import and audio output problems land there. Each launch moves the
previous log to `deckcraft.1.log` (and that one to `deckcraft.2.log`), so the log of a run that
crashed survives the next start. The file stops growing at 16 MiB. `--version` writes no file.
@@ -160,13 +150,12 @@ deckcraft-cli commands format. # list commands
deckcraft-cli run --sample --cmd 'slide.new={"layout":"titleOnly","title":"Hello"}' --save hello.deckcraft
deckcraft-cli mcp # MCP server over stdio (headless)
deckcraft-cli mcp --connect 7990 # drive the running app (deckcraft --control 7990)
deckcraft-cli mcp --automation-read-root DIR --automation-write-root DIR # confine the headless agent to folders
```
## Roadmap
DeckCraft is in **alpha**. It covers **84% of the features tracked in [`docs/target-app-parity.md`](docs/target-app-parity.md) by breadth** (92% of the core
ones, measured) and is about **55% ready for real work across all tracked capabilities** (estimated).
DeckCraft is in **alpha**. It covers **79% of PowerPoint's features by breadth** (92% of the core
ones, measured) and is about **55% of the way to replacing PowerPoint for real work** (estimated).
See [ROADMAP.md](ROADMAP.md) for the stage, numbers by dimension and what's next,
[docs/target-app-parity.md](docs/target-app-parity.md) for the full assessment,
[docs/gaps.md](docs/gaps.md) for every known shortfall and
@@ -201,10 +190,6 @@ Remove-Item Env:WGPU_BACKEND # restore the default for later
An explicit `gl` override can bring the driver crash back on affected systems. The macOS, Linux
and web backend defaults are unchanged.
DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcompiler.dll` or
`dxil.dll` is needed ("Parent device is lost" at start, #153). `$env:WGPU_DX12_COMPILER = "dxc"`
(or `"auto"`) selects wgpu's DXC handling again for troubleshooting.
### macOS
| Build | File | Notes |
@@ -224,41 +209,6 @@ DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcom
RISC-V 64 (riscv64): `deckcraft-<ver>-linux-riscv64.tar.gz`, a tarball only (cross-compiled; needs glibc 2.39+, e.g. Ubuntu 24.04+).
**Runtime libraries.** The window-system, GPU and file-dialog libraries DeckCraft needs are opened
when the app starts (`dlopen` through `x11-dl`, `xkbcommon-dl`, `ash`, `glutin` and `rfd`) instead
of being linked in, so `ldd` shows none of them: an install that satisfies the linked dependencies
can still fail at start-up with a loader error and no hint of what to install. Only
`libasound.so.2` (slide-show sound) is a hard link-time dependency, and only of the `deckcraft`
GUI — `deckcraft-cli` uses neither sound nor a display. The `.deb` and `.rpm` declare the set in
`packaging/linux/nfpm.yaml`; a tarball install or a musl system has to provide it itself:
```sh
apk add libx11 libxcursor libxrandr libxi libxkbcommon xkeyboard-config \
wayland-libs-client alsa-lib \
vulkan-loader mesa-vulkan-swrast \
mesa-gl mesa-egl mesa-dri-gallium \
xdg-desktop-portal
```
Alpine Linux `v3.22` names above; Void's musl variant uses the same `/lib/ld-musl-x86_64.so.1`
loader and the same libraries as `libX11 libXcursor libXrandr libXi libxkbcommon xkeyboard-config
wayland alsa-lib vulkan-loader mesa xdg-desktop-portal`. There is no musl build among the release
artifacts yet — this is what a build from source on musl needs at run time, and what a future musl
artifact will need (#954).
- `mesa-vulkan-swrast` is the software Vulkan driver: it runs anywhere, VMs and containers
included. On a real GPU install your vendor's driver instead (`mesa-vulkan-intel`,
`mesa-vulkan-ati`, `mesa-vulkan-nouveau`, …).
- Without Vulkan the app falls back to CPU rendering through Mesa's GL drivers. It works, but
slowly — a driver limit, not a DeckCraft bug.
- `xdg-desktop-portal` (with `xdg-desktop-portal-gtk` or `-kde`; `-wlr` has no file chooser, so
on wlroots compositors install `zenity`) is what the Open and Save dialogs talk to; `xkeyboard-config` holds the XKB keyboard data `libxkbcommon` reads.
- fontconfig and freetype are not needed: DeckCraft reads `/usr/share/fonts` itself and embeds its
presentation fonts.
Building from source on musl also needs `build-base pkgconf alsa-lib-dev` (`alsa-lib-dev` is the
ALSA headers).
### FreeBSD
| Build | File |
@@ -286,15 +236,7 @@ stand on its own.
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | **Presentations and slide shows · you are here** | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
@@ -329,13 +271,15 @@ Bundled fonts, icons, images and other assets keep their own open licenses; each
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
DeckCraft's themes, layouts, shape geometry, icons and sample decks are original work, drawn or
generated in code; no proprietary artwork, fonts, themes or templates are used.
generated in code; no Microsoft artwork, fonts, themes or templates are used.
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
part of this repository and DeckCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
<sub>Microsoft and PowerPoint are trademarks of the Microsoft group of companies. Adobe, Photoshop, Illustrator, Premiere Pro, Lightroom, Acrobat, After Effects and InDesign are trademarks or registered trademarks of Adobe Inc. in the United States and/or other countries. DeckCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Microsoft Corporation or Adobe Inc.; these names are used only to describe the workflows it is compatible with.</sub>
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
+27 -327
View File
@@ -2,30 +2,7 @@
**Stage: alpha** · next: beta, ~20 points and ~120–210 h away
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-11 · **Change:** trivial (the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** trivial (File › About replaces Account; product links, credits and appearance retained; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (progress log: fix for a workflow-breaking regression: Ctrl+C/X/V use the system clipboard again, broken for all text and objects from 0.11.1 to 0.15.0; pasted and duplicated placeholders keep their look; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (locked No Fill and no-outline click-through regression coverage added; No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-30 · **Change:** trivial (progress log: read-only `slide.actions` lists shape and table text actions; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-27 · **Change:** trivial (progress log: Set Up Slide Show ▸ Keep mouse cursor visible, #1445; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-26 · **Change:** trivial (progress log: dragging several selected slides moves them all; previous: trivial, progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-24 · **Change:** trivial (progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-29 · **Change:** trivial (progress log: the Picture Styles row leaves room for Crop and Size, #1232; previous: trivial, progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-24 · **Change:** trivial (progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-29 · **Change:** trivial (progress log: the Picture Styles row leaves room for Crop and Size, #1232; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-29 · **Change:** trivial (accessibility contrast checks now include every text run, paragraph and nested group descendant; parity summary unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-24 · **Change:** trivial (progress log: Ctrl+wheel zoom during the slide show, #1286; previous: trivial, scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-24 · **Change:** trivial (progress log: picture and embedded object fills; previous: trivial, scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-25 · **Change:** trivial (progress log: a picture in a picture placeholder is cut into the layout's shape; previous: trivial, progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-25 · **Change:** trivial (progress log: a picture in a picture placeholder is cut into the layout's shape; previous: trivial, progress log: Ctrl+wheel zoom during the slide show, #1286; previous: trivial, scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-25 · **Change:** trivial (progress log: a picture in a picture placeholder is cut into the layout's shape; previous: trivial, progress log: picture and embedded object fills; previous: trivial, scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-22 · **Change:** trivial (fill and outline edits reach group members, #1079; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-20 · **Change:** trivial (empty chart number-format sections hide values; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-18 · **Change:** minor (Symbol-font characters (U+F0xx) remap to the installed Symbol face's real Unicode on macOS, so they draw from Symbol instead of a look-alike; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-21 · **Change:** minor (proofing language for the whole presentation; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (hours to ~95% per audience added; ready 56% → 55%; stage stays alpha; previous: major, full re-measure against PowerPoint for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
DeckCraft aims at full PowerPoint parity, and to be better: faster, open (a documented zip+JSON
format plus PPTX), scriptable by agents (CLI, JSON control channel, MCP), and available everywhere
@@ -37,8 +14,8 @@ format plus PPTX), scriptable by agents (CLI, JSON control channel, MCP), and av
| | Value | Kind |
|---|---|---|
| **Feature breadth** | **84%** weighted over 191 PowerPoint features (P0 92%, P1 82%, P2 55%) | measured: `cargo xtask parity` over [docs/parity-checklist.md](docs/parity-checklist.md) |
| Menu-bar coverage | 59% of 217 app-specific PowerPoint menu items matched by name (lower bound) | measured: script over the PowerPoint menu dump and the 226 commands at d556ff9 (the registry has grown since; not re-measured) |
| **Feature breadth** | **79%** weighted over 191 PowerPoint features (P0 92%, P1 75%, P2 36%) | measured: `cargo xtask parity` over [docs/parity-checklist.md](docs/parity-checklist.md) |
| Menu-bar coverage | 59% of 217 app-specific PowerPoint menu items matched by name (lower bound) | measured: script over the PowerPoint menu dump and the 226 commands |
| **Ready for real work** | **~55%** | estimated: weighted dimensions below |
| Mainstream practitioner | ~53% | estimated: weekly-use areas × discounts for interaction (×0.92), stability (×0.92) and `.pptx` exchange (×0.88), [method](docs/target-app-parity.md#mainstream-practitioner-and-essentials-user) |
| Essentials user | ~62% | estimated: core features × discounts for launch (×0.90), clarity (×0.95) and opening received files (×0.90), [method](docs/target-app-parity.md#mainstream-practitioner-and-essentials-user) |
@@ -60,7 +37,7 @@ Calibration is the same as for the full number (see [docs/target-app-parity.md](
`.pptx`, present, add tables and charts, share as PDF, review. Core workflows work end to end (build a deck, open and save `.pptx`, present with
transitions, animations, media and presenter view, export PDF), but depth, fidelity and polish
have known gaps, and PPTX has never been tested on a corpus of real decks. Beta needs ~75% ready
and no blocking gap in `.pptx`: the real-deck corpus, the round-trip losses (#70, #74),
and no blocking gap in `.pptx`: the real-deck corpus, the round-trip losses (#70, #74, #77),
EMF/SVG pictures, the data-loss and startup-crash bugs (#60, #40, #59) and the beta list in
[docs/roadmap.md](docs/roadmap.md).
@@ -68,7 +45,7 @@ EMF/SVG pictures, the data-loss and startup-crash bugs (#60, #40, #59) and the b
| Dimension | Ready | Hours to full | Doc |
|---|---:|---|---|
| Features (breadth 84% measured, with depth) | ~62% | 140–240 | [docs/parity-checklist.md](docs/parity-checklist.md) |
| Features (breadth 79% measured, with depth) | ~62% | 140–240 | [docs/parity-checklist.md](docs/parity-checklist.md) |
| UI/UX fidelity | ~60% | 30–50 | [docs/ui-parity.md](docs/ui-parity.md) |
| File formats (PPTX, PDF, legacy, export) | ~58% | 60–110 | [docs/file-format-parity.md](docs/file-format-parity.md) |
| Hardware (GPU raster, video decode, displays, pens) | ~40% | 25–45 | [docs/hardware-parity.md](docs/hardware-parity.md) |
@@ -84,26 +61,26 @@ EMF/SVG pictures, the data-loss and startup-crash bugs (#60, #40, #59) and the b
| Area | Breadth (measured) | Ready (est.) | Hours | Doc |
|---|---:|---:|---|---|
| Application shell | 81% | ~55% | 8–14 | [ui-parity](docs/ui-parity.md) |
| Slides and sections | 92% | ~85% | 3–5 | [checklist](docs/parity-checklist.md) |
| Views | 98% | ~80% | 3–6 | [ui-parity](docs/ui-parity.md) |
| Masters and themes | 92% | ~70% | 8–14 | [checklist](docs/parity-checklist.md) |
| Shapes | 91% | ~75% | 8–14 | [ui-parity](docs/ui-parity.md) |
| Format (fill, line, effects) | 83% | ~65% | 8–14 | [ui-parity](docs/ui-parity.md) |
| Application shell | 71% | ~55% | 8–14 | [ui-parity](docs/ui-parity.md) |
| Slides and sections | 90% | ~85% | 3–5 | [checklist](docs/parity-checklist.md) |
| Views | 90% | ~80% | 3–6 | [ui-parity](docs/ui-parity.md) |
| Masters and themes | 85% | ~70% | 8–14 | [checklist](docs/parity-checklist.md) |
| Shapes | 86% | ~75% | 8–14 | [ui-parity](docs/ui-parity.md) |
| Format (fill, line, effects) | 81% | ~65% | 8–14 | [ui-parity](docs/ui-parity.md) |
| Arrange | 100% | ~90% | 1–2 | [ui-parity](docs/ui-parity.md) |
| Text | 83% | ~62% | 18–30 | [gaps](docs/gaps.md#features) |
| Tables | 97% | ~75% | 3–6 | [checklist](docs/parity-checklist.md) |
| Text | 80% | ~62% | 18–30 | [gaps](docs/gaps.md#features) |
| Tables | 89% | ~75% | 3–6 | [checklist](docs/parity-checklist.md) |
| Charts | 65% | ~45% | 12–20 | [gaps](docs/gaps.md#charts-data-grid-elements-and-the-newer-chart-types) |
| SmartArt | 50% | ~35% | 8–14 | [gaps](docs/gaps.md#smartart-editing-is-shallow) |
| Pictures | 60% | ~45% | 12–20 | [file formats](docs/file-format-parity.md) |
| SmartArt | 33% | ~25% | 10–16 | [gaps](docs/gaps.md#smartart-is-pre-drawn-shapes-only) |
| Pictures | 48% | ~45% | 12–20 | [file formats](docs/file-format-parity.md) |
| Media | 67% | ~60% | 8–14 | [file formats](docs/file-format-parity.md) |
| Transitions | 100% | ~80% | 4–8 | [animation-parity](docs/animation-parity.md) |
| Animations | 85% | ~65% | 10–16 | [animation-parity](docs/animation-parity.md) |
| Slide show and presenter view | 68% | ~60% | 10–16 | [slideshow-parity](docs/slideshow-parity.md) |
| Review | 70% | ~45% | 8–14 | [gaps](docs/gaps.md) |
| Draw (ink) | 50% | ~30% | 5–9 | [hardware-parity](docs/hardware-parity.md) |
| Undo and clipboard | 100% | ~75% | 3–5 | [ui-parity](docs/ui-parity.md) |
| Files (commands; formats above) | 75% | ~50% | in file formats | [file formats](docs/file-format-parity.md) |
| Transitions | 92% | ~80% | 4–8 | [animation-parity](docs/animation-parity.md) |
| Animations | 79% | ~65% | 10–16 | [animation-parity](docs/animation-parity.md) |
| Slide show and presenter view | 66% | ~60% | 10–16 | [slideshow-parity](docs/slideshow-parity.md) |
| Review | 60% | ~45% | 8–14 | [gaps](docs/gaps.md) |
| Draw (ink) | 33% | ~30% | 5–9 | [hardware-parity](docs/hardware-parity.md) |
| Undo and clipboard | 88% | ~75% | 3–5 | [ui-parity](docs/ui-parity.md) |
| Files (commands; formats above) | 69% | ~50% | in file formats | [file formats](docs/file-format-parity.md) |
## Languages
@@ -133,12 +110,9 @@ ships 26.
Ranked; detail and the full beta plan in [docs/roadmap.md](docs/roadmap.md).
1. **No data loss, no startup crashes:** Close's save prompt (#60), Windows GPU crashes (#40, #59),
image paste on Windows (#1414), editor soak tests. 10–20 h.
2. **PPTX on real decks:** the owned corpus now round-trips comments, links and actions, custom
shows, rotated groups, inherited placeholders, text effects and body layout, theme effects,
fills, bevels, connectors, tables, charts, animations, media, sections, masters, 3-D models
and animation bounce end. Still open: a corpus of real decks, #70, #74, EMF+ records,
MicroType Express font subsets and SVG. 36–64 h.
image paste (#53), editor soak tests. 10–20 h.
2. **PPTX on real decks:** owned corpus, round-trip checks, fixes; #70, #74, #77; EMF/WMF and SVG.
36–64 h.
3. **Localization:** catalog, system language (#15), zh-Hans, es, fr, de, ja with IME. 27–46 h.
4. **Output:** vector PDF, printing. 10–16 h.
5. **Depth that users hit:** font weights (#69), chart data and elements, Animation Pane timeline,
@@ -154,183 +128,14 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | What landed |
|---|---|
| 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 |
| 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered |
| 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop |
| 2026-11-02 | Slide show on Linux and the BSDs: Presenter View stays off when winit lists exactly one display, as in PowerPoint; if it lists none, the setting is kept. On one display the presenter window covered the show, and the hidden window stalled every frame: slide changes took up to ~1.7 s under Hyprland (#1156) |
| 2026-11-02 | Native and PPTX saves retain optional table right-to-left direction, including explicit false and omission; two-save round-trip tests keep labeled columns in order |
| 2026-11-02 | Text runs preserve alternate-language metadata independently from the main language through native and PPTX saves |
| 2026-11-02 | Picture compression measures displayed dimensions through nested group transforms; checklist score unchanged |
| 2026-11-02 | Deleting slides removes their IDs from every custom show; the cleanup is undoable and survives native save/reopen |
| 2026-11-02 | Reused slides scale their geometry and content dimensions to the destination slide, including kept source masters and layouts; the reuse picker still lacks thumbnails |
| 2026-11-02 | File › About replaces the unused Account page, with version, project links, contributor/model credits and appearance preferences |
| 2026-11-02 | PPTX reflection effects keep their authored start position, affine scale/skew, direction and fade, alignment, and rotation flag through native and PPTX saves |
| 2026-11-03 | Reuse Slides brings along referenced custom table styles, including grouped tables, and remaps conflicting style ids without changing destination tables |
| 2026-11-02 | Tiled picture fills in groups: a tile (`a:blipFill` with `a:tile`) keeps its size, offset and anchor in slide points whatever the group's child-coordinate scale, uniform or stretched unevenly, nested or flipped (also a group's own tile fill passed to its members, and a picture shape's own tile, with its shadow and reflection), and tiles with `rotWithShape="0"` keep their size in points at any zoom, as PowerPoint draws them (measured on its own PNG export of a synthetic probe deck: every grouped case within ~3/255 of the ungrouped control's own difference from PowerPoint, which is ~13/255 from resampling). Before, a group whose child space was ~1800 times smaller than its box showed one flat texel of the texture (a Venn diagram with paper-textured circles and a hatched intersection) |
| 2026-11-01 | Ctrl+V of a picture copied in a browser (Copy Image) pastes the picture, not a text box with its link and alt text; the link still pastes as text when no picture came with it |
| 2026-11-01 | Copy, Cut, Paste, Duplicate and Alt+drag of a title, body or other placeholder on a slide keep its look: the copy is a regular shape that takes the size, font, bullets, indents, autofit and box its layout and master gave it, instead of 18 pt unbulleted text |
| 2026-11-01 | Clipboard: Ctrl+C, Ctrl+X and Ctrl+V use the system clipboard again, so text and pictures paste from other apps and in-app copies paste back. Since the egui 0.37 migration (#1350) the desktop build had a clipboard that only worked inside the app. On native Wayland, text goes through egui's Wayland clipboard; HTML stays on X11, macOS and Windows |
| 2026-10-31 | No Fill shape interiors allow selection and editing of underlying objects, even when a quick style remains; hit-testing uses the renderer’s fill resolution. Outlines, rotation, text targets and actual fills keep their hit behaviour (#1621) |
| 2026-10-30 | Print-preview tests use the URL emitted by egui and its exact file path; previews are explicitly removed before the macOS process exits |
| 2026-10-30 | `slide.actions` lists shape click and hover actions and text-run hyperlinks (including table cells and grouped shapes) for audit; listing never runs an action. The UI pane is a follow-up |
| 2026-10-29 | Slide Show: going back to the previous slide plays the transition of the slide being left, reversed, as PowerPoint does, instead of the previous slide's own entrance transition (#1531); a jump (Go to Slide, links) still plays the target slide's transition |
| 2026-10-27 | Set Up Slide Show ▸ Keep mouse cursor visible: a full-screen show no longer hides a still pointer, so the choices of a branching deck stay visible and clickable; the setting is kept with the user's preferences (`ui.json`, `showKeepCursor`), off by default (#1445) |
| 2026-10-25 | A photo in a picture placeholder is cut into the shape its layout gives the placeholder, as PowerPoint draws it: a layout's round picture placeholder keeps a slide's photo in a circle with the layout's white border, where it came out as a rectangle (the reader only passed `p:sp` placeholders to `inherit_placeholder_geometry`, not `p:pic`) |
| 2026-10-28 | CLI `run --cmd-file FILE` reads UTF-8 commands in order alongside `--cmd`, skips blank/comment lines, and reports file/line errors before final save/export (#1098) |
| 2026-10-28 | MCP accepts repeated `--automation-read-root` and `--automation-write-root` flags for access to multiple folders (#1154) |
| 2026-10-26 | Slide reorder: dragging one of several selected slides in the thumbnail pane or the Slide Sorter moves the whole selection, as one run in deck order and one undo step; the slides stay selected and join the section they land in. `slide.move {ids, to}` does the same from the control channel and MCP; dragging an unselected slide still moves only that slide |
| 2026-10-26 | A space, digit or punctuation after a symbol-font character (`a:sym`, e.g. a Wingdings arrow typed in a run) draws in the run's own font, as PowerPoint does; it stayed in the symbol font, whose space is about four times as wide (synthetic probe) |
| 2026-10-29 | Review ▸ Accessibility checks text runs in every paragraph and nested group descendants for low contrast, reporting each affected shape once; the all-black control stays clear |
| 2026-10-25 | Windows installer: the Start menu shortcut takes the icon embedded in `deckcraft.exe` instead of an MSI `<Icon>`, so a taskbar pin keeps its icon after an update (#1114); a pin that already lost it has to be unpinned and pinned again once |
| 2026-10-29 | Picture Format: the Picture Styles row shows as many styles as leave room for the groups after it, and its arrow opens all 24. With every style in the row, Crop and Size sat past the ribbon's edge in any window narrower than about 2500 px, so Crop could not be seen without scrolling the ribbon (#1232). In the default 1440 px window Crop, Height and Width are now in view, and from 1600 px the whole tab fits |
| 2026-10-24 | AutoFormat as you type: a paragraph that starts with `*`, `-`, `--`, `>`, `<>`, `1.`, `1)`, `I.`, `i.`, `A.`, `a.` or `a)` and a space or tab becomes a bulleted or numbered list in that style; Backspace right after puts the typed text back, and Tools ▸ AutoCorrect and `text.autocorrect {lists}` turn it off |
| 2026-10-24 | Tables: while the caret is in a cell, dragging into another cell selects that range of cells (shaded, merged cells taken in whole), and Shift+arrow grows or shrinks it; formatting applies to the selected cells only, and Delete clears their text and keeps the table |
| 2026-10-24 | Preferences ▸ Measurement units: inches or centimetres. The Format pane's Size and Position fields, Shape Format ▸ Size on the ribbon, the Slide Size dialog and the ruler show and take the chosen unit; the deck still stores points (#1326) |
| 2026-10-23 | Chart text colour: `chart.options {textColor}` and Font Color on a selected chart colour its title, axes, legend and data labels; the colour is written to the chart part (`c:txPr` on the axes, legend, labels and chart, the title's run defaults) so an imported chart keeps its `txPr` colours through an edit and a save; text without a colour of its own takes PowerPoint's default, the theme's text colour at 65 % plus 35 % (595959 on a light theme, light grey on a dark one) |
| 2026-10-24 | A picture's own fill shows behind its transparent pixels, and an embedded object (an old equation, `p:oleObj`) takes the fill and outline of its fallback picture, as PowerPoint for Mac draws them (synthetic probe: a half-transparent PNG on orange and on yellow with an outline); on a private 166-deck corpus 51 slides of equations on coloured boxes move closer to PowerPoint's PDF, none further |
| 2026-10-23 | Format Background ▸ Apply to All also sets the background of the slide masters the slides use (and clears their layouts' overrides), so new slides keep it (#891) |
| 2026-10-22 | Table text takes the master's other-text style (`otherStyle`), shapes and text boxes the presentation's default text style, as PowerPoint for Mac draws them (synthetic probe: 14 pt cells under a 14 pt `otherStyle` and a 26 pt `defaultTextStyle`); a private deck's table had been drawn 20 pt instead of 18 |
| 2026-10-18 | Find (Ctrl+F): "Find what:" has the keyboard as soon as the dialog opens, and keeps it after Enter finds a match, so the search can be typed and changed without clicking the field (#951) |
| 2026-10-24 | Columns dialog: Home › Columns › More Columns… and Format Shape › Text Box › Columns… set the number of text columns (1 to 16) and the spacing between them in inches, in one undo step; `format.columns` with no fields opens it, and a key left out keeps the text box's own value |
| 2026-10-18 | Duplicate (Ctrl+D) repeats a move: duplicate a shape, move the copy, and the next Duplicate places its copy the same distance further on, as in PowerPoint (#966) |
| 2026-10-26 | Duplicate (Ctrl+D) names the copy as PowerPoint does: a shape with an automatic name ("Rectangle 1") gets the next one ("Rectangle 5", also for the shapes inside a duplicated group), and a name you chose ("Hero") stays as it is instead of becoming "Hero copy" |
| 2026-10-22 | Slide Show: while animations play, each frame draws only the slide's shapes over the slide's backdrop (background, master and layout graphics), rendered once and ahead of time. A full-slide picture with a glow in the layout re-rendered at every frame held animations to 2–3 frames a second (~390 ms a frame at 1080p); now ~28 ms |
| 2026-10-22 | Animation Pane ▸ Play From: with an effect selected, the pane's play button starts the canvas preview at that effect, with the effects before it already played. With nothing selected it is still Play All |
| 2026-10-21 | Opening a .pptx puts the text of shapes without an anchor at the top even when the theme's shape defaults (`spDef`) centre new shapes, as PowerPoint for Mac draws them; checked with a synthetic probe and on a private 166-deck corpus (51 slides closer to PowerPoint's PDF, none further) |
| 2026-10-23 | A shape with no fill and no line (a text box) no longer draws its shape-level glow as a halo round its box; the text's own glow is all PowerPoint shows |
| 2026-10-24 | Slide Show: Ctrl+wheel (Cmd+wheel on a Mac) over the slide zooms in and out around the pointer, four notches per doubling, up to 4×, as in PowerPoint; zooming back to the whole slide leaves the zoom, and the plain wheel still turns the page (#1286) |
| 2026-10-23 | Normal view: a slide zoomed past the window gets a horizontal and a vertical scroll bar on the axes that overflow; drag the thumb or click the track to reach every edge (#1157) |
| 2026-10-22 | Shape Fill and Shape Outline format the members of a selected group, including nested groups, in one undo step. Fill transparency retains each member's effective colour (#1079) |
| 2026-10-21 | 3-D contours, extrusion depths and bevels keep their size in points inside a group whose child coordinates scale its shapes: a 1 pt contour on a small extruded cube in a legacy group drew hundreds of points wide, a band across the slide |
| 2026-10-21 | Groups nest at most 32 deep (`arrange.group` refuses more), as deep as PPTX import reads and slides draw: a deck grouped 39 or more levels deep saved without complaint and then could not be opened again |
| 2026-10-21 | Review › Language has *Whole presentation*: one proofing language for every text box, table cell, note, master and layout, and the default for new text (`format.languageAll`, one undo step); the per-selection language still works |
| 2026-10-20 | Chart number formats with explicit empty positive, negative or zero sections hide the corresponding labels, including all values with three semicolons; a blank whole format still uses General. Synthetic formatter regressions |
| 2026-10-22 | Chart bars and their legend keys draw the series' own pattern fill (`a:pattFill`, now read and written) and draw nothing for `a:noFill`, with the series outline where it has one, as PowerPoint for Mac does (synthetic probe); they took the palette's colour before. Lines, areas and markers use a pattern's foreground colour |
| 2026-10-24 | Format Shape and Format Background ▸ Pattern fill: a gallery of the 48 preset patterns PowerPoint offers, drawn in the current colors, with Foreground and Background color menus. Format Shape could only set 25 % in accent 1 on background 1, and Format Background listed 10 presets by their XML names |
| 2026-10-25 | Format Shape ▸ Fill: Slide background fill shows the slide background through the shape (`shape.fill {background: true}`, saved as `useBgFill`). A shape opened from a file with this fill showed it as Automatic, and the pane offered no way to set it |
| 2026-10-21 | Reuse Slides: pick which slides of the other presentation to insert from a list (`slide.reuseList`, #1103) |
| 2026-10-21 | Slide list and slide sorter: Shift+click selects a range of slides and Ctrl+Shift+click adds it to the selection (`slide.selectRange`, #1105) |
| 2026-10-18 | Native chart sidecar bytes move from JSON arrays into referenced ZIP entries, with shared media byte/item limits and bounded reads; older inline sidecars still load. Synthetic format regressions cover large workbooks and malformed members |
| 2026-10-18 | Slide thumbnails and the Slide Sorter render only the slides in view: on a deck of more than 600 slides they used to evict their own thumbnails, so the pane flashed white and never finished (#969) |
| 2026-10-18 | Resizing with the mouse snaps the edge being dragged to the slide, guides and other shapes: a fixed edge that already lined up used to take the snap and leave the dragged edge free, and a fixed edge near a line shifted the dragged one (#961) |
| 2026-10-18 | Slide show: a video or audio clip is looked up on the slide it belongs to, so slides whose shape ids repeat (the PPTX import numbers each slide afresh) no longer play each other's clips (#994) |
| 2026-10-18 | About: Contributors and Models get their own fixed-size block below the tab row, so the tab row is no longer squeezed into the credits and the tabs keep answering (#843) |
| 2026-10-19 | README: the Linux runtime libraries a tarball or musl install has to provide — the `dlopen`ed X11/Vulkan/GL/dialog libraries with their Alpine and Void package names, the software-Vulkan fallback, and why fontconfig and freetype are not among them (#955) |
| 2026-10-17 | Opening a file caps absurd effect sizes (glow, soft edges, shadows, reflections, on shapes, text and table text) at what Format Shape allows: a glow of 10^18 pt in a .pptx made rendering ask for 34 GB and abort |
| 2026-10-17 | Opening a .deckcraft file whose shapes repeat an id gives the repeats fresh ids (groups, layouts and masters too), so the deck validates and edits by id find one shape |
| 2026-10-24 | Edit Points: hold Shift, Ctrl or Alt while dragging a point's handle to make it a smooth, straight or corner point, as in PowerPoint (Cmd and Option work as Ctrl and Alt on the Mac); the point keeps that type for the next drag |
| 2026-10-17 | Edit Points: turning a shape into a freeform is one undo step, so Undo brings the original shape back (it used to stay a freeform) |
| 2026-10-17 | While a placeholder's text is being edited, a click on a shape in front of it selects that shape instead of moving the caret, as in PowerPoint (#931) |
| 2026-10-16 | Symbol-font characters: a run's U+F0xx symbol code (from `<a:sym typeface="Symbol"/>`) now draws from the installed Symbol face even when it has no private-use mapping — Apple's Symbol on macOS maps the glyphs to real Unicode, so the code is remapped to that character (the Adobe Symbol encoding) instead of falling to a look-alike. Bullets and metafile text take the same remap |
| 2026-10-15 | Native saves keep an imported chart's embedded workbook, drawings and relationships; headless PPTX → edit → native save/reopen → PPTX tests verify the payloads and stale-workbook rejection |
| 2026-10-18 | Charts: a series' own data-label setting is honoured — numbers PowerPoint shows on a graph no longer disappear, and a bare `c:showVal` means on (#868) |
| 2026-10-15 | Render: quick styles render on empty placeholders — the fill gate now checks for style and line overrides too (#832) |
| 2026-10-15 | Canvas: the resize cursor follows the handle's rotated diagonal — rotated shapes showed the wrong diagonal cursor (#745) |
| 2026-10-20 | Tests: the Options dialog's Cancel, Esc and close button put the settings back the way they were (#878) |
| 2026-10-20 | Tests: Ctrl+A in the slide sorter selects every slide, as in PowerPoint (#936) |
| 2026-10-18 | Thumbnails: navigating slides with the arrow keys scrolls the thumbnail pane to keep the current slide visible (#917) |
| 2026-10-15 | PPTX trigger sequences keep separate On Click steps, including paragraph builds; synthetic import/edit/save/reopen and headless show regressions |
| 2026-10-16 | Export: PNG with a transparent background — the slide background is left out, only the slide's content is drawn (Export… dialog, File › Export, web download, `file.export`/`file.render` `transparentBackground`, `deckcraft-cli render --transparent`) (#784) |
| 2026-10-16 | Arrange ▸ Align: Align to Slide and Align Selected Objects, as in PowerPoint. One object aligns to the slide and several to each other until the other choice is ticked; the choice holds for that selection and also drives Distribute |
| 2026-10-16 | Fitted canvas: discrete mouse-wheel steps navigate immediately, including rapid and batched input, while trackpad gestures retain their cooldown and zoomed slides still pan. |
| 2026-10-16 | PPTX import: a paragraph build edited in PowerPoint (paragraphs with their own start, other shapes' effects in between, builds by 2nd-level paragraphs) takes PowerPoint's clicks in the show; it used to be rebuilt as one build, 34 clicks instead of 10 on the reporter's slide. Paragraph builds with sub-points save as PowerPoint writes them (#844) |
| 2026-10-15 | CLI: .txt and .md export includes table cell text, which it used to skip silently (#814) |
| 2026-10-15 | A `.pptx` slide that can't be read is reported, not dropped in silence: `lostSlides` from `file.open`, a message and a repaired copy in the app, a warning from `deckcraft-cli` (#203) |
| 2026-10-16 | AutoFormat as you type: ordinals (1st, 22nd, 103rd) get superscript suffixes after a space or punctuation; Tools ▸ AutoCorrect and `text.autocorrect {ordinals}` turn it off |
| 2026-10-16 | A PowerPoint Show (`.ppsx`) opened from the command line or the file association starts its slide show, as in PowerPoint; File › Open still opens it for editing (#862) |
| 2026-10-15 | Canvas: the Format and Animation Painter override the cursor to show the tool is armed (#830) |
| 2026-10-24 | Edit Points: Esc pressed before the mouse button is released cancels a point or handle drag, as in PowerPoint, and leaves the shape as it was with no undo step. Edit Points stays on after the cancel |
| 2026-10-15 | Edit Points: right-click a segment for Straight/Curved Segment, a point for Open/Close Path (`shape.segmentType`, `shape.openPath`, `shape.closePath`); Delete Segment and Add Point in the menu still to come |
| 2026-10-24 | Edit Points: right-click a segment for Add Point (at the pointer), Delete Segment (a closed outline opens there; grayed out on an open one) and Open/Close Path, as in PowerPoint (`shape.deleteSegment`) |
| 2026-10-15 | Design › Browse for Themes… with a `.pptx` or `.potx` brings its slide master and layouts, not just the theme: the master the current slide uses is replaced (a preserved one stays beside it), the template stretches to the deck's slide size, and each slide moves to the layout with the same name or kind and keeps its content. One undo step (#807) |
| 2026-10-15 | Clicking the frame of a text box or placeholder selects the box whole, so it can be moved, duplicated or deleted; only a click inside puts the caret in the text (#787) |
| 2026-10-15 | Review › Compare: Reject and Reject All drop revisions without applying them (`review.reject`); Accept All skips what was rejected |
| 2026-10-15 | PDF export and rendering: `anchorCtr` centres the drawn text block — right-aligned text no longer ran past the box edge (#736) |
| 2026-10-14 | connected MCP rejects unrelated, malformed, incomplete and oversized replies without replay; buffered unsolicited bytes force a fresh connection before sending (#718) |
| 2026-10-14 | Empty bulleted and numbered paragraphs show gray markers while editing, including on first click and after Enter. Markers use the list style and stay out of slide shows and exports. |
| 2026-10-13 | Interface font fallback continues to eligible installed faces when the first covering face is colour or exceeds the 48 MiB limit; document fallback order and the CJK/IME rendering assertions are retained (#101) |
| 2026-10-13 | PDFW2: adopt the shared writer with native unwind recovery and explicit font-embedding failures; preserve app-owned export behavior and keep reader dependencies out of production |
| 2026-10-13 | Eyedropper: Shape Fill, Shape Outline, Font Color and every other colour menu end with an Eyedropper that takes the colour drawn at a point of the slide (hover shows it, a click applies it, Esc cancels); `slide.colorAt` gives the same from scripts and MCP (#367) |
| 2026-10-13 | Slide show: Honeycomb's hexagons cover the whole slide again — the bottom quarter stayed black until the endpoint (#420) |
| 2026-10-13 | Copy and Cut from the ribbon, the slide's right-click menu and the menus put the text on the system clipboard, as Ctrl+C and Ctrl+X do (#431) |
| 2026-10-13 | Video seeks and loops keep newly decoded frames and end-of-stream notifications; stale generations are filtered when consumed (upstream #416). Deterministic queue coverage and repeated seeks across H.264, HEVC, VP9 and AV1 |
| 2026-10-14 | Presenter View handles the same keyboard navigation as the audience window, consumes handled keys before focused buttons, and remains available at the end screen. Regression tests cover presenter-only input, single-step navigation and Escape |
| 2026-10-13 | EMF and WMF rectangle clip regions (`INTERSECTCLIPRECT`, `EXCLUDECLIPRECT`, `EXTSELECTCLIPRGN`) limit later drawing. EMF+ records are still skipped |
| 2026-10-13 | Embedded fonts (`p:embeddedFontLst`) are read, written and used to draw. TrueType, OpenType and Embedded OpenType faces load; MicroType Express subsets are kept for the round trip and still draw in a stand-in |
| 2026-10-13 | Codec parsers (#426): H.264 and HEVC quantiser offsets, Matroska block times, Opus granule timing and QuickTime PCM frame sizes are range-checked before the arithmetic, so a hostile number is a format error instead of an overflow |
| 2026-10-13 | WordArt Transform: Shape Format ▸ Text Effects shows the 40 text warps and No Transform; `format.textWarp` applies one to the selected text. Adjust handles are still open |
| 2026-10-13 | PPTX corpus round-trip for decks we author (open → save → reopen, package parts and text). A notes master's header and footer are kept instead of being replaced by an empty notes master |
| 2026-10-13 | PPTX round trip of comments, hyperlinks and actions, custom shows, rotated groups, and placeholders that inherit from the layout. Paragraph default formatting (`defRPr`, including a link) and action sounds (the clip, stop-previous, and a custom show's "Show and return") are kept. Embedded fonts and comment threads stay open |
| 2026-10-13 | PPTX round trip of text effects, autofit, columns, vertical and RTL text, tab stops, line spacing, theme effects, gradient and pattern fills, 3-D bevels and connectors. A run keeps its inner shadow, reflection and soft edge, and a bevel preset with no kept 3-D XML is written back. Embedded fonts and #70, #74, #77 stay open |
| 2026-10-14 | PPTX: an owned corpus round-trips SmartArt and OLE kept as XML, audio and video bookmarks and trims, a section with a hidden slide, slide-number and date fields, ink (as freeform lines), 3-D models (`.glb`, including the fallback picture) and animation repeat, bounce end and triggers. Relationship-bearing SmartArt and OLE (#203), playback options (#74) and rewind (#77) stay open |
| 2026-10-14 | Chart trendlines are drawn: linear, exponential, logarithmic, polynomial, power and moving average, with forecast and the equation and R² label. The value axis grows to include the fit |
| 2026-10-14 | Chart trendlines round-trip (type, polynomial order, moving-average period, forecast, intercept, equation and R²). An owned corpus slice also checks combo charts with data labels, merged tables with diagonal borders, and text columns, autofit, vertical text and a WordArt warp |
| 2026-10-14 | Insert › Icons: a gallery of Lucide stroke icons (release 1.56.0) inserted as custom shapes, no fill, round stroke scaled from the 24-unit design |
| 2026-10-14 | Size and Position dialog: height, width, rotation, scale and lock aspect ratio in one undo step, from Shape Format › Size and the shape menu |
| 2026-10-14 | Review: Previous and Next comment walk every comment in the deck; the Comments pane lists every slide and highlights the one you landed on |
| 2026-10-13 | View › New Window opens a second window on the same presentation. The window has its own slide and shows edits made in the first window. Arrange All is not included |
| 2026-10-14 | File › New starter decks: Briefing, Lesson, Pitch, Field Notes, Quarterly and Evening Talk, original text on our themes (`file.new {template}`, `file.templates`). The large template gallery is still open |
| 2026-10-14 | Slide Sorter sections: Add Section, rename in place, collapse a section, and drag the bar to move that section and its slides |
| 2026-10-14 | Text: an input method's composition in a table cell is underlined in place, with the caret and candidate window in that cell |
| 2026-10-14 | Edit Photo Album (`insert.photoAlbumEdit`): reopen the album's slides and re-flow them in one undo step, with black and white, rotation, brightness, contrast and an album theme |
| 2026-10-14 | Photo Album dialog (`insert.photoAlbum`): pictures and text boxes become slides in the open presentation, one undo step |
| 2026-10-14 | Design › Colors › Customize Colors… opens Create New Theme Colors: the open master's scheme name and twelve theme colours, applied in one undo |
| 2026-10-14 | Design › Fonts › Customize Fonts… opens Create New Theme Fonts: the open master's scheme name and its heading and body latin faces, applied in one undo |
| 2026-10-14 | Alt Text: Mark as decorative opens checked when the selection already is, so OK no longer clears it |
| 2026-10-14 | Insert Hyperlink: address, email, slide and ScreenTip open from the selection, so OK no longer replaces them with `https://` and an empty tip |
| 2026-10-14 | Insert › Date and Time: the ribbon and Insert menu open a format list (datetime1–datetime13) with a language and Update automatically. OK inserts one field, or the shown text when Update is off. English has every format; en-GB, French, Japanese and Swedish list the numeric date and 24-hour time |
| 2026-10-14 | View: the Zoom dialog takes a percent or Fit and applies it on OK. View ▸ Zoom opens it; the arrow still lists the presets |
| 2026-10-13 | PPTX corpus round-trip for tables, charts, animations, media, sections and masters/layouts (open → save → reopen, package parts and text). A handout master's header, footer, date and slide number are kept |
| 2026-10-13 | Playback stays with its document and its clip (#415): switching decks or closing the last one stops the previous sound, replacing a clip plays the new one, and the duration and decode caches keep the bytes they are keyed by |
| 2026-10-13 | Slide show: a laser pointer (Cmd/Ctrl+L, the show's laser colour, no ink). Checklist row Partial. The presenter window does not move the dot |
| 2026-10-14 | Slide Show: Show Media Controls writes the show setting and hides the playback bar and GIF button during the show |
| 2026-10-14 | During a show, a typed slide number is shown and Enter goes to that slide |
| 2026-10-14 | A custom show plays only its slides: Show in the Custom Shows dialog, Set Up Slide Show, or a click action |
| 2026-10-14 | Presenter view pauses and resets its timer (T, R) and changes notes size (A-/A+, brackets). The clock shows local time. Second-display placement stays with #433 |
| 2026-10-14 | See All Slides and zoom during a show: a thumbnail grid (G, or All), click to jump, and click-to-zoom at 2× (Z). Presenter view has Black, White, All slides and Zoom |
| 2026-10-13 | The command palette skips commands that need a value, so searching for Export runs the export dialog (#79) |
| 2026-10-14 | PNG and JPEG slide export record their resolution. The default 2 pixels per point is 144 dpi, so Preview and print show the slide's real size instead of twice that |
| 2026-10-14 | Design ▸ Effects: named effect schemes (DeckCraft, Soft, Crisp, Lift, Glow, Plain) replace the theme's fills, lines and effects and leave colours and fonts. `design.effects` |
| 2026-10-14 | Slide Master: Preserve on the open master or layout, and Title and Footers placeholder checkboxes. Two commands (`master.preserve`, `master.placeholders`) |
| 2026-10-14 | Trim Media: start, end and fades open from the selected clip, so OK no longer resets them to zero |
| 2026-10-14 | Format Background: a solid fill's transparency, and for a picture transparency, tile, offset, scale, alignment and mirror. Apply to All copies a picture background onto every slide. The same `design.background` command; dialogs stay 27 |
| 2026-10-13 | Editor slide rasters sit on the physical pixel grid, so small text stays sharp on a Retina display instead of being blurred by a linear filter between pixels (#184) |
| 2026-10-14 | Copy and paste with other apps: bold, italic and underline travel as HTML (Pages keeps them); a shape with no text still copies as DeckCraft objects so Ctrl+V pastes it (#182) |
| 2026-10-13 | Animations ▸ Preview plays the current slide's animations on the editor canvas (Play All does the same); Escape or a click stops it. Checklist row Preview in editor re-scored done |
| 2026-10-14 | A two-finger twist on the trackpad rotates the selected shapes, as one undo step. Pinch-zoom is unchanged |
| 2026-10-14 | A trackpad swipe turns the page: sideways when the slide fits the window, and any flick during the slide show. One gesture turns one page. Pinch-zoom is unchanged |
| 2026-10-14 | Format Shape: the Fill transparency slider shows the selected solid fill, and leaving it no longer clears that transparency |
| 2026-10-13 | Web file picker: a picture, sound, video or outline finishes on the document and slide that asked for it, and is dropped if that presentation was closed or the picker dismissed (#414) |
| 2026-10-14 | Paragraph dialog (Home › Paragraph launcher): alignment, first-line and hanging indents, spacing before and after, line spacing, and a Tabs dialog, each applied in one undo step |
| 2026-10-14 | Font dialog (Home › Font, the shape menu, Cmd+T): family, size, bold, italic, underline, colour, strikethrough, baseline, caps and character spacing, applied in one undo step |
| 2026-10-13 | Grid Options: spacing, snap to grid, snap to other objects, and whether gridlines and guides are drawn; the on-screen grid uses that spacing |
| 2026-10-13 | WordArt adjust handles: a selected text warp shows one yellow handle per adjust, and dragging it sets that guide value (one undo step) |
| 2026-10-14 | Draw: pen pressure scales ink width when the pointer reports it (a mouse or a missing reading stays at the pen width; a stroke saved as a flat 0.5 still draws at the pen width). Tilt is not read |
| 2026-10-13 | Saving a presentation keeps the embedded workbook behind an unchanged chart, and the chart part's relationships (#335). Editing the chart drops that workbook instead of writing numbers that no longer match it |
| 2026-10-13 | A presentation whose object ids are used up refuses to grow instead of handing out duplicate ids (#407) |
| 2026-10-13 | macOS: a Finder double-click, Open With, a drop on the Dock icon and `open -a DeckCraft deck.pptx` open the file (#138, #347). `Info.plist` now declares the documents DeckCraft opens (`.deckcraft`, `.pptx`, `.potx`, `.ppsx`, the same set as the Windows installer and the Linux desktop file, kept equal by a test), and the `kAEOpenDocuments` Apple event is handled through the pinned `fmv-macos-events` crate as in GridCraft; the `-psn_` argument older macOS adds on a Finder launch is ignored. PowerPoint stays the default until the user picks DeckCraft |
| 2026-10-13 | Slide transitions like PowerPoint: every transition and option measured frame by frame against PowerPoint's video export and retuned (curves, directions, soft edges, 3-D perspective, contents moving over backgrounds); PowerPoint's own XML elements and defaults read and written (diagonal Wipe, Zoom, Shape In/Out, Glitter Hexagons, Shred In/Out, Page Curl Single); `deckcraft-cli render-transition` renders frames headless |
| 2026-10-13 | Wild text cases measured against PowerPoint (102 synthetic slides): bidi by run language, East Asian vertical text upright, mongolianVert/wordArtVert/wordArtVertRtl, underline styles and strikethrough at the font's metrics, centre/right/decimal tabs, East Asian, Thai, Hindi, Arabic and Hebrew numbering, small caps, all-caps "ß", transparent text, soft hyphens, kinsoku, rtlCol and just/dist anchoring, emoji presentation, fallback faces that no longer move the baseline |
| 2026-10-13 | Render matches PowerPoint more closely on wild shape, picture and table cases: even-odd custom paths, dashes and caps, arrowheads, radial and path gradients, tile rects, rotWithShape, gradient lines, shadows cast by what is drawn (group and perspective too), group fill, picture borders, tiles, reflection, recolour (biLevel, alphaInv, brightness/contrast), table borders and grid default, 20+ preset shapes by their ECMA formulas, default miter joins, and approximate 3-D bevels, cameras and face lighting |
| 2026-10-13 | Slide show for interactive decks: click-triggered animations play (one step per click, repeating, applied in click order), a slide the show returns to keeps its state and its triggered animations go on where they stopped, shapes an animation has hidden cannot be clicked, a shape without an action blocks the one beneath it, hand cursor over clickable shapes, "advance on click" off respected |
| 2026-10-12 | SmartArt import: text laid out on its `dsp:txXfrm` text rectangle, not squeezed into the shape (list layouts no longer show text in narrow columns) |
| 2026-10-12 | Title bar: Export button next to Save, opening the Export dialog on every platform (a shortcut beside File › Export) |
| 2026-10-13 | PPTX export writes modern threaded comments (`p188`) next to the flattened legacy part; replies and resolved state survive a round trip, and real PowerPoint decks stop importing their comments twice (#70) |
| 2026-10-12 | Canvas: a right click selects the shape under the pointer before the context menu opens (`contextclick` pointer kind for the control channel and MCP); in edited text the menu offers text items |
| 2026-10-12 | Canvas: dragging the frame of a text box being edited moves it (move cursor on the frame, one undo step); the caret zone follows rotated boxes |
| 2026-10-13 | Start screen: a missing Recent file is marked and its click shows the error there; entries can be removed from the list (#172) |
| 2026-10-12 | Tables: the caret and text selection show in the cell being edited; clicks and double-clicks place the caret in the clicked cell (and select the word); dragging inner column borders, the right edge and row borders resizes them in one undo step; Tab skips cells hidden under a merge |
| 2026-10-12 | Objects off the slide show and can be selected and moved around it in Normal view, as in PowerPoint; the show, exports and thumbnails still clip to the slide (#270) |
| 2026-10-12 | Korean, Japanese and Chinese input: IME composition shown in place and underlined, one undo step per composition, candidate window at the caret (slide text, notes, fields); interface text (title, notes, outline, sections, comments) borrows installed fonts for scripts the interface fonts lack (#101) |
| 2026-10-12 | Selection Pane like PowerPoint (#133): front-most first, groups fold, drag and drop restacks among siblings, Bring Forward / Send Backward, Show All / Hide All, eye, rename in place, keyboard; Lock (pane padlock, canvas menu) keeps objects from moving, sizing or rotating and round-trips PowerPoint's locking attributes |
| 2026-10-12 | Text keys like PowerPoint for Windows (#268): Ctrl+arrows and Ctrl+Shift+arrows by word (punctuation, CJK, emoji, RTL), Ctrl+Backspace/Delete with smart spacing, Ctrl+Up/Down by paragraph, Ctrl+Home/End, End on wrapped lines, Ctrl+]/[ and Ctrl+Shift+>/< font size, Shift+F3 case cycle, word and paragraph selection |
| 2026-10-12 | EMF/WMF pictures draw their text (fonts, alignment, dx advances, escapement, symbol fonts), pattern and hatch brushes, PATBLT and the XOR/AND see-through shadow; legacy OLE objects show their VML preview and ActiveX controls their pictures |
| 2026-10-12 | File tab (Backstage) like PowerPoint's (#76): File or Alt+F opens Home, New, Open, Info, Save, Save As, Print, Export, Close, Account and Options over the window, Esc or Back returns, arrows walk the side menu; the start screen is File › Home. Pages run the existing file commands; new `file.info`, print slide ranges (`"1-3, 5"`), Print through a PDF, Ctrl+P, and Close/Ctrl+W ask about unsaved changes |
| 2026-10-12 | WordArt text warps (`prstTxWarp`): all 40 presets drawn, curves fitted to PowerPoint by observation; warp adjusts round-trip |
| 2026-10-12 | Render: line widths, dashes and arrowheads inside a group no longer scale with the group's child-coordinate mapping, so a group in a small legacy child space (scale about 1600) draws thin lines instead of covering the slide (#233) |
| 2026-10-12 | `deckcraft-cli help` and each subcommand's `--help` explain the CLI to an agent; `describe` spells out a command's parameters and what it acts on; `commands` lists one command per line |
| 2026-10-11 | Animated GIF export of the deck: the Export… dialog (Animated GIF), `file.export` format `gif`, CLI and MCP (#171) |
| 2026-10-10 | Progress docs restructured; full re-measure (breadth 79%, ready ~55%, mainstream ~53%, essentials ~62%, alpha). Landed: Animation Painter (#54), Morph geometry outlines (#27), animated GIF playback (#39), hyperlink colour and following links in the show (#37, #45), date fields in their own format (#36), flipped shapes keep readable text (#35), show transition fix (#46), start screen from the Home button (#49), MCP export lists PDF (#65), OmaStore manifest (#57) |
| 2026-10-10 | Progress docs restructured to the craftrules standard; full re-measure (breadth 79%, ready ~55%, mainstream ~53%, essentials ~62%, alpha). Landed: Animation Painter (#54), Morph geometry outlines (#27), animated GIF playback (#39), hyperlink colour and following links in the show (#37, #45), date fields in their own format (#36), flipped shapes keep readable text (#35), show transition fix (#46), start screen from the Home button (#49), MCP export lists PDF (#65), OmaStore manifest (#57) |
| 2026-10-09 | v0.4.0 released. UAX #9 bidi and Arabic shaping (#4), Morph with Words and Characters (#5), tables grow to fit and PDF cell text (#14), rotating log file (#7), DX12 default on Windows (#16), H.264/HEVC overflow hardening (#2), PPTX sniffing anywhere in the zip (#19) |
| 2026-10-08 | v0.2.0 and v0.3.0 released: Windows arm64, Flatpak aarch64, AppImage zsync updates, branded DMG |
| 2026-10-07 | v0.1.0 released, signed and notarized; About window with contributor credits (#3); PrintCraft renamed PdfCraft |
@@ -341,114 +146,9 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | Change | Summary |
|---|---|---|
| 2026-11-11 | trivial | Opus and container code moved to craft-libs crates; parity scores unchanged |
| 2026-11-04 | trivial | Ogg Opus recovery duration includes its recovered tail; parity scores unchanged |
| 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged |
| 2026-11-03 | trivial | Reuse Slides brings referenced custom table styles along; scores unchanged |
| 2026-11-03 | trivial | Progress log: web `?host=parent` bridge to a framing page; scores unchanged |
| 2026-11-02 | trivial | File › About replaces Account; product links, credits and appearance retained |
| 2026-11-02 | trivial | Progress log: tiled picture fills keep their size in scaled groups. Scores and milestone names unchanged |
| 2026-11-01 | trivial | Workflow-breaking regression fixed: the desktop build uses the system clipboard again (eframe `clipboard` feature) |
| 2026-10-31 | trivial | No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged |
| 2026-10-30 | trivial | Progress log: read-only slide action inspection; parity scores unchanged |
| 2026-10-29 | trivial | Progress log: going back in the slide show reverses the left slide's transition (#1531). Scores and milestone names unchanged |
| 2026-10-29 | trivial | Progress log: the Picture Styles row leaves room for Crop and Size (#1232). Scores and milestone names unchanged |
| 2026-10-25 | trivial | Progress log: a picture in a picture placeholder takes the layout's shape. Scores and milestone names unchanged |
| 2026-10-28 | trivial | Progress log: CLI command-file input (#1098). Scores and milestone scope unchanged. |
| 2026-10-28 | trivial | Progress log: MCP accepts multiple automation read and write roots (#1154). Scores and milestone names unchanged |
| 2026-10-26 | trivial | Progress log: dragging several selected slides moves them all. Scores and milestone names unchanged |
| 2026-10-29 | trivial | Review: accessibility contrast checks all runs, paragraphs and nested group descendants; checklist score and headline figures unchanged |
| 2026-10-25 | trivial | Progress log: Windows shortcut icon survives updates (#1114). Scores and milestone names unchanged |
| 2026-10-29 | trivial | Progress log: the Picture Styles row leaves room for Crop and Size (#1232). Scores and milestone names unchanged |
| 2026-10-24 | trivial | Progress log: selecting a range of table cells by dragging. Scores and milestone names unchanged |
| 2026-10-24 | trivial | Progress log: measurement units in centimetres (#1326). Scores unchanged |
| 2026-10-22 | trivial | Progress log: Animation Pane ▸ Play From. Scores unchanged |
| 2026-10-24 | trivial | Progress log: Ctrl+wheel zoom during the slide show (#1286). Scores and milestone names unchanged |
| 2026-10-23 | trivial | Progress log: scroll bars on the zoomed slide pane (#1157). Scores and milestone names unchanged |
| 2026-10-24 | trivial | Progress log: the Columns dialog. Scores and milestone names unchanged |
| 2026-10-24 | trivial | Progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option. Scores and milestone names unchanged |
| 2026-10-20 | trivial | Explicit empty chart number-format sections hide their values; blank whole-code General fallback is retained. Synthetic formatter regressions; chart-element scores and readiness estimates unchanged |
| 2026-10-21 | trivial | Progress log: Reuse Slides picker (#1103). Scores and milestone names unchanged |
| 2026-10-21 | trivial | Progress log: slide range selection (#1105). Scores and milestone names unchanged |
| 2026-10-18 | minor | Native chart payloads use referenced ZIP members and share media byte/item limits; old inline sidecars remain readable. Synthetic tests cover multi-megabyte layout, all shape owners, shared budgets, missing/corrupt members and invalid references. Scores and milestone scope unchanged |
| 2026-10-16 | minor | Symbol-font U+F0xx codes remap to the installed Symbol face's real Unicode (Apple Symbol on macOS) |
| 2026-10-15 | trivial | Progress log: chart package parts survive a native save. Scores and milestone names unchanged |
| 2026-10-18 | trivial | Progress log: thumbnails of huge decks render only the slides in view (#969) |
| 2026-10-15 | trivial | Progress log: PPTX trigger click-step round trip. Feature scores and milestone names unchanged |
| 2026-10-16 | trivial | Progress log: PNG export with a transparent background (#784) |
| 2026-10-16 | trivial | Progress log: a `.ppsx` from the system starts the slide show (#862) |
| 2026-10-26 | trivial | Progress log: spaces after symbol-font characters |
| 2026-10-24 | trivial | Progress log: picture and embedded object fills |
| 2026-10-22 | trivial | Progress log: table text takes the master's other-text style |
| 2026-10-16 | trivial | Progress log: responsive mouse-wheel navigation on the fitted canvas |
| 2026-10-21 | trivial | Progress log: theme `spDef` anchor no longer applied to a file's own shapes |
| 2026-10-21 | trivial | Progress log: 3-D sizes in scaled groups stay in points |
| 2026-10-22 | trivial | Progress log: chart series pattern and no fills |
| 2026-10-15 | trivial | Progress log: Browse for Themes applies a template's master and layouts (#807) |
| 2026-10-15 | trivial | Progress log: Compare Reject and Reject All |
| 2026-10-16 | trivial | Progress log: PPTX paragraph builds edited in PowerPoint keep their clicks (#844) |
| 2026-10-14 | trivial | remote MCP checks reply IDs, envelopes and bounded newline framing (#718) |
| 2026-10-14 | minor | Gray list markers on empty paragraphs while editing; caret keeps the list indent before typing |
| 2026-10-14 | minor | Community PR wave folded: headline breadth 84% over 191 features (P0 92%, P1 82%, P2 55%) and the feature-area breadths from `cargo xtask parity`; one row per area; Upcoming item 2 merged; per-PR count notes dropped from the progress log. Ready stays ~55%, stage alpha |
| 2026-10-13 | trivial | Progress log: Eyedropper in the colour menus, slide.colorAt (#367) |
| 2026-10-13 | trivial | Progress log: video seek frame-loss race and regression coverage |
| 2026-10-14 | minor | Presenter keyboard navigation and end-screen controls |
| 2026-10-13 | trivial | Progress log: EMF/WMF rectangle clip regions |
| 2026-10-13 | trivial | Progress log: embedded fonts |
| 2026-10-13 | trivial | Progress log: codec parsers reject overflowing numeric fields (#426) |
| 2026-10-13 | trivial | Progress log: owned PPTX corpus round-trip; notes-master header and footer |
| 2026-10-13 | trivial | Progress log: PPTX corpus for comments, links, custom shows, groups and inherited placeholders |
| 2026-10-13 | trivial | Progress log: PPTX corpus for text effects, body layout, theme effects, fills, bevels and connectors |
| 2026-10-14 | trivial | Progress log: PPTX corpus for 3-D models, media bookmarks and animation bounce end |
| 2026-10-14 | trivial | Progress log: chart trendlines are drawn |
| 2026-10-14 | trivial | Progress log: chart trendlines |
| 2026-10-14 | trivial | Progress log: Lucide icon gallery |
| 2026-10-14 | trivial | Progress log: Size and Position dialog. Breadth stays 79%, ready stays ~55% |
| 2026-10-14 | trivial | Progress log: previous and next comment |
| 2026-10-13 | trivial | Progress log: View › New Window |
| 2026-10-14 | trivial | Progress log: six original starter decks |
| 2026-10-14 | trivial | Progress log: Slide Sorter sections |
| 2026-10-14 | trivial | Progress log: IME underlines in table cells |
| 2026-10-14 | trivial | Progress log: Photo Album dialog. Breadth stays 79%, ready ~55% |
| 2026-10-14 | trivial | Progress log: Edit Photo Album. Breadth stays 79%, ready ~55% |
| 2026-10-14 | trivial | Progress log: Create New Theme Colors |
| 2026-10-14 | trivial | Progress log: Create New Theme Fonts |
| 2026-10-14 | trivial | Progress log: Alt Text decorative checkbox |
| 2026-10-14 | trivial | Progress log: Hyperlink dialog follows the selection |
| 2026-10-14 | trivial | Progress log: Insert › Date and Time dialog (28 dialogs, 226 commands; breadth and readiness unchanged) |
| 2026-10-14 | trivial | Progress log: Zoom dialog |
| 2026-10-13 | trivial | Progress log: owned PPTX corpus for more deck kinds; handout-master text |
| 2026-10-13 | trivial | Progress log: media playback follows the open document and clip (#415) |
| 2026-10-13 | trivial | Progress log: laser pointer. Headline P2 36% → 39% to match the checklist (the row moves P2 unweighted 38% → 39%; breadth stays 79%) |
| 2026-10-14 | trivial | Progress log: Show Media Controls |
| 2026-10-14 | trivial | Progress log: go to slide shows the typed number. Breadth stays 79% |
| 2026-10-14 | trivial | Progress log: custom show playback. Breadth stays 79% |
| 2026-10-14 | trivial | Progress log: presenter timer pause/reset, clock and notes size. Breadth stays 79% |
| 2026-10-14 | trivial | Progress log: See All Slides and zoom during a show. Breadth stays 79% |
| 2026-10-13 | trivial | Progress log: command palette Export (#79) |
| 2026-10-14 | trivial | Progress log: Design ▸ Effects |
| 2026-10-14 | trivial | Progress log: Slide Master Preserve and Title/Footers placeholders. Percentages unchanged |
| 2026-10-14 | trivial | Progress log: Trim Media dialog follows the selection |
| 2026-10-14 | trivial | Progress log: Format Background picture and solid options |
| 2026-10-13 | trivial | Progress log: editor rasters on the Retina pixel grid (#184) |
| 2026-10-14 | trivial | Progress log: copy and paste rich text and pictures with other apps |
| 2026-10-13 | trivial | Progress log: animation preview on the editor canvas; breadth 80%, Animations 85% |
| 2026-10-14 | trivial | Progress log: Format Shape fill transparency follows the selection |
| 2026-10-13 | trivial | Progress log: web file picker keeps its document and slide (#414) |
| 2026-10-14 | trivial | Progress log: Paragraph dialog |
| 2026-10-14 | trivial | Progress log: Font dialog |
| 2026-10-13 | trivial | Progress log: Grid Options dialog |
| 2026-10-14 | trivial | Progress log: pen pressure scales ink width |
| 2026-10-13 | trivial | Progress log: chart workbook round-trip (#335) |
| 2026-10-13 | trivial | Progress log: Finder opens presentations on macOS (#138) |
| 2026-10-13 | trivial | Progress log: wild text cases |
| 2026-10-13 | trivial | Progress log: slide show for interactive decks |
| 2026-10-12 | minor | Progress log: table cell editing and border resizing |
| 2026-10-12 | trivial | Progress log: File tab (Backstage, #76) |
| 2026-10-12 | trivial | Progress log: lines in scaled groups (#233) |
| 2026-10-11 | minor | Progress log: animated GIF export (#171); P2 breadth 36% → 37%, overall breadth stays 79% |
| 2026-10-10 | minor | Readiness-by-audience table with hours to ~95% for full, mainstream and essentials |
| 2026-10-10 | minor | Added mainstream practitioner (~53%) and essentials user (~62%); features recomputed from written area weights, ready ~56% → ~55% |
| 2026-10-10 | minor | Stage checked against the new core-workflow gate: passes, stays alpha |
| 2026-10-10 | major | Restructured: stage, two numbers, dimensions, features, languages; parity estimate moved to docs/target-app-parity.md, "Working today" to its evidence section, the alpha checklist to docs/roadmap.md |
| 2026-10-10 | major | Restructured to craftrules `standards/progress-docs.md`: stage, two numbers, dimensions, features, languages; parity estimate moved to docs/target-app-parity.md, "Working today" to its evidence section, the alpha checklist to docs/roadmap.md |
| 2026-10-07 | major | Alpha checklist (~80% to a self-defined alpha), breadth ~80%, overall ~62%, ~190 h to full parity |
-3
View File
@@ -17,6 +17,3 @@ path = "src/main.rs"
deckcraft-engine = { workspace = true }
deckcraft-mcp = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
zip = { workspace = true }
-83
View File
@@ -1,83 +0,0 @@
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
//! flag must not silently remove a root and leave the server unconfined.
use std::path::PathBuf;
pub struct AutomationArgs {
pub read_roots: Vec<PathBuf>,
pub write_roots: Vec<PathBuf>,
}
impl AutomationArgs {
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
Self { read_roots: read_root.into_iter().collect(), write_roots: write_root.into_iter().collect() }
}
/// Returns whether this argument is a root flag. Both spellings (`--flag DIR` and
/// `--flag=DIR`) may be repeated.
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
let roots = match flag {
"--automation-read-root" => &mut self.read_roots,
"--automation-write-root" => &mut self.write_roots,
_ => return Ok(false),
};
let value = match inline {
Some(value) => value.to_owned(),
None => {
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
if value.starts_with('-') {
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
}
value
}
};
if value.is_empty() {
return Err(format!("{flag} needs a non-empty folder"));
}
roots.push(value.into());
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roots_are_repeated_and_other_arguments_are_left() {
let mut roots = AutomationArgs::new(None, None);
let mut args = ["a folder".to_owned(), "deck.pptx".to_owned()].into_iter();
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
assert!(roots.consume("--automation-read-root=other", &mut args).unwrap());
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
assert!(!roots.consume("--sample", &mut args).unwrap());
assert_eq!(roots.read_roots, [PathBuf::from("a folder"), PathBuf::from("other")]);
assert_eq!(roots.write_roots, [PathBuf::from("out")]);
assert_eq!(args.next().as_deref(), Some("deck.pptx"));
}
#[test]
fn invalid_operands_leave_roots_unchanged() {
for flag in ["--automation-read-root", "--automation-write-root"] {
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
let mut args = operand.map(str::to_owned).into_iter();
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
assert_eq!(roots.read_roots, [PathBuf::from("read")]);
assert_eq!(roots.write_roots, [PathBuf::from("write")]);
}
let mut roots = AutomationArgs::new(None, None);
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
}
}
#[test]
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
let mut roots = AutomationArgs::new(None, None);
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
assert_eq!(roots.read_roots, [PathBuf::from("-folder")]);
assert_eq!(roots.write_roots, [PathBuf::from("./-folder")]);
}
}
-198
View File
@@ -1,198 +0,0 @@
pub struct Subcommand {
pub name: &'static str,
pub usage: &'static str,
pub summary: &'static str,
pub details: &'static str,
}
pub const SUBCOMMANDS: &[Subcommand] = &[
Subcommand {
name: "info",
usage: "info FILE",
summary: "print a presentation's slides, layouts and theme as JSON",
details: "Prints FILE (.deckcraft or .pptx) as JSON: its slides (index, id, title, layout, how many shapes,
notes, transition), its layouts, theme fonts, sections and slide size.
The shapes of one slide, with their ids, boxes and text, come from the slide.inspect command:
deckcraft-cli run --in deck.deckcraft --print --cmd 'slide.inspect={\"index\":0}'",
},
Subcommand {
name: "render",
usage: "render (FILE | --sample) [--slide N | --all] [--scale S] [--edit] [--transparent] OUT",
summary: "draw slides as PNG images",
details: "Draws slides of FILE, or of the sample presentation with --sample, as PNG images. FILE comes first;
OUT is the image to write. With --all, OUT is a folder that gets one slide-01.png, slide-02.png… per
slide. Prints each image's path and size.
--slide N the slide at index N; indices start at 0, and 0 is the default
--scale S pixels per point, 2 by default: a 960×540 slide becomes 1920×1080
--edit draw what the editor shows: placeholder prompts and their dashed outlines
--transparent leave the slide background out, so only what is on the slide is drawn
deckcraft-cli render deck.deckcraft --slide 2 slide-3.png",
},
Subcommand {
name: "render-transition",
usage: "render-transition FILE --slide N --t T[,T...] [--width PX] OUT.png",
summary: "draw frames of the transition into a slide as PNG images",
details: "Draws the transition into slide N of FILE at each time T, from 0 (the slide before) to 1 (slide N),
as PNG images. With one T, OUT.png is the image; with several, each frame is written next to it as
OUT-t0.250.png and so on. Prints each image's path, size, transition and time.
--slide N the slide the transition leads into; indices start at 0
--t T,T... the times to draw, comma-separated
--width PX the image width in pixels, twice the slide width in points by default
deckcraft-cli render-transition deck.deckcraft --slide 1 --t 0.25,0.5,0.75 fade.png",
},
Subcommand {
name: "convert",
usage: "convert IN OUT",
summary: "save a presentation in the format OUT's extension names",
details: "Opens IN (.deckcraft or .pptx) and writes it to OUT, in the format OUT's extension names:
.deckcraft, .pptx, .pdf, .txt or .md for the outline, .png or .jpg for the first slide, .gif for an
animated GIF with one frame per slide. Other extensions are refused. Prints OUT.
deckcraft-cli convert deck.deckcraft deck.pptx",
},
Subcommand {
name: "run",
usage: "run [--in FILE | --sample] [--cmd COMMAND[=PARAMS] | --cmd-file FILE]... [--save OUT] [--export OUT [--export-params JSON]] [--print]",
summary: "run commands on a presentation, then save or export it",
details: "Runs commands, in order, on one presentation: FILE with --in, the sample presentation with --sample,
else a new one with an empty title slide. Then --save writes the presentation: .deckcraft keeps
everything; .pptx, .pdf and .md (the outline) are written as convert writes them. --export writes the
current slide as .png or .jpg, or the presentation as .pdf, .pptx or an animated .gif (one frame per
slide). --export-params passes file.export options as one JSON object, such as
'{\"width\": \"large\", \"secondsPerSlide\": 3, \"loop\": false, \"slides\": [0, 1, 2]}' for a GIF
(`deckcraft-cli describe file.export` lists them).
Each --cmd is one command: COMMAND is a command id, then `=`, then the command's parameters as one
JSON object. Quote it for the shell. A command that needs no parameters is just its id.
--cmd-file FILE reads the same commands from a UTF-8 text file, one per line, avoiding shell quoting
and command-line length limits. Each line can be up to 16 MiB, including commands with embedded
media data. Blank lines and full-line # comments are ignored, as is surrounding whitespace. CRLF
line endings and an optional UTF-8 BOM at the start of the file are accepted.
Repeat --cmd-file or mix it with --cmd: commands execute in the order those options appear.
File errors name the path; line-reading, JSON and command errors also name the line number.
deckcraft-cli run --cmd-file commands.txt --cmd slide.next --save result.deckcraft
deckcraft-cli run \\
--cmd 'slide.new={\"layout\":\"titleOnly\",\"title\":\"Q3 results\"}' \\
--cmd 'shape.insert={\"preset\":\"roundRect\",\"rect\":[80,160,320,120],\"text\":\"Revenue\"}' \\
--cmd 'format.size={\"size\":28}' \\
--save q3.deckcraft
`deckcraft-cli commands` lists the command ids; `deckcraft-cli describe COMMAND` explains one and its
parameters.
What the ids don't say:
- Positions and sizes are in points on a 960×540 slide, x to the right and y down; a rect is
[x, y, width, height].
- Slide indices start at 0. slide.new inserts after the current slide and makes the new one current;
slide.go {\"index\": N} makes slide N current.
- Shape ids are looked up on the current slide only.
- A command that adds a shape (shape.insert, insert.textBox, insert.table…) selects it. format.* acts
on the selected text or shapes; edit.select {\"ids\": [...]} selects others. Many shape commands
take the ids directly; `deckcraft-cli describe COMMAND` says what a command acts on.
If a command fails, run stops there and saves nothing. --print shows each command's answer, such as
the id of an inserted shape.",
},
Subcommand {
name: "commands",
usage: "commands [FILTER]",
summary: "list the commands run can use, one per line",
details: "Lists the commands that run --cmd, app and the MCP server take, one per line: the id, its name in
the app and its parameters. FILTER keeps the commands whose id or name contains it, ignoring case.
deckcraft-cli commands format.
In the parameters, `?` marks an optional one, a spaced ` | ` separates alternatives and `→` shows what
the command answers. `deckcraft-cli describe COMMAND` spells one command out.",
},
Subcommand {
name: "describe",
usage: "describe COMMAND",
summary: "explain one command and its parameters",
details: "Explains one command: what it is in the app, each of its parameters, what it answers, and how run
calls it.
deckcraft-cli describe shape.insert",
},
Subcommand {
name: "app",
usage: "app [--port PORT] COMMAND [PARAMS] | --method METHOD [PARAMS]",
summary: "run a command in the DeckCraft app started with --control",
details: "Sends one request to the DeckCraft app started with `deckcraft --control PORT` (port 7979 by default)
and prints its answer as JSON. COMMAND [PARAMS] runs a command, as run --cmd does; --method METHOD
[PARAMS] calls a control-channel method such as ui.screenshot. PARAMS is a JSON object.
deckcraft-cli app shape.insert '{\"preset\":\"star5\",\"rect\":[100,100,200,200]}'
deckcraft-cli app --method ui.screenshot '{\"path\":\"/tmp/shot.png\"}'",
},
Subcommand {
name: "mcp",
usage: "mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...",
summary: "serve the commands to an agent over MCP on stdio",
details: "Runs a Model Context Protocol server on stdin and stdout. It works on its own presentation without a
window, or with --connect PORT (or host:port) on the DeckCraft app started with --control PORT.
--sample opens the sample presentation.
--automation-read-root DIR and --automation-write-root DIR confine every file the agent's commands read
(open, pictures, audio, video) and write (save, export, PDF) to those folders, links followed. Repeat either
flag to grant access to more folders; a root left out grants none of its access. They run the in-process
server, so they conflict with --connect (a running app is not confined by them).",
},
Subcommand {
name: "bench",
usage: "bench (FILE | --sample) [--runs N] [--json]",
summary: "time opening, drawing, saving and exporting a presentation",
details: "Times how long FILE, or the sample presentation with --sample, takes to open, to draw each slide, to
save as .deckcraft and .pptx, to reopen as .pptx and to export as .pdf, and the peak memory. Prints the
median and slowest of N runs (5 by default, 1 to 1000) as a table, or as JSON with --json.
deckcraft-cli bench deck.pptx --runs 10",
},
Subcommand {
name: "links",
usage: "links",
summary: "print the DeckCraft community and project links",
details: "Prints the DeckCraft community and project links.",
},
Subcommand { name: "version", usage: "--version", summary: "print the version", details: "Prints the version of deckcraft-cli." },
];
pub fn page(name: &str) -> Option<String> {
let name = match name {
"help" | "--help" | "-h" => return Some(overview()),
"--version" | "-V" => "version",
name => name,
};
SUBCOMMANDS.iter().find(|s| s.name == name).map(|s| format!("usage: deckcraft-cli {}\n\n{}", s.usage, s.details))
}
pub fn overview() -> String {
let width = SUBCOMMANDS.iter().map(|s| s.usage.split(' ').next().unwrap_or_default().len()).max().unwrap_or_default();
let list: Vec<String> =
SUBCOMMANDS.iter().map(|s| format!(" {:<width$} {}", s.usage.split(' ').next().unwrap_or_default(), s.summary)).collect();
format!(
"deckcraft-cli works on DeckCraft presentations (.deckcraft, .pptx) without a window.
{}
A presentation is edited by running commands on it:
deckcraft-cli run --cmd 'slide.new={{\"title\":\"Q3 results\"}}' --save q3.deckcraft
`deckcraft-cli help SUBCOMMAND`, or `deckcraft-cli SUBCOMMAND --help`, explains one subcommand;
`deckcraft-cli help run` explains how to write a command.
If an output reader closes early, run, render, render-transition and convert continue; their exit
status reflects the work, not output delivery. Stop the process to cancel them.",
list.join("\n")
)
}
+61 -663
View File
@@ -1,122 +1,87 @@
//! Headless DeckCraft. `deckcraft-cli help` explains each subcommand (`help.rs`).
//! Headless DeckCraft.
//!
//! ```text
//! deckcraft-cli info FILE # slides, titles, layouts (JSON)
//! deckcraft-cli render (FILE | --sample) [--slide N | --all] [--scale S] OUT.png|OUT_DIR
//! deckcraft-cli convert IN OUT # .deckcraft ⇄ .pptx, outline .txt, .png (first slide)
//! deckcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--save OUT] [--export OUT] [--print]
//! deckcraft-cli commands [FILTER] # list commands (JSON)
//! deckcraft-cli describe ID # one command
//! deckcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON] # drive the running app
//! deckcraft-cli mcp [--connect PORT] [--sample] # MCP server over stdio
//! deckcraft-cli links | --version
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod automation_args;
mod help;
use std::process::ExitCode;
use std::sync::atomic::{AtomicBool, Ordering};
use deckcraft_engine::Session;
use serde_json::{Value, json};
static STDOUT_CLOSED: AtomicBool = AtomicBool::new(false);
macro_rules! outln {
($($arg:tt)*) => {{
if !STDOUT_CLOSED.load(Ordering::Relaxed) && let Err(e) = stdout_line(format_args!($($arg)*)) {
use std::io::Write as _;
if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
if e.kind() == std::io::ErrorKind::BrokenPipe {
STDOUT_CLOSED.store(true, Ordering::Relaxed);
} else {
eprintln!("deckcraft-cli: can't write to stdout: {e}");
std::process::exit(1);
std::process::exit(0);
}
eprintln!("deckcraft-cli: can't write to stdout: {e}");
std::process::exit(1);
}
}};
}
fn stdout_line(args: std::fmt::Arguments<'_>) -> std::io::Result<()> {
use std::io::Write as _;
#[cfg(unix)]
let mut stdout = {
use std::os::fd::AsFd as _;
std::fs::File::from(std::io::stdout().as_fd().try_clone_to_owned()?)
};
#[cfg(not(unix))]
let mut stdout = std::io::stdout();
stdout.write_all(format!("{args}\n").as_bytes())
}
const USAGE: &str = "usage: deckcraft-cli info FILE
deckcraft-cli render (FILE | --sample) [--slide N | --all] [--scale S] [--edit] OUT
deckcraft-cli convert IN OUT
deckcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--save OUT] [--export OUT] [--print]
deckcraft-cli commands [FILTER]
deckcraft-cli describe COMMAND
deckcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]
deckcraft-cli mcp [--connect PORT] [--sample]
deckcraft-cli links | --version";
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
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)) {
outln!("{page}");
return ExitCode::SUCCESS;
}
match args.first().map(String::as_str) {
Some("help" | "--help" | "-h") => match rest.first() {
None => {
outln!("{}", help::overview());
ExitCode::SUCCESS
}
Some(name) => match help::page(name) {
Some(page) => {
outln!("{page}");
ExitCode::SUCCESS
}
None => unknown(name),
},
},
Some("--version" | "-V" | "version") => {
outln!("deckcraft-cli {}", env!("CARGO_PKG_VERSION"));
ExitCode::SUCCESS
}
Some("info") => report(info(rest)),
Some("bench") => report(bench(rest)),
Some("render") => report(render(rest)),
Some("render-transition") => report(render_transition(rest)),
Some("convert") => report(convert(rest)),
Some("run") => report(run(rest)),
Some("commands") => {
let s = Session::new();
let f = rest.first().map(|x| x.to_lowercase());
for c in deckcraft_engine::command_specs()
.iter()
let list: Vec<Value> = s
.commands()
.into_iter()
.filter(|c| f.as_ref().is_none_or(|f| c.id.to_lowercase().contains(f.as_str()) || c.label.to_lowercase().contains(f.as_str())))
{
match c.params.strip_prefix("{}") {
Some(answer) => outln!("{} — {}{answer}", c.id, c.label),
None => outln!("{} — {}: {}", c.id, c.label, c.params),
}
}
.map(|c| serde_json::to_value(c).unwrap_or_default())
.collect();
outln!("{}", serde_json::to_string_pretty(&list).unwrap_or_default());
ExitCode::SUCCESS
}
Some("describe") => report(describe(rest.first().map(String::as_str))),
Some("app") => report(app(rest)),
Some("mcp") => report(mcp(rest)),
Some("links") => {
use deckcraft_engine::links::{APP_PAGE, DISCORD, GITHUB, WEBSITE};
use deckcraft_engine::links::*;
outln!("Discord {DISCORD}\nWebsite {WEBSITE}\nApp page {APP_PAGE}\nGitHub {GITHUB}");
ExitCode::SUCCESS
}
Some(other) => unknown(other),
None => usage(),
_ => {
eprintln!("{USAGE}");
eprintln!("\nCommunity: {} · {}", deckcraft_engine::links::DISCORD, deckcraft_engine::links::APP_PAGE);
ExitCode::FAILURE
}
}
}
fn is_help(arg: &str) -> bool {
matches!(arg, "--help" | "-h")
}
/// The help page of subcommand `name`, else the overview.
fn help_page(name: &str) -> String {
help::page(name).unwrap_or_else(help::overview)
}
fn unknown(sub: &str) -> ExitCode {
eprintln!("deckcraft-cli: unknown subcommand `{sub}`\n");
usage()
}
fn usage() -> ExitCode {
eprintln!("{}", help::overview());
eprintln!("\nCommunity: {} · {}", deckcraft_engine::links::DISCORD, deckcraft_engine::links::APP_PAGE);
ExitCode::FAILURE
}
fn report(r: Result<(), String>) -> ExitCode {
match r {
Ok(()) => ExitCode::SUCCESS,
@@ -132,142 +97,12 @@ fn open(s: &mut Session, input: Option<&str>, sample: bool) -> Result<(), String
return deckcraft_engine::sample::open_sample(s).map_err(|e| e.to_string());
}
match input {
Some(p) => {
let opened = s.execute("file.open", &json!({"path": p})).map_err(|e| e.to_string())?;
warn_if_damaged(p, &opened);
Ok(())
}
Some(p) => s.execute("file.open", &json!({"path": p})).map(|_| ()).map_err(|e| e.to_string()),
None => s.execute("file.new", &json!({})).map(|_| ()).map_err(|e| e.to_string()),
}
}
/// Say on stderr what a file lost on opening, so a saved copy doesn't silently miss it (#203).
fn warn_if_damaged(path: &str, opened: &serde_json::Value) {
let count = |key: &str| opened.get(key).and_then(|v| v.as_array()).map_or(0, |a| a.len());
let (slides, media) = (count("lostSlides"), count("damagedMedia"));
if slides > 0 {
eprintln!("deckcraft-cli: warning: {path}: {slides} slide{} couldn't be read and left out", if slides == 1 { "" } else { "s" });
}
if media > 0 {
eprintln!("deckcraft-cli: warning: {path}: {media} picture or media file{} couldn't be read", if media == 1 { "" } else { "s" });
}
}
/// Median and slowest of `runs` timings of `f`, in milliseconds.
fn time_ms(runs: usize, mut f: impl FnMut() -> Result<(), String>) -> Result<(f64, f64), String> {
let mut ms = Vec::with_capacity(runs);
for _ in 0..runs.max(1) {
let t = std::time::Instant::now();
f()?;
ms.push(t.elapsed().as_secs_f64() * 1000.0);
}
Ok(summarize_ms(ms))
}
/// Summarize one population of measurements; each maximum must come from that population.
fn summarize_ms(mut ms: Vec<f64>) -> (f64, f64) {
ms.sort_by(f64::total_cmp);
(ms.get(ms.len() / 2).copied().unwrap_or(0.0), ms.last().copied().unwrap_or(0.0))
}
/// Peak resident memory of this process in MiB (Linux `VmHWM`); `None` elsewhere.
fn peak_rss_mib() -> Option<f64> {
let s = std::fs::read_to_string("/proc/self/status").ok()?;
let kb: f64 = s.lines().find_map(|l| l.strip_prefix("VmHWM:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
Some(kb / 1024.0)
}
/// The performance baseline (docs/gaps.md "No baseline"): how long a deck takes to open, to
/// render each slide, to save and to export, and the peak memory, as JSON or a table.
fn bench(args: &[String]) -> Result<(), String> {
use deckcraft_engine::cmd::file::{open_presentation, save_bytes};
let mut input = None;
let mut sample = false;
let mut runs = 5usize;
let mut as_json = false;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--sample" => sample = true,
"--json" => as_json = true,
"--runs" => {
runs = it.next().and_then(|v| v.parse().ok()).filter(|n| (1..=1000).contains(n)).ok_or("--runs needs a number from 1 to 1000")?
}
f if !f.starts_with("--") && input.is_none() => input = Some(f.to_string()),
o => return Err(format!("bench: unknown argument `{o}`")),
}
}
if input.is_none() && !sample {
return Err("bench needs a FILE or --sample".into());
}
let mut s = Session::new();
let (name, bytes) = match &input {
Some(p) => (p.clone(), std::fs::read(p).map_err(|e| format!("{p}: {e}"))?),
None => {
open(&mut s, None, true)?;
let doc = &s.doc().map_err(|e| e.to_string())?.doc;
("sample.deckcraft".to_string(), save_bytes(doc, "deckcraft").map_err(|e| e.to_string())?)
}
};
let e = |x: deckcraft_engine::EngineError| x.to_string();
let doc = open_presentation(&name, &bytes).map_err(e)?;
let slides = doc.slides.len();
let open = time_ms(runs, || open_presentation(&name, &bytes).map(|_| ()).map_err(e))?;
let opts = deckcraft_engine::render::RenderOpts { scale: 1.0, ..Default::default() };
let mut per_slide = vec![];
for i in 0..slides {
per_slide.push(time_ms(runs, || {
deckcraft_engine::render::render_slide(&doc, i, &opts);
Ok(())
})?);
}
let pptx = save_bytes(&doc, "pptx").map_err(e)?;
let mut steps = vec![
("open", open),
("save .deckcraft", time_ms(runs, || save_bytes(&doc, "deckcraft").map(|_| ()).map_err(e))?),
("save .pptx", time_ms(runs, || save_bytes(&doc, "pptx").map(|_| ()).map_err(e))?),
("open .pptx", time_ms(runs, || open_presentation("bench.pptx", &pptx).map(|_| ()).map_err(e))?),
("export .pdf", time_ms(runs, || save_bytes(&doc, "pdf").map(|_| ()).map_err(e))?),
];
let render_all = time_ms(runs, || {
for i in 0..slides {
deckcraft_engine::render::render_slide(&doc, i, &opts);
}
Ok(())
})?;
steps.insert(1, ("render all slides (1×)", render_all));
let peak = peak_rss_mib();
if as_json {
let v = json!({
"file": name,
"bytes": bytes.len(),
"slides": slides,
"runs": runs,
"steps": steps.iter().map(|(k, (m, x))| json!({"step": k, "medianMs": m, "maxMs": x})).collect::<Vec<_>>(),
"renderMsPerSlide": per_slide.iter().map(|m| m.0).collect::<Vec<_>>(),
"peakRssMiB": peak,
});
outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
} else {
outln!("{name}: {slides} slides, {} KiB, median of {runs} runs", bytes.len() / 1024);
for (k, (m, x)) in &steps {
outln!(" {k:<24} {m:>9.1} ms (slowest {x:.1} ms)");
}
if let Some((i, m)) = per_slide.iter().enumerate().max_by(|a, b| a.1.0.total_cmp(&b.1.0)) {
outln!(" slowest slide {:>9.1} ms (slide {})", m.0, i + 1);
}
if let Some(p) = peak {
outln!(" peak memory {p:>9.1} MiB");
}
}
Ok(())
}
fn info(args: &[String]) -> Result<(), String> {
if args.first().is_some_and(|a| is_help(a)) {
outln!("{}", help_page("info"));
return Ok(());
}
let path = args.first().ok_or("info needs a FILE")?;
let mut s = Session::new();
open(&mut s, Some(path), false)?;
@@ -283,22 +118,15 @@ fn render(args: &[String]) -> Result<(), String> {
let mut all = false;
let mut scale = 2.0;
let mut edit = false;
let mut transparent = false;
let mut out = None;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--sample" => sample = true,
"--transparent" => transparent = true,
"--slide" => slide = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--slide needs a number")?),
"--all" => all = true,
"--edit" => edit = true,
"--scale" => scale = it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?,
"--help" | "-h" => {
outln!("{}", help_page("render"));
return Ok(());
}
other if other.starts_with('-') => return Err(format!("unknown option `{other}`")),
other
if input.is_none()
&& !sample
@@ -317,12 +145,15 @@ fn render(args: &[String]) -> Result<(), String> {
open(&mut s, input.as_deref(), sample)?;
let st = s.doc().map_err(|e| e.to_string())?;
let n = st.doc.slides.len();
let list = slide_indices(n, all, slide)?;
let list: Vec<usize> = if all { (0..n).collect() } else { vec![slide.unwrap_or(0)] };
if all {
std::fs::create_dir_all(&out).map_err(|e| format!("{out}: {e}"))?;
}
for i in list {
let (png, w, h) = deckcraft_engine::cmd::file::render_png_with(&st.doc, i, scale, edit, transparent);
if i >= n {
return Err(format!("no slide {i} (the deck has {n})"));
}
let (png, w, h) = deckcraft_engine::cmd::file::render_png(&st.doc, i, scale, edit);
let path = if all { format!("{out}/slide-{:02}.png", i + 1) } else { out.clone() };
std::fs::write(&path, png).map_err(|e| format!("{path}: {e}"))?;
outln!("{path} ({w}×{h})");
@@ -330,131 +161,13 @@ fn render(args: &[String]) -> Result<(), String> {
Ok(())
}
/// Slides `--slide` asks for. `N` is a 0-based index, the same one `slide.go` uses.
/// `--all` still names files from 1 (`slide-01.png`), which is PowerPoint's slide number.
fn slide_indices(n: usize, all: bool, slide: Option<usize>) -> Result<Vec<usize>, String> {
if all {
return Ok((0..n).collect());
}
let i = slide.unwrap_or(0);
if i >= n {
return Err(missing_slide(i, n));
}
Ok(vec![i])
}
fn missing_slide(i: usize, n: usize) -> String {
match n {
0 => format!("no slide index {i} (this deck has no slides)"),
1 => format!("no slide index {i} (this deck has 1 slide, index 0, which --all names slide-01.png)"),
n => {
let last = n - 1;
format!(
"no slide index {i} (this deck has {n} slides, numbered 0 through {last}; --all names them slide-01.png through slide-{n:02}.png)"
)
}
}
}
/// Frames of slide N's transition (0-based N; from slide N-1, or black for the first slide) at
/// the given progress values. With several values, OUT gets `-t<value>` before its extension.
fn render_transition(args: &[String]) -> Result<(), String> {
use deckcraft_engine::render;
let mut input = None;
let mut slide: Option<usize> = None;
let mut ts: Vec<f64> = Vec::new();
let mut width: Option<f64> = None;
let mut out = None;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--slide" => slide = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--slide needs a number")?),
"--t" => {
let v = it.next().ok_or("--t needs a value")?;
for x in v.split(',') {
let t: f64 = x.trim().parse().map_err(|_| format!("bad --t value `{x}`"))?;
if !t.is_finite() {
return Err(format!("bad --t value `{x}`"));
}
ts.push(t);
}
}
"--width" => {
width = Some(it.next().and_then(|v| v.parse().ok()).filter(|w: &f64| w.is_finite() && *w >= 1.0).ok_or("--width needs pixels")?)
}
other if input.is_none() => input = Some(other.to_string()),
other => out = Some(other.to_string()),
}
}
let input = input.ok_or("render-transition needs a FILE")?;
let out = out.ok_or("render-transition needs an output path")?;
let i = slide.ok_or("render-transition needs --slide N")?;
if ts.is_empty() {
return Err("render-transition needs --t".into());
}
let paths = frame_paths(&out, &ts)?;
let mut s = Session::new();
open(&mut s, Some(&input), false)?;
let st = s.doc().map_err(|e| e.to_string())?;
let doc = &st.doc;
let n = doc.slides.len();
let Some(sl) = doc.slides.get(i) else { return Err(format!("no slide {i} (the deck has {n})")) };
let sw = doc.slide_size.width.max(1.0);
let w = width.unwrap_or(sw * 2.0).min(render::MAX_SIDE as f64);
let opts = render::RenderOpts { scale: w / sw, ..Default::default() };
let tr = sl.transition.clone().unwrap_or_default();
// Render both slides once and composite every frame from them (morph re-renders per frame).
let prev = i.checked_sub(1);
let cached = (tr.kind != "morph").then(|| {
let parts = render::uses_slide_parts(&tr.kind, &tr.option).then(|| render::SlideParts::render(doc, prev, i, &opts));
(prev.map(|p| render::render_slide(doc, p, &opts)), render::render_slide(doc, i, &opts), parts)
});
let aspect = sw / doc.slide_size.height.max(1.0);
for (t, path) in ts.iter().zip(&paths) {
let img = match &cached {
Some((old, new, parts)) => {
render::composite_transition(old.as_ref(), new, parts.as_ref(), &render::transition_frame(&tr.kind, &tr.option, *t, aspect))
}
None => render::render_transition(doc, i, *t, &opts),
};
std::fs::write(path, img.to_png_at(render::dpi_for_scale(opts.scale))).map_err(|e| format!("{path}: {e}"))?;
outln!("{path} ({}×{}) {} {} t={t}", img.width, img.height, tr.kind, tr.option);
}
Ok(())
}
/// Output path of each frame. A single frame goes to OUT; several get `-t<value>` (three decimals)
/// before the extension. Values that round to the same name would overwrite each other, so that is an error.
fn frame_paths(out: &str, ts: &[f64]) -> Result<Vec<String>, String> {
if ts.len() == 1 {
return Ok(vec![out.to_string()]);
}
let p = std::path::Path::new(out);
let stem = p.file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("frame");
let mut paths: Vec<String> = Vec::with_capacity(ts.len());
for t in ts {
let path = p.with_file_name(format!("{stem}-t{t:.3}.png")).to_string_lossy().into_owned();
if paths.contains(&path) {
return Err(format!("--t values round to the same three decimals: more than one frame would be written to {path}"));
}
paths.push(path);
}
Ok(paths)
}
fn convert(args: &[String]) -> Result<(), String> {
if args.first().is_some_and(|a| is_help(a)) {
outln!("{}", help_page("convert"));
return Ok(());
}
let (Some(input), Some(out)) = (args.first(), args.get(1)) else { return Err("convert needs IN and OUT".into()) };
let fmt = output_format(out)?;
let mut s = Session::new();
open(&mut s, Some(input), false)?;
let fmt = deckcraft_engine::cmd::file::format_for_path(out);
let r = if matches!(fmt, "png" | "jpeg") {
s.execute("file.export", &json!({"path": out, "slide": 0}))
} else if fmt == "gif" {
s.execute("file.export", &json!({"path": out}))
} else {
s.execute("file.saveAs", &json!({"path": out}))
};
@@ -463,196 +176,53 @@ fn convert(args: &[String]) -> Result<(), String> {
Ok(())
}
/// The format `convert`, `run --save` and `run --export` write to `path`, or an error naming the
/// supported extensions when `path`'s extension isn't one (rather than native bytes under that name).
fn output_format(path: &str) -> Result<&'static str, String> {
use deckcraft_engine::cmd::file::{WRITABLE_EXTENSIONS, writable_format_for_path};
writable_format_for_path(path).ok_or_else(|| {
let ext = std::path::Path::new(path).extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_else(|| "(none)".into());
format!("{path}: unsupported output format {ext} (supported: .{})", WRITABLE_EXTENSIONS.join(", ."))
})
}
enum CommandSource {
Inline(String),
File(String),
}
const MAX_COMMAND_FILE_LINE_BYTES: usize = 16 * 1024 * 1024;
fn read_command_file_line(reader: &mut impl std::io::BufRead, line: &mut Vec<u8>) -> std::io::Result<bool> {
line.clear();
loop {
let available = reader.fill_buf()?;
if available.is_empty() {
return Ok(!line.is_empty());
}
let newline = available.iter().position(|byte| *byte == b'\n');
let count = newline.unwrap_or(available.len());
line.len().checked_add(count).filter(|length| *length <= MAX_COMMAND_FILE_LINE_BYTES).ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::InvalidData, format!("command line exceeds {MAX_COMMAND_FILE_LINE_BYTES} byte limit"))
})?;
line.extend_from_slice(&available[..count]);
reader.consume(count + usize::from(newline.is_some()));
if newline.is_some() {
return Ok(true);
}
}
}
/// The same command syntax and execution path for --cmd and each command-file line.
fn run_command(s: &mut Session, command: &str, print: bool) -> Result<(), String> {
let (id, params) = match command.split_once('=') {
Some((id, j)) => (id, serde_json::from_str::<Value>(j).map_err(|e| format!("{id}: bad JSON: {e}"))?),
None => (command, json!({})),
};
let r = s.execute(id, &params).map_err(|e| e.to_string())?;
if print {
outln!("{id} → {r}");
}
Ok(())
}
fn run_command_file(s: &mut Session, path: &str, print: bool) -> Result<(), String> {
use std::io::BufReader;
let file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
let mut reader = BufReader::new(file);
let mut bytes = Vec::new();
let mut line_number = 0usize;
loop {
line_number = line_number.checked_add(1).ok_or_else(|| format!("{path}: too many lines"))?;
if !read_command_file_line(&mut reader, &mut bytes).map_err(|e| format!("{path}:{line_number}: {e}"))? {
break;
}
let line = std::str::from_utf8(&bytes).map_err(|e| format!("{path}:{line_number}: invalid UTF-8: {e}"))?;
let line = if line_number == 1 { line.trim_start_matches('\u{feff}') } else { line };
let command = line.trim();
if command.is_empty() || command.starts_with('#') {
continue;
}
run_command(s, command, print).map_err(|e| format!("{path}:{line_number}: {e}"))?;
}
Ok(())
}
fn run(args: &[String]) -> Result<(), String> {
let mut input = None;
let mut sample = false;
let mut cmds = vec![];
let mut save = None;
let mut export = None;
let mut export_params = json!({});
let mut print = false;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--in" => input = Some(it.next().cloned().ok_or("--in needs a file")?),
"--sample" => sample = true,
"--cmd" => cmds.push(CommandSource::Inline(it.next().cloned().ok_or("--cmd needs COMMAND[=PARAMS]")?)),
"--cmd-file" => cmds.push(CommandSource::File(it.next().cloned().ok_or("--cmd-file needs a file")?)),
"--cmd" => cmds.push(it.next().cloned().ok_or("--cmd needs ID[=JSON]")?),
"--save" => save = Some(it.next().cloned().ok_or("--save needs a path")?),
"--export" => export = Some(it.next().cloned().ok_or("--export needs a path")?),
"--export-params" => {
let j = it.next().ok_or("--export-params needs a JSON object")?;
export_params = serde_json::from_str::<Value>(j).map_err(|e| format!("--export-params: bad JSON: {e}"))?;
if !export_params.is_object() {
return Err("--export-params must be a JSON object".into());
}
}
"--print" => print = true,
"--help" | "-h" => {
outln!("{}", help_page("run"));
return Ok(());
}
other => return Err(format!("unknown option `{other}`")),
}
}
for p in save.iter().chain(&export) {
output_format(p)?;
}
let mut s = Session::new();
open(&mut s, input.as_deref(), sample)?;
for source in cmds {
match source {
CommandSource::Inline(command) => run_command(&mut s, &command, print)?,
CommandSource::File(path) => run_command_file(&mut s, &path, print)?,
for c in cmds {
let (id, p) = match c.split_once('=') {
Some((id, j)) => (id.to_string(), serde_json::from_str::<Value>(j).map_err(|e| format!("{id}: bad JSON: {e}"))?),
None => (c.clone(), json!({})),
};
let r = s.execute(&id, &p).map_err(|e| e.to_string())?;
if print {
outln!("{id} → {r}");
}
}
if let Some(p) = save {
s.execute("file.saveAs", &json!({"path": p})).map_err(|e| e.to_string())?;
}
if let Some(p) = export {
export_params["path"] = json!(p);
s.execute("file.export", &export_params).map_err(|e| e.to_string())?;
} else if export_params != json!({}) {
return Err("--export-params needs --export OUT".into());
s.execute("file.export", &json!({"path": p})).map_err(|e| e.to_string())?;
}
Ok(())
}
fn describe(id: Option<&str>) -> Result<(), String> {
if id.is_some_and(is_help) {
outln!("{}", help_page("describe"));
return Ok(());
}
let id = id.ok_or("describe needs a command id")?;
let c = deckcraft_engine::find_command(id).ok_or_else(|| deckcraft_engine::EngineError::UnknownCommand(id.into()).to_string())?;
let mut head = format!("{}: {}", c.id, c.label);
if !c.menu.is_empty() {
head.push_str(&format!(", in {}", c.menu.join(" ▸ ")));
}
if let Some(k) = c.shortcut {
head.push_str(&format!(", shortcut {k}"));
}
outln!("{head}.\n");
let (args, answer) = c.params.split_once('→').unwrap_or((c.params, ""));
let parsed = deckcraft_engine::cmd::parse_params(c.params);
match &parsed {
Err(_) => outln!("Parameters: {}", args.trim()),
Ok(params) if params.is_empty() => outln!("Takes no parameters."),
Ok(params) => print_params(params),
}
let params = parsed.unwrap_or_default();
if let Some(acts) = c.acts_on() {
outln!("{acts}");
}
let remark = remark(args);
if !remark.is_empty() {
outln!("Note: {remark}");
}
if !answer.trim().is_empty() {
outln!("Answers with {}.", answer.trim());
}
let bare = params.is_empty() || params.iter().any(|p| params.iter().filter(|q| q.object == p.object).all(|q| q.optional));
let call = if bare { c.id.to_string() } else { format!("'{}={{…}}'", c.id) };
outln!("\nRun it with: deckcraft-cli run --cmd {call}");
let c = deckcraft_engine::find_command(id).ok_or_else(|| format!("unknown command `{id}`"))?;
outln!("{} — {}\n where: {}\n shortcut: {}\n params: {}", c.id, c.label, c.menu.join(" ▸ "), c.shortcut.unwrap_or("—"), c.params);
Ok(())
}
fn print_params(params: &[deckcraft_engine::cmd::Param]) {
let name = |p: &deckcraft_engine::cmd::Param| {
let or = if p.or { "or " } else { "" };
let optional = if p.optional { ", optional" } else { "" };
format!("{or}{}{optional}", p.name)
};
let width = params.iter().map(|p| name(p).chars().count()).max().unwrap_or_default();
let sets = params.iter().map(|p| p.object).max().unwrap_or_default() > 0;
outln!("Parameters:");
for (k, p) in params.iter().enumerate() {
if sets && params.get(k.wrapping_sub(1)).is_none_or(|before| before.object != p.object) {
outln!(" {}", if p.object == 0 { "either:" } else { "or:" });
}
let indent = if sets { " " } else { " " };
outln!("{}", format!("{indent}{:<width$} {}", name(p), p.about).trim_end());
}
}
fn remark(args: &str) -> &str {
let after = args.rfind('}').and_then(|i| args.get(i + 1..)).unwrap_or_default().trim().trim_start_matches('—').trim();
after.strip_prefix('(').and_then(|n| n.strip_suffix(')')).unwrap_or(after)
}
fn app(args: &[String]) -> Result<(), String> {
use deckcraft_mcp::{Backend, Remote, control_addr};
let mut port = deckcraft_mcp::DEFAULT_PORT.to_string();
@@ -663,10 +233,6 @@ fn app(args: &[String]) -> Result<(), String> {
match a.as_str() {
"--port" => port = it.next().cloned().ok_or("--port needs a value")?,
"--method" => method = Some(it.next().cloned().ok_or("--method needs a name")?),
"--help" | "-h" => {
outln!("{}", help_page("app"));
return Ok(());
}
other => rest.push(other.to_string()),
}
}
@@ -687,51 +253,24 @@ fn app(args: &[String]) -> Result<(), String> {
}
fn mcp(args: &[String]) -> Result<(), String> {
use deckcraft_engine::file_access::{self, AutomationRoots};
use deckcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
let mut connect: Option<String> = None;
let mut sample = false;
let mut roots_args = automation_args::AutomationArgs::new(None, None);
let mut it = args.iter().cloned();
let mut it = args.iter();
while let Some(a) = it.next() {
if roots_args.consume(&a, &mut it)? {
continue;
}
match a.as_str() {
"--connect" => connect = Some(it.next().ok_or("--connect needs a port or host:port")?),
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs a port or host:port")?),
"--sample" => sample = true,
"--help" | "-h" => {
outln!("{}", help_page("mcp"));
return Ok(());
}
other => return Err(format!("unknown mcp option `{other}`")),
}
}
let roots = AutomationRoots::new(&roots_args.read_roots, &roots_args.write_roots)?;
if roots.is_some() && connect.is_some() {
return Err("--automation-read-root and --automation-write-root confine the in-process server; a running app is not confined by them, \
so drop --connect (or use --connect without the roots)"
.into());
}
let backend: Box<dyn Backend> = match connect {
Some(c) => Box::new(Remote::connect(&control_addr(&c)).map_err(|e| format!("can't reach the app at {c}: {e}"))?),
None => {
let mut h = Headless::new();
// `--sample` is the operator's own choice, made before the roots come into force.
if sample {
deckcraft_engine::sample::open_sample(&mut h.session).map_err(|e| e.to_string())?;
}
if let Some(roots) = roots {
// Every thread of this process, not only the server's: nothing reaches past the roots.
file_access::confine_process(roots.clone());
let show = |roots: Vec<String>| if roots.is_empty() { "none".to_string() } else { roots.join(", ") };
eprintln!(
"deckcraft-cli: files confined: read roots {}, write roots {}",
show(roots.read_roots().map(|r| r.display().to_string()).collect()),
show(roots.write_roots().map(|r| r.display().to_string()).collect())
);
h = h.with_automation_roots(Some(roots));
}
Box::new(h)
}
};
@@ -739,144 +278,3 @@ so drop --connect (or use --connect without the roots)"
let stdin = std::io::stdin();
server.serve(stdin.lock(), std::io::stdout()).map_err(|e| e.to_string())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
fn args(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
#[test]
fn timing_summary_keeps_median_and_max_from_one_population() {
let slide_medians = [8.99, 16.565];
let whole_deck = summarize_ms(vec![17.0, 18.0, 16.0]);
assert_eq!(whole_deck, (17.0, 18.0));
assert!(whole_deck.1 >= whole_deck.0);
assert!(slide_medians.iter().sum::<f64>() > whole_deck.1, "fixture must expose summing independent slide medians");
assert_eq!(summarize_ms(vec![]), (0.0, 0.0));
}
#[test]
fn render_help_prints_usage_and_writes_nothing() {
assert!(render(&args(&["--help"])).is_ok());
assert!(render(&args(&["-h"])).is_ok());
assert!(!std::path::Path::new("--help").exists());
}
#[test]
fn render_rejects_unknown_flag() {
let err = render(&args(&["--sample", "--scael", "2", "out.png"])).unwrap_err();
assert_eq!(err, "unknown option `--scael`");
assert!(!std::path::Path::new("--scael").exists());
}
#[test]
fn other_subcommands_accept_help() {
assert!(info(&args(&["--help"])).is_ok());
assert!(convert(&args(&["-h"])).is_ok());
assert!(run(&args(&["--help"])).is_ok());
assert!(describe(Some("--help")).is_ok());
assert!(mcp(&args(&["-h"])).is_ok());
}
#[test]
fn render_refuses_an_unknown_option_instead_of_writing_it_as_a_file() {
let out = std::env::temp_dir().join("deckcraft-cli-unknown-option.png");
let _ = std::fs::remove_file(&out);
for flag in ["--bogus", "-x"] {
let args: Vec<String> = ["--sample", flag, &out.to_string_lossy()].iter().map(|a| a.to_string()).collect();
let e = render(&args).unwrap_err();
assert!(e.contains(&format!("unknown option `{flag}`")), "{flag}: {e}");
assert!(!out.exists(), "{flag}: rendered anyway");
}
}
/// `render --transparent` leaves the slide background out (#784): the corner is transparent.
#[test]
fn render_transparent_leaves_the_background_out() {
let dir = std::env::temp_dir().join(format!("deckcraft-cli-transparent-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let alpha = |path: &std::path::Path| deckcraft_engine::render::decode_image(&std::fs::read(path).unwrap()).unwrap().get_pixel(1, 1).0[3];
let opaque = dir.join("opaque.png");
render(&args(&["--sample", "--scale", "0.25", &opaque.to_string_lossy()])).unwrap();
assert_eq!(alpha(&opaque), 255);
let clear = dir.join("clear.png");
render(&args(&["--sample", "--transparent", "--scale", "0.25", &clear.to_string_lossy()])).unwrap();
assert_eq!(alpha(&clear), 0);
let _ = std::fs::remove_dir_all(&dir);
}
/// `run --export OUT.gif --export-params JSON` and `convert IN OUT.gif` write animated GIFs.
#[test]
fn exports_an_animated_gif() {
let dir = std::env::temp_dir().join(format!("deckcraft-cli-gif-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let gif = dir.join("sample.gif").to_string_lossy().to_string();
let deck = dir.join("sample.deckcraft").to_string_lossy().to_string();
let params = r#"{"width": "small", "secondsPerSlide": 2, "loop": false, "slides": [0, 1]}"#;
run(&args(&["--sample", "--save", &deck, "--export", &gif, "--export-params", params])).unwrap();
let bytes = std::fs::read(&gif).unwrap();
assert!(bytes.starts_with(b"GIF89a"));
assert_eq!(u16::from_le_bytes([bytes[6], bytes[7]]), 640, "small = 640 px wide");
assert!(!bytes.windows(11).any(|w| w == b"NETSCAPE2.0"), "play once: no loop block");
let gif2 = dir.join("converted.gif").to_string_lossy().to_string();
convert(&args(&[&deck, &gif2])).unwrap();
let bytes = std::fs::read(&gif2).unwrap();
assert!(bytes.starts_with(b"GIF89a") && bytes.windows(11).any(|w| w == b"NETSCAPE2.0"), "loops forever by default");
// Bad options are errors, not panics.
let bad = dir.join("bad.gif").to_string_lossy().to_string();
assert!(run(&args(&["--sample", "--export", &bad, "--export-params", r#"{"width": 1e9}"#])).is_err());
assert!(run(&args(&["--sample", "--export", &bad, "--export-params", "[1]"])).is_err());
assert!(run(&args(&["--sample", "--export-params", "{}"])).is_ok());
assert!(run(&args(&["--sample", "--export-params", r#"{"width": 64}"#])).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod slide_index_tests {
use super::{missing_slide, slide_indices};
#[test]
fn slide_numbers_start_at_zero_and_files_at_one() {
assert_eq!(slide_indices(8, false, None).ok().as_deref(), Some(&[0][..]));
assert_eq!(slide_indices(8, false, Some(0)).ok().as_deref(), Some(&[0][..]));
assert_eq!(slide_indices(8, false, Some(7)).ok().as_deref(), Some(&[7][..]));
assert_eq!(slide_indices(8, true, None).ok().as_deref(), Some(&[0, 1, 2, 3, 4, 5, 6, 7][..]));
let err = slide_indices(8, false, Some(8)).err().unwrap_or_default();
assert!(!err.is_empty(), "index 8 was accepted");
assert!(err.contains("numbered 0 through 7"), "{err}");
assert!(err.contains("slide-01.png"), "{err}");
assert!(err.contains("slide-08.png"), "{err}");
assert!(missing_slide(0, 0).contains("no slides"));
assert!(missing_slide(1, 1).contains("index 0"));
}
}
#[cfg(test)]
mod frame_path_tests {
use super::frame_paths;
#[test]
fn single_frame_uses_out_as_is() {
assert_eq!(frame_paths("a/b.png", &[0.5]), Ok(vec!["a/b.png".to_string()]));
}
#[test]
fn frames_get_distinct_names() {
let paths = frame_paths("f.png", &[0.0, 0.25, 1.0]).unwrap_or_default();
assert_eq!(paths, ["f-t0.000.png", "f-t0.250.png", "f-t1.000.png"]);
}
#[test]
fn values_rounding_to_one_name_are_rejected() {
assert!(frame_paths("f.png", &[0.1001, 0.1002]).is_err());
assert!(frame_paths("f.png", &[0.5, 0.5]).is_err());
}
}
-289
View File
@@ -1,289 +0,0 @@
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).args(args).output().unwrap()
}
fn stdout(o: &Output) -> String {
assert!(o.status.success(), "exit {:?}\nstderr: {}", o.status, String::from_utf8_lossy(&o.stderr));
String::from_utf8_lossy(&o.stdout).into_owned()
}
fn stderr(o: &Output) -> String {
assert!(!o.status.success(), "exit {:?}\nstdout: {}", o.status, String::from_utf8_lossy(&o.stdout));
String::from_utf8_lossy(&o.stderr).into_owned()
}
const SUBCOMMANDS: [&str; 11] = ["info", "render", "render-transition", "convert", "run", "commands", "describe", "app", "mcp", "bench", "links"];
fn words(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn command_file_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("deckcraft-cli-command-file-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn inspected_titles(out: &str) -> Vec<String> {
let answer = out.lines().last().unwrap().strip_prefix("document.inspect → ").unwrap();
let doc: serde_json::Value = serde_json::from_str(answer).unwrap();
doc["slides"].as_array().unwrap().iter().map(|s| s["title"].as_str().unwrap().to_string()).collect()
}
#[test]
fn command_file_runs_utf8_lines_in_order_and_skips_comments() {
let dir = command_file_dir("lines");
let file = dir.join("commands with spaces.txt");
std::fs::write(
&file,
"\u{feff}# heading\r\n\r\n # indented comment\r\n slide.new={\"title\":\"Résumé = # 测试\"} \r\nslide.new\r\nslide.new={\"title\":\"Last\"}",
)
.unwrap();
let o = cli(&["run", "--print", "--cmd-file", &file.to_string_lossy(), "--cmd", "document.inspect"]);
let out = stdout(&o);
let commands: Vec<_> = out.lines().map(|l| l.split_once(" → ").unwrap().0).collect();
assert_eq!(commands, ["slide.new", "slide.new", "slide.new", "document.inspect"]);
let titles = inspected_titles(&out);
assert_eq!(titles.len(), 4);
assert_eq!(titles[1], "Résumé = # 测试");
assert_eq!(titles[3], "Last");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn command_files_and_inline_commands_keep_argument_order() {
let dir = command_file_dir("mixed");
let first = dir.join("first.txt");
let second = dir.join("second.txt");
let saved = dir.join("result.deckcraft");
std::fs::write(&first, "slide.new={\"title\":\"First file\"}\n").unwrap();
std::fs::write(&second, "slide.new={\"title\":\"Second file\"}\n").unwrap();
let o = cli(&[
"run",
"--cmd",
"slide.new={\"title\":\"Inline first\"}",
"--cmd-file",
&first.to_string_lossy(),
"--cmd",
"slide.new={\"title\":\"Inline middle\"}",
"--cmd-file",
&second.to_string_lossy(),
"--cmd",
"document.inspect",
"--print",
"--save",
&saved.to_string_lossy(),
]);
let out = stdout(&o);
let titles = inspected_titles(&out);
assert_eq!(&titles[1..], ["Inline first", "First file", "Inline middle", "Second file"]);
assert_eq!(out.lines().count(), 5);
let reopened = cli(&["run", "--in", &saved.to_string_lossy(), "--cmd", "document.inspect", "--print"]);
assert_eq!(inspected_titles(&stdout(&reopened)), titles);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_failed_file_command_stops_later_commands_and_final_outputs() {
let dir = command_file_dir("failure");
let file = dir.join("commands.txt");
let later = dir.join("later-in-file.deckcraft");
let inline = dir.join("later-inline.deckcraft");
let save = dir.join("saved.deckcraft");
let export = dir.join("exported.png");
let inline_command = format!("file.saveAs={}", serde_json::json!({"path": inline.to_string_lossy()}));
for (command, message) in [("slide.new={", "bad JSON"), ("no.such.command", "unknown command"), ("slide.go={\"index\":999}", "slide")] {
let later_command = format!("file.saveAs={}", serde_json::json!({"path": later.to_string_lossy()}));
std::fs::write(&file, format!("# header\nslide.new\n{command}\n{later_command}\n")).unwrap();
std::fs::write(&save, b"keep saved file").unwrap();
std::fs::write(&export, b"keep exported file").unwrap();
let o = cli(&[
"run",
"--print",
"--cmd-file",
&file.to_string_lossy(),
"--cmd",
&inline_command,
"--save",
&save.to_string_lossy(),
"--export",
&export.to_string_lossy(),
]);
let err = stderr(&o);
assert!(err.contains(&format!("{}:3:", file.display())) && err.contains(message), "{err}");
assert_eq!(String::from_utf8_lossy(&o.stdout).lines().count(), 1, "only the first command ran");
assert!(!later.exists() && !inline.exists(), "commands after the failure must not run");
assert_eq!(std::fs::read(&save).unwrap(), b"keep saved file");
assert_eq!(std::fs::read(&export).unwrap(), b"keep exported file");
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn command_file_read_errors_name_the_path_and_utf8_line() {
let dir = command_file_dir("read-errors");
let missing = dir.join("missing.txt");
let invalid = dir.join("invalid.txt");
let save = dir.join("out.deckcraft");
std::fs::write(&invalid, b"slide.new\n\xff\n").unwrap();
for file in [&missing, &dir, &invalid] {
let o = cli(&["run", "--cmd-file", &file.to_string_lossy(), "--save", &save.to_string_lossy()]);
let err = stderr(&o);
assert!(err.contains(&file.display().to_string()), "{err}");
if file == &invalid {
assert!(err.contains(&format!("{}:2:", invalid.display())) && err.contains("UTF-8"), "{err}");
}
assert!(!save.exists());
}
assert!(stderr(&cli(&["run", "--cmd-file"])).contains("--cmd-file needs a file"));
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn command_file_rejects_an_oversized_line_before_running_it() {
let dir = command_file_dir("line-limit");
let file = dir.join("commands.txt");
let command = format!("slide.new={{\"title\":\"{}\"}}", "x".repeat(16 * 1024 * 1024));
std::fs::write(&file, format!("{command}\nslide.new\n")).unwrap();
let o = cli(&["run", "--print", "--cmd-file", &file.to_string_lossy()]);
let err = stderr(&o);
assert!(err.contains(&format!("{}:1:", file.display())) && err.contains("command line exceeds 16777216 byte limit"), "{err}");
assert!(o.stdout.is_empty(), "the oversized command must not run");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn inline_commands_keep_their_existing_syntax_and_errors() {
let o = cli(&["run", "--cmd", "slide.new", "--cmd", "slide.new={\"title\":\"Inline = #\"}", "--cmd", "document.inspect", "--print"]);
let out = stdout(&o);
let titles = inspected_titles(&out);
assert_eq!(titles.len(), 3);
assert_eq!(titles[2], "Inline = #");
assert!(stderr(&cli(&["run", "--cmd", "slide.new={"])).starts_with("deckcraft-cli: slide.new: bad JSON:"));
assert!(stderr(&cli(&["run", "--cmd", "no.such.command"])).contains("unknown command `no.such.command`"));
}
#[test]
fn an_unknown_subcommand_is_named_before_the_overview() {
for args in [vec!["frobnicate"], vec!["help", "frobnicate"], vec!["--info", "--help"]] {
let err = stderr(&cli(&args));
assert!(err.contains("unknown subcommand `") && err.contains("\n\ndeckcraft-cli works on"), "{args:?}: {err}");
}
}
#[test]
fn no_subcommand_shows_the_overview_and_fails() {
assert!(stderr(&cli(&[])).starts_with("deckcraft-cli works on"));
}
#[test]
fn help_lists_every_subcommand_with_a_run_example() {
for flag in ["help", "--help", "-h"] {
let out = stdout(&cli(&[flag]));
for sub in SUBCOMMANDS {
assert!(out.contains(&format!("\n {sub} ")), "{flag} lacks {sub}: {out}");
}
assert!(out.contains("deckcraft-cli run --cmd 'slide.new={\"title\":\"Q3 results\"}' --save q3.deckcraft"), "{out}");
}
}
#[test]
fn every_subcommand_answers_help_and_does_nothing_else() {
let dir = std::env::temp_dir().join(format!("dc-cli-help-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
for sub in SUBCOMMANDS {
for args in [vec![sub, "--help"], vec![sub, "-h", "out.png"], vec!["help", sub]] {
let o = Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).current_dir(&dir).args(&args).output().unwrap();
assert!(stdout(&o).starts_with(&format!("usage: deckcraft-cli {sub}")), "{args:?}");
}
}
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "help wrote nothing");
std::fs::remove_dir_all(&dir).unwrap();
for args in [["help", "version"], ["--version", "--help"]] {
assert!(stdout(&cli(&args)).starts_with("usage: deckcraft-cli --version"), "{args:?}");
}
for args in [["help", "help"], ["help", "--help"]] {
assert!(stdout(&cli(&args)).starts_with("deckcraft-cli works on"), "{args:?}");
}
}
#[test]
fn run_help_says_what_the_ids_do_not() {
let out = words(&stdout(&cli(&["run", "--help"])));
for fact in [
"COMMAND is a command id, then `=`, then the command's parameters as one JSON object.",
"points on a 960×540 slide",
"Slide indices start at 0.",
"Shape ids are looked up on the current slide only.",
"A command that adds a shape (shape.insert, insert.textBox, insert.table…) selects it.",
"format.* acts on the selected text or shapes",
"--cmd-file FILE reads the same commands from a UTF-8 text file, one per line",
"commands execute in the order those options appear.",
"If a command fails, run stops there and saves nothing.",
] {
assert!(out.contains(fact), "{fact}: {out}");
}
}
#[test]
fn describe_spells_out_a_command() {
assert_eq!(
stdout(&cli(&["describe", "shape.insert"])),
"shape.insert: Shapes, in Insert ▸ Illustrations.
Parameters:
preset rect|roundRect|ellipse|triangle|rightArrow|star5|… (see shape.presets)
rect [x,y,w,h] pt
text, optional string
Run it with: deckcraft-cli run --cmd 'shape.insert={…}'
"
);
assert_eq!(
stdout(&cli(&["describe", "format.size"])),
"format.size: Font Size, in Home ▸ Font.
Parameters:
size pt
Acts on the selected text or shapes.
Run it with: deckcraft-cli run --cmd 'format.size={…}'
"
);
assert!(stdout(&cli(&["describe", "edit.copy"])).contains("Answers with {text, html?}.\n\nRun it with: deckcraft-cli run --cmd edit.copy\n"));
assert!(stdout(&cli(&["describe", "text.set"])).contains("Note: replaces the whole text, keeping the first run's formatting\n"));
assert_eq!(
stdout(&cli(&["describe", "shape.setDefault"])),
"shape.setDefault: Set as Default Shape.\n\nTakes no parameters.\nActs on the selected shapes.\n\nRun it with: deckcraft-cli run --cmd shape.setDefault\n"
);
}
#[test]
fn describe_shows_alternative_sets_of_parameters() {
assert!(stdout(&cli(&["describe", "slide.go"])).contains("Parameters:\n either:\n index\n or:\n id\n"));
let remove = stdout(&cli(&["describe", "animation.remove"]));
assert!(remove.contains(" or:\n ids, optional (all of the shapes' animations)\n"), "{remove}");
assert!(remove.ends_with("Run it with: deckcraft-cli run --cmd animation.remove\n") && !remove.contains("Note:"), "{remove}");
assert!(stdout(&cli(&["describe", "shape.move"])).contains(
" either:
dx, optional pt (relative)
dy, optional pt (relative)
ids, optional
or:
x, optional pt (absolute)
y, optional pt (absolute)
ids, optional
"
));
}
#[test]
fn commands_lists_one_line_per_command() {
assert_eq!(stdout(&cli(&["commands", "format.size"])), "format.size — Font Size: {size: pt}\n");
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");
}
@@ -1,110 +0,0 @@
use std::fs::{self, File};
use std::os::fd::OwnedFd;
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};
struct Scratch(PathBuf);
impl Scratch {
fn new(name: &str) -> Self {
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
let path = std::env::temp_dir().join(format!("deckcraft-closed-stdout-{name}-{}-{nonce}", std::process::id()));
fs::create_dir(&path).unwrap();
Self(path)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn closed_stdout() -> Stdio {
let (writer, reader) = UnixStream::pair().unwrap();
drop(reader);
Stdio::from(OwnedFd::from(writer))
}
fn run(dir: &Path, args: &[&str], stdout: Stdio) -> Output {
Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).current_dir(dir).args(args).stdout(stdout).stderr(Stdio::piped()).output().unwrap()
}
#[test]
fn broken_pipe_does_not_skip_later_commands_or_save() {
let dir = Scratch::new("save");
let out = run(
&dir.0,
&[
"run",
"--cmd",
r#"slide.new={"layout":"titleOnly","title":"First"}"#,
"--cmd",
r#"slide.new={"layout":"titleOnly","title":"Later"}"#,
"--print",
"--save",
"out.deckcraft",
],
closed_stdout(),
);
assert!(out.status.success(), "exit {:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
let saved = dir.0.join("out.deckcraft");
assert!(saved.is_file(), "requested save was skipped");
let info = Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).arg("info").arg(saved).output().unwrap();
assert!(info.status.success(), "{}", String::from_utf8_lossy(&info.stderr));
let data: serde_json::Value = serde_json::from_slice(&info.stdout).unwrap();
let slides = data["slides"].as_array().unwrap();
assert!(slides.iter().any(|slide| slide["title"] == "Later"), "later command did not persist: {data}");
}
#[test]
fn broken_pipe_does_not_hide_a_later_command_failure() {
let dir = Scratch::new("command-failure");
let out = run(
&dir.0,
&["run", "--cmd", r#"slide.new={"title":"First"}"#, "--cmd", r#"slide.go={"index":999}"#, "--print", "--save", "out.deckcraft"],
closed_stdout(),
);
assert!(!out.status.success(), "a later command failure returned success");
assert!(!dir.0.join("out.deckcraft").exists(), "failed run unexpectedly saved");
assert!(String::from_utf8_lossy(&out.stderr).contains("no slide 999"), "missing command failure diagnostic");
}
#[test]
fn broken_pipe_does_not_hide_a_save_failure() {
let dir = Scratch::new("save-failure");
fs::create_dir(dir.0.join("out.deckcraft")).unwrap();
let out = run(&dir.0, &["run", "--cmd", r#"slide.new={"title":"First"}"#, "--print", "--save", "out.deckcraft"], closed_stdout());
assert!(!out.status.success(), "a failed save returned success");
assert!(!out.stderr.is_empty(), "missing save failure diagnostic");
}
#[test]
fn broken_pipe_does_not_skip_later_rendered_slides() {
let dir = Scratch::new("render-all");
let baseline = run(&dir.0, &["render", "--sample", "--all", "--scale", "0.1", "normal"], Stdio::piped());
assert!(baseline.status.success(), "{}", String::from_utf8_lossy(&baseline.stderr));
let closed = run(&dir.0, &["render", "--sample", "--all", "--scale", "0.1", "closed"], closed_stdout());
assert!(closed.status.success(), "{}", String::from_utf8_lossy(&closed.stderr));
let names = |folder: &str| {
let mut files: Vec<_> = fs::read_dir(dir.0.join(folder)).unwrap().map(|entry| entry.unwrap().file_name()).collect();
files.sort();
files
};
let expected = names("normal");
assert!(expected.len() > 1, "sample must have multiple slides");
assert_eq!(names("closed"), expected, "rendering stopped after stdout closed");
}
#[test]
fn other_stdout_write_errors_fail() {
let dir = Scratch::new("write-failure");
let path = dir.0.join("readonly");
fs::write(&path, b"").unwrap();
let readonly = File::open(path).unwrap();
let out = run(&dir.0, &["run", "--cmd", r#"slide.new={"title":"First"}"#, "--print"], Stdio::from(readonly));
assert!(!out.status.success(), "a non-broken stdout error returned success");
assert!(String::from_utf8_lossy(&out.stderr).contains("can't write to stdout"));
}
-57
View File
@@ -1,57 +0,0 @@
//! `deckcraft-cli convert` writes the format OUT's extension names, or fails without writing.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
fn cli(args: &[&Path]) -> Output {
Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).args(args).output().unwrap()
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("deckcraft-cli-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn convert_rejects_output_formats_it_cannot_write() {
let dir = temp_dir("convert-unsupported");
let input = dir.join("in.pptx");
let out = Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).args(["run", "--sample", "--export"]).arg(&input).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
for name in ["out.odp", "out.bmp", "out.svg", "out.outline", "out"] {
let target = dir.join(name);
let out = cli(&[Path::new("convert"), &input, &target]);
assert!(!out.status.success(), "{name}: convert should fail");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("unsupported output format") && err.contains(".pptx"), "{name}: {err}");
assert!(!target.exists(), "{name}: nothing is written");
}
let target = dir.join("out.deckcraft");
let out = cli(&[Path::new("convert"), &input, &target]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(std::fs::read(&target).unwrap().starts_with(b"PK\x03\x04"));
let target = dir.join("out.txt");
let out = cli(&[Path::new("convert"), &input, &target]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(!std::fs::read(&target).unwrap().starts_with(b"PK"), "an outline is text, not a zip");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn run_rejects_unsupported_save_and_export_paths_before_running() {
let dir = temp_dir("run-unsupported");
for flag in ["--save", "--export"] {
let target = dir.join("deck.odp");
let out = Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).args(["run", "--sample", flag]).arg(&target).output().unwrap();
assert!(!out.status.success(), "{flag}: run should fail");
assert!(String::from_utf8_lossy(&out.stderr).contains("unsupported output format .odp"), "{flag}");
assert!(!target.exists(), "{flag}: nothing is written");
}
let _ = std::fs::remove_dir_all(&dir);
}
-53
View File
@@ -1,53 +0,0 @@
//! Opening a `.pptx` that lost slides says so on stderr instead of saving a shorter deck in silence (#203).
use std::io::{Cursor, Read, Write};
use std::path::PathBuf;
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_deckcraft-cli")).args(args).output().unwrap()
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("deckcraft-cli-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// `deck` with `ppt/slides/slide2.xml` cut off.
fn without_slide2(deck: &[u8]) -> Vec<u8> {
let mut zin = zip::ZipArchive::new(Cursor::new(deck)).unwrap();
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default();
for i in 0..zin.len() {
let mut f = zin.by_index(i).unwrap();
let mut data = vec![];
f.read_to_end(&mut data).unwrap();
if f.name() == "ppt/slides/slide2.xml" {
data = b"<p:sld".to_vec();
}
out.start_file(f.name(), options).unwrap();
out.write_all(&data).unwrap();
}
out.finish().unwrap().into_inner()
}
#[test]
fn a_pptx_with_an_unreadable_slide_is_reported_on_stderr() {
let dir = temp_dir("lost-slide");
let good = dir.join("good.pptx");
let made = cli(&["run", "--sample", "--save", good.to_str().unwrap()]);
assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
let broken = dir.join("broken.pptx");
std::fs::write(&broken, without_slide2(&std::fs::read(&good).unwrap())).unwrap();
let ok = cli(&["info", good.to_str().unwrap()]);
assert!(ok.status.success() && !String::from_utf8_lossy(&ok.stderr).contains("warning"), "{}", String::from_utf8_lossy(&ok.stderr));
let bad = cli(&["info", broken.to_str().unwrap()]);
assert!(bad.status.success(), "{}", String::from_utf8_lossy(&bad.stderr));
let err = String::from_utf8_lossy(&bad.stderr);
assert!(err.contains("warning") && err.contains("1 slide couldn't be read and left out"), "{err}");
let _ = std::fs::remove_dir_all(&dir);
}
-8
View File
@@ -1,8 +0,0 @@
mod cli;
#[cfg(unix)]
mod closed_stdout;
mod convert;
mod damaged;
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md).
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod mcp_roots;
-159
View File
@@ -1,159 +0,0 @@
//! `deckcraft-cli mcp` with the automation root flags, run as the real binary.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Output, Stdio};
use serde_json::Value;
fn bin() -> Command {
Command::new(env!("CARGO_BIN_EXE_deckcraft-cli"))
}
fn run(args: &[&str]) -> Output {
bin().args(args).output().unwrap()
}
fn tmpdir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("dc-cli-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// Send `calls` (tool name, arguments) to `deckcraft-cli mcp <args>`; returns whether it exited
/// cleanly, its stderr, and the stdout lines after `initialize`, one per call.
fn mcp_session(args: &[&str], calls: &[(&str, Value)]) -> (bool, String, Vec<Value>) {
let mut child = bin().arg("mcp").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
{
let stdin = child.stdin.as_mut().unwrap();
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
for (i, (name, arguments)) in calls.iter().enumerate() {
let call = serde_json::json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}});
writeln!(stdin, "{call}").unwrap();
}
}
let out = child.wait_with_output().unwrap();
let stdout = String::from_utf8(out.stdout).unwrap();
let replies = stdout.lines().skip(1).map(|l| serde_json::from_str(l).unwrap()).collect();
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned(), replies)
}
fn text(reply: &Value) -> &str {
reply["result"]["content"][0]["text"].as_str().unwrap()
}
#[test]
fn mcp_automation_roots_confine_the_server() {
let base = tmpdir("roots");
let (work, elsewhere) = (base.join("work"), base.join("elsewhere"));
std::fs::create_dir_all(&work).unwrap();
std::fs::create_dir_all(&elsewhere).unwrap();
std::fs::write(work.join("in.txt"), "Inside text").unwrap();
std::fs::write(elsewhere.join("secret.txt"), "TOP SECRET").unwrap();
let work_s = work.to_str().unwrap();
let secret = elsewhere.join("secret.txt").to_str().unwrap().to_string();
// Both spellings of the flags; inside works, outside is refused with a readable message.
let read_flag = format!("--automation-read-root={work_s}");
let calls = [
("open_presentation", serde_json::json!({"path": work.join("in.txt").to_str().unwrap()})),
("open_presentation", serde_json::json!({"path": secret})),
("save_presentation", serde_json::json!({"path": work.join("saved.deckcraft").to_str().unwrap()})),
("save_presentation", serde_json::json!({"path": elsewhere.join("saved.deckcraft").to_str().unwrap()})),
];
let (success, stderr, replies) = mcp_session(&[&read_flag, "--automation-write-root", work_s], &calls);
assert!(success, "{stderr}");
assert!(stderr.contains("files confined"), "{stderr}");
assert_eq!(replies[0]["result"]["isError"], false, "{}", replies[0]);
assert_eq!(replies[1]["result"]["isError"], true);
assert!(text(&replies[1]).contains("outside the read root"), "{}", text(&replies[1]));
assert_eq!(replies[2]["result"]["isError"], false, "{}", replies[2]);
assert!(work.join("saved.deckcraft").exists());
assert_eq!(replies[3]["result"]["isError"], true);
assert!(text(&replies[3]).contains("outside the write root"), "{}", text(&replies[3]));
assert!(!elsewhere.join("saved.deckcraft").exists());
// A root left out grants none of its access.
let save = [("new_presentation", serde_json::json!({})), calls[2].clone()];
let (_, _, replies) = mcp_session(&[&read_flag], &save);
assert_eq!(replies[1]["result"]["isError"], true);
assert!(text(&replies[1]).contains("write authority is absent"), "{}", text(&replies[1]));
// No flags: nothing is confined.
let (success, _, replies) = mcp_session(&[], &calls[1..2]);
assert!(success);
assert_eq!(replies[0]["result"]["isError"], false, "{}", replies[0]);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn mcp_accepts_multiple_read_and_write_roots() {
let base = tmpdir("multiple-roots");
let read1 = base.join("read1");
let read2 = base.join("read2");
let write1 = base.join("write1");
let write2 = base.join("write2");
for dir in [&read1, &read2, &write1, &write2] {
std::fs::create_dir_all(dir).unwrap();
}
let (input1, input2) = (read1.join("one.txt"), read2.join("two.txt"));
std::fs::write(&input1, "one").unwrap();
std::fs::write(&input2, "two").unwrap();
let (output1, output2) = (write1.join("one.deckcraft"), write2.join("two.deckcraft"));
let args = [
"--automation-read-root".to_owned(),
read1.to_string_lossy().into_owned(),
format!("--automation-read-root={}", read2.display()),
"--automation-write-root".to_owned(),
write1.to_string_lossy().into_owned(),
format!("--automation-write-root={}", write2.display()),
];
let args = args.iter().map(String::as_str).collect::<Vec<_>>();
let calls = [
("open_presentation", serde_json::json!({"path": input1})),
("open_presentation", serde_json::json!({"path": input2})),
("save_presentation", serde_json::json!({"path": output1})),
("save_presentation", serde_json::json!({"path": output2})),
];
let (success, stderr, replies) = mcp_session(&args, &calls);
assert!(success, "{stderr}");
for reply in &replies {
assert_eq!(reply["result"]["isError"], false, "{reply}");
}
assert!(output1.exists());
assert!(output2.exists());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn mcp_automation_root_flags_are_checked_up_front() {
let base = tmpdir("roots-args");
let dir = base.to_str().unwrap();
let missing = base.join("missing");
let fails = |args: &[&str], needle: &str| {
let mut full = vec!["mcp"];
full.extend_from_slice(args);
let o = run(&full);
assert!(!o.status.success(), "{args:?}");
let err = String::from_utf8_lossy(&o.stderr).into_owned();
assert!(err.contains(needle), "{args:?}: {err}");
};
// The flags confine the in-process server, so they cannot be combined with --connect.
fails(&["--connect", "7979", "--automation-read-root", dir], "--connect");
fails(&["--automation-write-root", dir, "--connect", "7979"], "--connect");
for flag in ["--automation-read-root", "--automation-write-root"] {
let mut full = vec!["mcp", flag, dir, flag];
full.push(dir);
let out = run(&full);
assert!(out.status.success(), "{flag}: {}", String::from_utf8_lossy(&out.stderr));
}
fails(&["--automation-read-root"], "needs a folder");
fails(&["--automation-write-root", "--sample"], "needs a folder");
fails(&["--automation-read-root", missing.to_str().unwrap()], "cannot open the automation read root");
fails(&["--automation-write-root="], "needs a non-empty folder");
// A file is not a folder.
std::fs::write(base.join("f.txt"), "x").unwrap();
fails(&["--automation-write-root", base.join("f.txt").to_str().unwrap()], "cannot open the automation write root");
let _ = std::fs::remove_dir_all(base);
}
+1 -5
View File
@@ -16,10 +16,6 @@ path = "src/main.rs"
[dependencies]
deckcraft-engine = { workspace = true }
deckcraft-ui-egui = { workspace = true }
# The page command API (storytold/craft-libs#413): window.deckcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
@@ -31,4 +27,4 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "MessageEvent", "Event", "EventTarget", "UrlSearchParams"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] }
+1 -1
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>DeckCraft</title>
<link data-trunk rel="rust" data-bin="deckcraft-web" data-wasm-opt="z" data-weak-refs />
<link data-trunk rel="icon" href="../../assets/app-icon/deckcraft.ico" />
<link data-trunk rel="icon" href="../../assets/app-icon/hicolor/32x32/apps/ai.storyteller.deckcraft.png" />
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262626; }
#deckcraft_canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
-151
View File
@@ -1,151 +0,0 @@
//! `window.deckcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the
//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`).
//!
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
//! `screenshot`, as promises with a timeout). This module is DeckCraft's part: a [`Request`] that
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
//! reply. A call the page gave up on is released ([`Pending`]), so the app skips it if it has not started it, instead of
//! applying a command the page was told had failed.
use std::sync::Arc;
use std::sync::atomic::AtomicU8;
use std::sync::mpsc::{Receiver, TryRecvError};
use deckcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
#[cfg(target_arch = "wasm32")]
const POLL_MS: i32 = 16;
/// A queued control request whose reply has not arrived. Dropping it before the reply (the page's
/// timeout fired, or the call was abandoned) releases the request: the app skips it if it has not started it (one it has taken still finishes).
struct Pending {
reply: Receiver<Value>,
state: Arc<AtomicU8>,
answered: bool,
}
impl Pending {
/// `Some` once the app has answered or gone away; `None` while the request is still waiting.
fn poll(&mut self) -> Option<Value> {
match self.reply.try_recv() {
Ok(reply) => {
self.answered = true;
Some(reply)
}
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => {
self.answered = true;
Some(json!({"ok": false, "error": "the app dropped the request"}))
}
}
}
}
impl Drop for Pending {
fn drop(&mut self) {
if !self.answered {
ControlRequest::abandon(&self.state);
}
}
}
#[cfg(target_arch = "wasm32")]
pub use web::install;
#[cfg(target_arch = "wasm32")]
mod web {
use std::rc::Rc;
use std::sync::mpsc::channel;
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use deckcraft_ui_egui::{ControlRequest, SlideApp};
use serde_json::json;
use wasm_bindgen_futures::JsFuture;
use super::{POLL_MS, Pending};
/// The app id in `window.<app>`.
const APP: &str = "deckcraft";
/// Give the app its control queue and put `window.deckcraft` on the page. An existing
/// `window.deckcraft` keeps the functions it already has.
pub fn install(app: &mut SlideApp, ctx: egui::Context) {
let (queue, requests) = channel::<ControlRequest>();
app.control_rx = Some(requests);
let request: Request = Rc::new(move |method, params| {
let (control, reply) = ControlRequest::new(method, params);
let mut pending = Pending { reply, state: control.state.clone(), answered: false };
if queue.send(control).is_err() {
pending.answered = true;
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
}
ctx.request_repaint();
Box::pin(async move {
loop {
if let Some(reply) = pending.poll() {
return reply;
}
sleep(POLL_MS).await;
}
})
});
if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() {
log::warn!("couldn't install window.{APP}: {e:?}");
}
}
async fn sleep(ms: i32) {
let promise = js_sys::Promise::new(&mut |resolve, _| {
if let Some(window) = web_sys::window() {
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
}
});
let _ = JsFuture::from(promise).await;
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::Ordering;
use super::*;
/// `ControlRequest`'s `state` values (`deckcraft_ui_egui::control`): the app has started it, or its
/// sender gave up.
const TAKEN: u8 = 1;
const ABANDONED: u8 = 2;
fn pending() -> (Pending, ControlRequest) {
let (control, reply) = ControlRequest::new("document.inspect", json!({}));
(Pending { reply, state: control.state.clone(), answered: false }, control)
}
#[test]
fn a_call_the_page_gave_up_on_is_released_so_the_app_skips_it() {
let (waiting, control) = pending();
drop(waiting);
assert_eq!(control.state.load(Ordering::SeqCst), ABANDONED);
assert!(!control.take(), "the app must not run a request the page was told had failed");
}
#[test]
fn an_answered_call_is_not_released() {
let (mut waiting, control) = pending();
assert!(control.take());
control.reply.send(json!({"ok": true, "result": 1})).unwrap_or_default();
assert_eq!(waiting.poll(), Some(json!({"ok": true, "result": 1})));
drop(waiting);
assert_eq!(control.state.load(Ordering::SeqCst), TAKEN);
}
#[test]
fn a_request_the_app_never_runs_waits_until_it_is_dropped() {
let (mut waiting, control) = pending();
assert_eq!(waiting.poll(), None);
drop(control);
assert_eq!(waiting.poll().and_then(|r| r["ok"].as_bool()), Some(false), "the app went away");
}
}
-149
View File
@@ -1,149 +0,0 @@
//! The host bridge, for pages that embed DeckCraft and keep its files (a Nextcloud app, a personal
//! file server). The messages and the two transports are `craft-web-host`'s
//! (storytold/craft-libs), the same contract as the other Craft apps' bridges, with the
//! `deckcraft:` prefix. This module is DeckCraft's part of it.
//!
//! - `?host=parent` (an `<iframe>`) talks to the same-origin parent over `postMessage`;
//! `data-host="page"` on the canvas (the page's own document, no iframe) uses DOM
//! `CustomEvent`s on the canvas instead. `?host=parent` wins when both are present. With no
//! parent, or a parent on another origin, there is no bridge: the normal app with downloads.
//! - `deckcraft:ready` (to the host): sent once the app is running and listening; send a file now. DeckCraft
//! reads bytes, so it says `file: false` and a host sends `bytes`.
//! - `deckcraft:open` (from the host): `{ name, bytes }`, bytes an `ArrayBuffer` or
//! `Uint8Array`, name a bare file name. It opens like a file picked with File › Open on the
//! desktop: a presentation sent with its name (.pptx, .potx, .ppsx, .deckcraft) has that name
//! as its file, so Save goes back to it; an outline (.txt, .md, .rtf), a file without a name and
//! a damaged file open untitled.
//! - `deckcraft:save` (to the host): `{ name, saveAs, bytes }` (with the bytes as a transferred `ArrayBuffer` over `postMessage`) for
//! every file DeckCraft would otherwise download. The host stores it and reports failures
//! itself. `saveAs` says whether the file becomes the presentation's file:
//! - Save: `false`. It writes the opened file under its own name and format (a .pptx stays a
//! .pptx), as the desktop app does. A name the parent never sent (an untitled presentation, an
//! outline, a file sent without a name, a repaired copy of a damaged file, a file the user
//! picked or dropped) is a new file: `true`, as for Save As, named `<title>.deckcraft` as
//! Save suggests on the desktop.
//! - Save As (File › Save As as .pptx or .deckcraft, Ctrl+Shift+S): `true`. The presentation is
//! now that file; the next Save sends its name with `false`.
//! - Export (PDF, pictures, outline, GIF, handouts, a Save As type that isn't a presentation)
//! and Print: `false`. They are copies; the presentation's file stays the same.
//! - `deckcraft:dirty` whenever unsaved changes appear or go away, `deckcraft:failed` when the
//! app couldn't start or refused a file of 2 GiB or larger.
//!
//! In host mode the app starts with an empty presentation instead of the sample, which gives way to
//! the first file the host sends; the host guards leaving the page, and `?author=` names the user
//! for comments.
use std::cell::RefCell;
use std::rc::Rc;
use craft_web_host::web::{FileData, Host, Message};
use deckcraft_ui_egui::{Services, SlideApp};
/// The app id in the host messages (`deckcraft:ready`).
const APP: &str = "deckcraft";
/// The name `craft-web-host` gives an open request that carries none (it cleans a host's name and
/// falls back to this): no name is no file, so the presentation opens untitled.
const NAMELESS: &str = "document";
/// The largest file a host may send. File › Open on the desktop refuses anything over 2 GiB.
/// On wasm32 a `Vec` cannot hold 2 GiB (`isize::MAX` is one byte less), so a file of exactly
/// 2 GiB is refused too, before its bytes are copied.
const MAX_OPEN_BYTES: f64 = 2_147_483_648.0;
/// The longest user name taken from `?author=` (the preferences' own limit).
const MAX_AUTHOR_CHARS: usize = 256;
#[derive(Clone)]
pub struct Bridge {
host: Rc<Host>,
/// Files the host sent (the name, if it sent one), waiting for the next frame.
opened: Rc<RefCell<Vec<(Option<String>, Vec<u8>)>>>,
}
impl Bridge {
/// The bridge for this page, or `None` when DeckCraft isn't hosted: no `?host=parent` and no
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
/// with downloads), or a parent on another origin.
pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
let host = Host::connect(APP, canvas)?;
// An opaque origin (a file:// page in some browsers) can't be a postMessage target.
if host.mode() == craft_web_host::Mode::Parent && web_sys::window()?.location().origin().ok()? == "null" {
return None;
}
Some(Self { host: Rc::new(host), opened: Rc::default() })
}
/// Hand saved and exported files to the host instead of downloading them, and hear the files
/// it sends.
pub fn connect(&self, services: &mut Services, ctx: egui::Context) {
self.listen(ctx);
let bridge = self.clone();
services.host_save = Some(Box::new(move |name: &str, bytes: &[u8], save_as: bool| bridge.post_save(name, bytes, save_as)));
// Exports and Print are copies.
let bridge = self.clone();
services.download = Some(Box::new(move |name: &str, bytes: &[u8]| {
if let Err(e) = bridge.post_save(name, bytes, false) {
log::error!("couldn't hand {name} to the page: {e}");
}
}));
}
/// `?author=`: the host's name for the user signs new comments.
pub fn set_author(app: &mut SlideApp, author: &str) {
let author: String = author.trim().chars().take(MAX_AUTHOR_CHARS).collect();
if !author.is_empty() {
app.session.prefs.author = author;
}
}
pub fn post_ready(&self) {
let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false);
}
/// The app couldn't start (no WebGPU or WebGL2, for example): let the host say so.
pub fn post_failed(&self, error: &str) {
let _ = self.host.post_failed(error, None);
}
/// Before each frame: open the files the host sent.
pub fn open_files(&self, app: &mut SlideApp) {
let opened = std::mem::take(&mut *self.opened.borrow_mut());
for (name, bytes) in opened {
app.open_from_host(name.as_deref(), &bytes);
}
}
/// After each frame: tell the host when unsaved changes appear or go away (the crate does not
/// repeat a state it already reported).
pub fn report_dirty(&self, app: &SlideApp) {
self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty()));
}
fn post_save(&self, path: &str, bytes: &[u8], save_as: bool) -> Result<(), String> {
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
self.host.post_save(&name, bytes, None, save_as)
}
/// Hear `deckcraft:open` and queue the file for the next frame.
fn listen(&self, ctx: egui::Context) {
let opened = self.opened.clone();
let host = self.host.clone();
self.host.listen(move |message| {
let Message::Open { name, data } = message else { return };
if data.size() >= MAX_OPEN_BYTES {
log::warn!("host file {name} is 2 GiB or larger; not opened");
let _ = host.post_failed(&format!("{name} is 2 GiB or larger, which DeckCraft's web build cannot open"), None);
return;
}
let FileData::Bytes(array) = data else {
log::warn!("host file {name} came as a File; DeckCraft reads bytes only; not opened");
return;
};
// No name is no file: the presentation opens untitled, never under an invented name.
let name = (name != NAMELESS).then_some(name);
opened.borrow_mut().push((name, array.to_vec()));
ctx.request_repaint();
});
}
}
+2 -12
View File
@@ -7,26 +7,16 @@
//! Differences from the desktop app:
//! - no TCP control channel (browsers can't listen on sockets);
//! - File → Open and Insert → Pictures/Audio/Video use the browser file picker; bytes arrive
//! asynchronously through `Services::inbox`, applied to the document, slide and operation
//! that started the pick (a dismissed picker or a closed document drops the file);
//! - Save and Export trigger a browser download (or go to the framing page with `?host=parent`);
//! asynchronously through `Services::inbox` (presentations open, media is inserted);
//! - Save and Export trigger a browser download;
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
//! - preferences are not persisted.
//!
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?blank` starts with an
//! empty presentation instead of the sample deck; `?show` starts the slide show.
//! `?host=parent` (inside an `<iframe>`) talks to a same-origin parent page instead: it sends the
//! presentation to open and stores what DeckCraft saves (`host`), and `&author=` names the user
//! for comments.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(any(target_arch = "wasm32", test))]
mod api;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(target_arch = "wasm32")]
mod presenter;
#[cfg(target_arch = "wasm32")]
mod web;
-306
View File
@@ -1,306 +0,0 @@
//! Same-origin popup transport. Each window starts its own eframe/WASM runner.
use deckcraft_ui_egui::presenter::{Command, DeltaCache, Host, Snapshot, View};
use std::{
cell::RefCell,
collections::VecDeque,
rc::{Rc, Weak},
};
use wasm_bindgen::{JsCast, closure::Closure};
const MAX_MESSAGE: usize = 16 * 1024 * 1024;
const MAX_COMMANDS: usize = 64;
const PREFIX: &str = "#deckcraft-presenter=";
fn error(e: wasm_bindgen::JsValue) -> String {
format!("{e:?}")
}
fn origin() -> Result<String, String> {
web_sys::window().ok_or("No browser window")?.location().origin().map_err(error)
}
pub fn token() -> Option<String> {
let hash = web_sys::window()?.location().hash().ok()?;
let token = hash.strip_prefix(PREFIX)?;
(!token.is_empty() && token.len() < 128).then(|| token.to_owned())
}
fn same_source(event: &web_sys::MessageEvent, window: &web_sys::Window, expected_origin: &str) -> bool {
event.origin() == expected_origin && event.source().is_some_and(|source| js_sys::Object::is(source.as_ref(), window.as_ref()))
}
fn send(window: &web_sys::Window, origin: &str, value: serde_json::Value) -> Result<(), String> {
let text = serde_json::to_string(&value).map_err(|e| e.to_string())?;
if text.len() > MAX_MESSAGE {
return Err("Presenter message is too large".into());
}
window.post_message(&wasm_bindgen::JsValue::from_str(&text), origin).map_err(error)
}
struct State {
popup: Option<web_sys::Window>,
token: String,
commands: VecDeque<Command>,
ready: bool,
refresh_images: bool,
}
pub struct BrowserHost {
state: Rc<RefCell<State>>,
origin: String,
listener: Closure<dyn FnMut(web_sys::MessageEvent)>,
button: Option<(web_sys::HtmlElement, Closure<dyn FnMut(web_sys::Event)>)>,
images: DeltaCache,
}
impl BrowserHost {
pub fn new(ctx: egui::Context) -> Result<Self, String> {
let window = web_sys::window().ok_or("No browser window")?;
let origin = origin()?;
let state = Rc::new(RefCell::new(State { popup: None, token: String::new(), commands: VecDeque::new(), ready: false, refresh_images: true }));
let weak = Rc::downgrade(&state);
let expected = origin.clone();
let listener = Closure::new(move |event: web_sys::MessageEvent| {
let Some(state) = weak.upgrade() else { return };
let Ok(mut state) = state.try_borrow_mut() else { return };
let Some(popup) = state.popup.as_ref() else { return };
if !same_source(&event, popup, &expected) {
return;
}
let Some(text) = event.data().as_string().filter(|s| s.len() <= 8192) else { return };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return };
if value.get("token").and_then(|v| v.as_str()) != Some(state.token.as_str()) {
return;
}
match value.get("kind").and_then(|v| v.as_str()) {
Some("ready") => {
state.ready = true;
state.refresh_images = true;
}
Some("command") if state.commands.len() < MAX_COMMANDS => {
if let Some(command) = value.get("command").and_then(|v| serde_json::from_value(v.clone()).ok()) {
state.commands.push_back(command);
}
}
_ => {}
}
ctx.request_repaint();
});
window.add_event_listener_with_callback("message", listener.as_ref().unchecked_ref()).map_err(error)?;
Ok(Self { state, origin, listener, button: None, images: DeltaCache::default() })
}
fn remove_button(&mut self) {
if let Some((button, callback)) = self.button.take() {
let _ = button.remove_event_listener_with_callback("click", callback.as_ref().unchecked_ref());
button.remove();
}
}
fn recovery_button(&mut self) {
if self.button.is_some() {
return;
}
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
let Some(body) = document.body() else { return };
let Ok(element) = document.create_element("button") else { return };
let Ok(button) = element.dyn_into::<web_sys::HtmlElement>() else { return };
button.set_text_content(Some("Open presenter window"));
let _ = button.set_attribute("style", "position:fixed;top:12px;right:12px;z-index:9999;padding:12px;color:white;background:#333;border:1px solid #aaa;border-radius:4px;cursor:pointer");
let weak: Weak<RefCell<State>> = Rc::downgrade(&self.state);
let button_copy = button.clone();
let callback = Closure::new(move |_event: web_sys::Event| {
if let Some(state) = weak.upgrade() {
match open_popup(&state) {
Ok(()) => {
button_copy.set_text_content(Some("Opening presenter window…"));
}
Err(_) => {
button_copy.set_text_content(Some("Popup blocked. Allow popups, then click to retry."));
}
}
}
});
if button.add_event_listener_with_callback("click", callback.as_ref().unchecked_ref()).is_ok() && body.append_child(&button).is_ok() {
self.button = Some((button, callback));
} else {
let _ = button.remove_event_listener_with_callback("click", callback.as_ref().unchecked_ref());
button.remove();
}
}
}
fn open_popup(state: &Rc<RefCell<State>>) -> Result<(), String> {
let window = web_sys::window().ok_or("No browser window")?;
let mut state = state.try_borrow_mut().map_err(|_| "Presenter is busy")?;
if let Some(popup) = &state.popup
&& !popup.closed().unwrap_or(true)
{
let _ = popup.focus();
return Ok(());
}
let token = format!("{}-{}", js_sys::Date::now(), js_sys::Math::random());
let url = web_sys::Url::new(&window.location().href().map_err(error)?).map_err(error)?;
url.set_hash(&format!("{PREFIX}{token}"));
let popup = window
.open_with_url_and_target_and_features(&url.href(), "_blank", "popup,width=1100,height=700")
.map_err(error)?
.ok_or("Presenter popup was blocked. Use Open presenter window to retry.")?;
if popup.closed().unwrap_or(true) {
return Err("Browser isolation prevented connecting the presenter window".into());
}
state.popup = Some(popup);
state.token = token;
state.commands.clear();
state.ready = false;
Ok(())
}
impl Host for BrowserHost {
fn open(&mut self) -> Result<(), String> {
self.close();
let result = open_popup(&self.state);
if result.is_err() {
self.recovery_button();
}
result
}
fn is_open(&self) -> bool {
self.state.borrow().popup.as_ref().is_some_and(|w| !w.closed().unwrap_or(true))
}
fn commands(&mut self) -> Vec<Command> {
self.state.borrow_mut().commands.drain(..).collect()
}
fn update(&mut self, snapshot: Snapshot) {
if !self.is_open() {
self.recovery_button();
return;
}
self.remove_button();
let mut state = self.state.borrow_mut();
if !state.ready {
return;
}
if let Some(popup) = state.popup.clone() {
let token = state.token.clone();
let sent = self.images.send(snapshot, &token, state.refresh_images, |delta, current_changed, next_changed| {
send(
&popup,
&self.origin,
serde_json::json!({"kind":"snapshot", "token":token, "snapshot":delta,
"currentChanged":current_changed, "nextChanged":next_changed}),
)
});
if sent.is_ok() {
state.refresh_images = false;
}
}
}
fn close(&mut self) {
self.remove_button();
let mut state = self.state.borrow_mut();
if let Some(window) = state.popup.take() {
let _ = window.close();
}
state.commands.clear();
state.ready = false;
state.token.clear();
}
}
impl Drop for BrowserHost {
fn drop(&mut self) {
self.close();
if let Some(window) = web_sys::window() {
let _ = window.remove_event_listener_with_callback("message", self.listener.as_ref().unchecked_ref());
}
}
}
pub struct Popup {
token: String,
origin: String,
opener: web_sys::Window,
snapshot: Rc<RefCell<Option<Snapshot>>>,
last_received: Rc<RefCell<f64>>,
listener: Closure<dyn FnMut(web_sys::MessageEvent)>,
view: View,
}
impl Popup {
pub fn new(token: String, ctx: egui::Context) -> Result<Self, String> {
let window = web_sys::window().ok_or("No browser window")?;
// `opener` is a WindowProxy from another realm; instanceof Window can fail across
// realms. The browser API supplies a WindowProxy or null, and messages still verify
// exact source identity and origin before any data is accepted.
let opener = window.opener().map_err(error)?;
if opener.is_null() || opener.is_undefined() {
return Err("The audience window is unavailable".into());
}
let opener: web_sys::Window = opener.unchecked_into();
let origin = origin()?;
let snapshot: Rc<RefCell<Option<Snapshot>>> = Rc::new(RefCell::new(None));
let last_received = Rc::new(RefCell::new(js_sys::Date::now()));
let received = last_received.clone();
let target = snapshot.clone();
let expected_origin = origin.clone();
let expected_opener = opener.clone();
let expected_token = token.clone();
let listener = Closure::new(move |event: web_sys::MessageEvent| {
if !same_source(&event, &expected_opener, &expected_origin) {
return;
}
let Some(text) = event.data().as_string().filter(|s| s.len() <= MAX_MESSAGE) else { return };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return };
if value.get("token").and_then(|v| v.as_str()) != Some(expected_token.as_str())
|| value.get("kind").and_then(|v| v.as_str()) != Some("snapshot")
{
return;
}
if let Some(mut data) = value.get("snapshot").and_then(|v| serde_json::from_value::<Snapshot>(v.clone()).ok()) {
if let Some(previous) = target.borrow().as_ref() {
if value.get("currentChanged").and_then(|v| v.as_bool()) == Some(false) {
data.current = previous.current.clone();
}
if value.get("nextChanged").and_then(|v| v.as_bool()) == Some(false) {
data.next = previous.next.clone();
}
if data.slides.is_none() {
data.slides = previous.slides.clone();
}
}
*target.borrow_mut() = Some(data);
*received.borrow_mut() = js_sys::Date::now();
ctx.request_repaint();
}
});
window.add_event_listener_with_callback("message", listener.as_ref().unchecked_ref()).map_err(error)?;
if let Some(document) = window.document() {
document.set_title("Presenter View — DeckCraft");
}
let popup = Self { token, origin, opener, snapshot, last_received, listener, view: View::default() };
send(&popup.opener, &popup.origin, serde_json::json!({"kind":"ready","token":popup.token}))?;
Ok(popup)
}
}
impl eframe::App for Popup {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let snapshot = self.snapshot.borrow();
let notes = snapshot.as_ref().map_or("", |snapshot| snapshot.notes.as_str());
if !self.view.prepare(ui.ctx(), notes) {
return;
}
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
if self.opener.closed().unwrap_or(true) {
ui.heading("The audience window has closed.");
return;
}
if js_sys::Date::now() - *self.last_received.borrow() > 10_000.0 {
ui.heading("The audience window is not responding.");
ui.label("Return to the audience window to resume the connection.");
return;
}
egui::CentralPanel::default().show(ui, |ui| {
if let Some(snapshot) = snapshot.as_ref() {
for command in self.view.ui(ui, snapshot) {
let _ = send(&self.opener, &self.origin, serde_json::json!({"kind":"command","token":self.token,"command":command}));
}
} else {
ui.label("Waiting for the audience window…");
}
});
}
}
impl Drop for Popup {
fn drop(&mut self) {
if let Some(window) = web_sys::window() {
let _ = window.remove_event_listener_with_callback("message", self.listener.as_ref().unchecked_ref());
}
}
}
+18 -104
View File
@@ -1,7 +1,7 @@
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
use deckcraft_engine::Session;
use deckcraft_ui_egui::{Inbox, InboxEvent, InboxFile, Services, SlideApp};
use deckcraft_ui_egui::{Inbox, Services, SlideApp};
use wasm_bindgen::JsCast as _;
const PRESENTATION_EXTS: &[&str] = &["deckcraft", "pptx", "potx", "ppsx", "txt", "md"];
@@ -11,8 +11,6 @@ const VIDEO_EXTS: &[&str] = &["mp4", "m4v", "mov", "webm"];
const CANVAS_ID: &str = "deckcraft_canvas";
const LOADING_ID: &str = "deckcraft_loading";
/// Start the browser shell: install logging, locate the canvas, launch the eframe runner,
/// build the sample or blank deck, and replace the loading element when launch finishes.
pub fn start() {
eframe::WebLogger::init(log::LevelFilter::Info).ok();
wasm_bindgen_futures::spawn_local(async {
@@ -24,18 +22,8 @@ pub fn start() {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
};
// Host modes (`craft-web-host`): `?host=parent`, a same-origin page framing DeckCraft,
// opens presentations in it and stores what it saves (`host`); `data-host="page"` on the
// canvas opts a page in that runs DeckCraft in its own document. The presenter popup is
// never the framed page.
let hosted = crate::presenter::token().is_none();
let bridge = if hosted { crate::host::Bridge::detect(&canvas) } else { None };
if hosted && bridge.is_none() && query_param("host").as_deref() == Some("parent") {
log::warn!("?host=parent needs a framing page on the same origin; saves download instead");
}
let app_bridge = bridge.clone();
let mut options = eframe::WebOptions::default();
if query_has("webgl")
if query().contains("webgl")
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
{
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
@@ -48,49 +36,23 @@ pub fn start() {
if let Some(rs) = &cc.wgpu_render_state {
log::info!("deckcraft-web {}: wgpu backend {:?}", env!("CARGO_PKG_VERSION"), rs.adapter.get_info().backend);
}
deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx);
if let Some(token) = crate::presenter::token() {
let presenter = crate::presenter::Popup::new(token, cc.egui_ctx.clone()).map_err(std::io::Error::other)?;
return Ok(Box::new(presenter) as Box<dyn eframe::App>);
}
let inbox: Inbox = Inbox::default();
let mut services = services(inbox.clone(), cc.egui_ctx.clone());
if let Some(bridge) = &app_bridge {
bridge.connect(&mut services, cc.egui_ctx.clone());
}
let mut app = SlideApp::new(Session::new(), services);
// In host mode the parent sends the presentation to edit; no sample meanwhile.
if app_bridge.is_some() {
if let Err(e) = app.start_for_host() {
log::error!("new presentation: {e}");
}
} else if !query_has("blank") {
let mut app = SlideApp::new(Session::new(), services(inbox.clone(), cc.egui_ctx.clone()));
let q = query();
if !q.contains("blank") {
if let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) {
log::error!("sample deck: {e}");
}
} else if let Err(e) = app.run("file.new", serde_json::json!({})) {
log::error!("new presentation: {e}");
}
if query_has("show") {
if q.contains("show") {
app.start_show(0, false);
}
if app_bridge.is_some()
&& let Some(author) = query_param("author")
{
crate::host::Bridge::set_author(&mut app, &author);
}
crate::api::install(&mut app, cc.egui_ctx.clone());
Ok(Box::new(WebShell { app, inbox, bridge: app_bridge }))
Ok(Box::new(WebShell { app, inbox }))
}),
)
.await;
// Ready only once the runner is up: starting can still fail after the app is made.
if let Some(bridge) = &bridge {
match &result {
Ok(()) => bridge.post_ready(),
Err(e) => bridge.post_failed(&format!("{e:?}")),
}
}
if let Some(el) = document.get_element_by_id(LOADING_ID) {
match result {
Ok(()) => el.remove(),
@@ -104,68 +66,35 @@ fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
fn query_param(key: &str) -> Option<String> {
web_sys::UrlSearchParams::new_with_str(&query()).ok()?.get(key)
}
/// Whether the URL has the flag `key` (`?show`, `&blank=1`). A whole parameter, never a substring:
/// `?author=` is free text.
fn query_has(key: &str) -> bool {
web_sys::UrlSearchParams::new_with_str(&query()).is_ok_and(|q| q.has(key))
}
/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously)
/// and feed them through the inbox.
struct WebShell {
app: SlideApp,
inbox: Inbox,
/// The parent page that keeps the files (`?host=parent`).
bridge: Option<crate::host::Bridge>,
}
impl eframe::App for WebShell {
/// Delegate one eframe logic pass to the wrapped application, opening the files the parent
/// page sent first and telling it about unsaved changes after.
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
if let Some(bridge) = &self.bridge {
bridge.open_files(&mut self.app);
}
self.app.logic(ctx);
if let Some(bridge) = &self.bridge {
bridge.report_dirty(&self.app);
}
if self.app.show.is_none()
&& let Some(host) = self.app.services.presenter.as_mut()
{
host.close();
}
}
/// Consume browser drops with fresh input, capture the identity before the asynchronous read,
/// and deliver the id, name, and bytes through the inbox.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Browsers cannot read dropped files synchronously. Consume this pass's drops here, with
// fresh input, and capture the document/slide before the asynchronous read finishes.
for f in std::mem::take(&mut raw.dropped_files) {
let id = self.app.begin_external_file("drop");
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
for f in dropped {
let inbox = self.inbox.clone();
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
match f.bytes_async().await {
Ok(bytes) => {
push_inbox(&inbox, InboxEvent::File(InboxFile { id, name, bytes }));
ctx.request_repaint();
}
Err(e) => {
log::error!("couldn't read dropped file {name}: {e}");
push_inbox(&inbox, InboxEvent::Cancelled { id });
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));
ctx.request_repaint();
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
}
});
}
self.app.raw_input_hook(ctx, raw);
self.app.logic(ctx);
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(raw);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
@@ -177,16 +106,8 @@ impl eframe::App for WebShell {
/// back to `open_async` (browser picker → inbox) and `download`.
fn services(inbox: Inbox, ctx: egui::Context) -> Services {
let open_inbox = inbox.clone();
let presenter = match crate::presenter::BrowserHost::new(ctx.clone()) {
Ok(host) => Some(Box::new(host) as Box<dyn deckcraft_ui_egui::presenter::Host>),
Err(error) => {
log::error!("Presenter window: {error}");
None
}
};
Services {
presenter,
open_async: Some(Box::new(move |purpose: &str, request: u64| {
open_async: Some(Box::new(move |purpose: &str| {
let inbox = open_inbox.clone();
let ctx = ctx.clone();
let dialog = match purpose {
@@ -197,12 +118,10 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
};
wasm_bindgen_futures::spawn_local(async move {
let Some(file) = dialog.pick_file().await else {
push_inbox(&inbox, InboxEvent::Cancelled { id: request });
ctx.request_repaint();
return;
};
let bytes = file.read().await;
push_inbox(&inbox, InboxEvent::File(InboxFile { id: request, name: file.file_name(), bytes }));
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
ctx.request_repaint();
});
})),
@@ -217,10 +136,6 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
}
}
fn push_inbox(inbox: &Inbox, event: InboxEvent) {
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(event);
}
/// Trigger a browser download of `bytes` named after the last component of `path`.
fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
@@ -253,7 +168,6 @@ fn mime_for(name: &str) -> &'static str {
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("pdf") => "application/pdf",
Some("gif") => "image/gif",
Some("txt") => "text/plain",
Some("pptx") => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
Some("deckcraft") => "application/zip",
+1 -12
View File
@@ -14,31 +14,20 @@ workspace = true
deckcraft-engine = { workspace = true }
deckcraft-ui-egui = { workspace = true }
deckcraft-media = { workspace = true }
# `clipboard` is the OS clipboard (Ctrl+C/X/V with other apps). Without it egui simulates one inside
# the app; the egui 0.37 migration (#1350) dropped it from this list.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "links", "wayland", "x11"] }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "links", "wayland", "x11"] }
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
chrono = { workspace = true }
[build-dependencies]
# Icon + VERSIONINFO for deckcraft.exe; build.rs only uses it when the target is Windows.
winresource = "0.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
image = { workspace = true }
cpal = "0.16"
[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
# GridCraft, PdfCraft and PhotoCraft) registers the handler (Objective-C interop needs unsafe, which
# our workspace forbids) behind a safe API. Pinned exactly: review the diff before bumping.
fmv-macos-events = "=0.1.0"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
-53
View File
@@ -1,53 +0,0 @@
//! macOS open-documents and quit Apple events.
//!
//! Finder double-clicks, Open With, drops on the Dock icon and `open -a DeckCraft deck.pptx` don't
//! pass paths on the command line: LaunchServices sends the running (or just-launched) app a
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
//! `NSApplicationDelegate`. Handling it ourselves needs Objective-C class declarations, i.e.
//! `unsafe`, which this workspace forbids. The audited `fmv-macos-events` crate (also used by
//! GridCraft, PdfCraft and PhotoCraft) wraps exactly that, an `NSAppleEventManager` handler
//! registered before Finder's launch event that leaves winit's delegate alone, behind a safe
//! main-thread API.
use deckcraft_ui_egui::SlideApp;
use fmv_macos_events::{Event, Inbox, Registration};
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
pub struct AppleEvents {
_registration: Registration,
inbox: Inbox,
}
impl AppleEvents {
/// Register the handlers. Call on the main thread before the event loop starts, so the event
/// that launched the app (a Finder double-click) is caught too.
pub fn install() -> Self {
let (registration, inbox) = Registration::install();
Self { _registration: registration, inbox }
}
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
let ctx = ctx.clone();
self.inbox.set_wake(move || ctx.request_repaint());
self.inbox.clone()
}
}
/// Open the documents and act on the quit requests that arrived since the last frame.
pub fn poll(inbox: &Inbox, app: &mut SlideApp, ctx: &egui::Context) {
for e in inbox.drain() {
match e {
Event::Open(paths) => {
for p in paths.iter().filter_map(|p| p.to_str()) {
if let Err(e) = app.open_path(p) {
let safe_p = p.replace(['\r', '\n'], " ");
log::error!("{safe_p}: {e}");
app.set_status(format!("Couldn't open {safe_p}: {e}"));
}
}
}
Event::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
}
}
}
+1 -18
View File
@@ -1,7 +1,6 @@
//! cpal audio output for media playback: the device pulls mixed samples from the
//! `deckcraft_media::Player`, which makes it the playback clock video frames follow.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
@@ -30,8 +29,6 @@ fn take_stream_error(slot: &ErrorSlot) -> Option<String> {
pub struct CpalOut {
stream: Option<cpal::Stream>,
error: ErrorSlot,
/// Set by the realtime error callback when the device went away: the stream is dead.
dead: Arc<AtomicBool>,
}
impl CpalOut {
@@ -59,14 +56,7 @@ impl AudioOut for CpalOut {
let rate = cfg.sample_rate().0;
let config: cpal::StreamConfig = cfg.clone().into();
let slot = self.error.clone();
let dead = Arc::new(AtomicBool::new(false));
self.dead = dead.clone();
let err = move |e: cpal::StreamError| {
if matches!(e, cpal::StreamError::DeviceNotAvailable) {
dead.store(true, Ordering::Relaxed);
}
keep_stream_error(&slot, &e);
};
let err = move |e: cpal::StreamError| keep_stream_error(&slot, &e);
let stream = match cfg.sample_format() {
cpal::SampleFormat::F32 => dev.build_output_stream(&config, move |buf: &mut [f32], _| fill(buf, channels, rate), err, None),
cpal::SampleFormat::I16 => {
@@ -96,13 +86,6 @@ impl AudioOut for CpalOut {
self.stream = None;
self.report();
}
fn failure(&mut self) -> Option<String> {
if !self.dead.swap(false, Ordering::Relaxed) {
return None;
}
Some(take_stream_error(&self.error).unwrap_or_else(|| "the audio device is no longer available".to_string()))
}
}
#[cfg(test)]
+30 -278
View File
@@ -1,310 +1,62 @@
//! Loopback JSON-lines control server: one request per line, one reply per line.
//! This is the transport the MCP server (`deckcraft-cli mcp --connect`) wraps.
//!
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
use std::time::{Duration, Instant};
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use deckcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
/// Resource bounds for the control server.
#[derive(Clone, Copy, Debug)]
pub struct Limits {
/// Connections served at once; more are told `busy` and closed.
pub max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
pub max_line: usize,
/// Requests waiting for the UI at once; more are answered `busy`.
pub queue: usize,
/// How long a connection may go without sending a byte before it is closed.
pub idle_timeout: Duration,
/// How long a reply write may block before the connection is closed.
pub write_timeout: Duration,
/// How long a request waits for the UI's answer.
pub reply_timeout: Duration,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_clients: 16,
// Picture and media inserts carry base64 payloads: room for files of about 190 MB.
max_line: 256 * 1024 * 1024,
queue: 64,
idle_timeout: Duration::from_secs(600),
write_timeout: Duration::from_secs(30),
reply_timeout: Duration::from_secs(60),
}
}
}
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => {
log::info!("control server listening on 127.0.0.1:{port}");
serve_listener(l, Limits::default(), ctx)
}
let (tx, rx) = channel::<ControlRequest>();
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
sync_channel::<ControlRequest>(0).1
return rx;
}
}
}
/// How long the accepting thread waits after a failed accept. Accepting can keep failing, for
/// example while the process has no file descriptors left, and retrying at once would keep a
/// core busy until it recovers.
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
/// The longest a connection refused as busy is drained before it is closed.
const REFUSED_GRACE: Duration = Duration::from_millis(250);
/// Refused connections drained at once, each on a thread of its own. Past this many, a refused
/// connection gets the busy reply and is closed without a drain.
const MAX_REFUSING: usize = 16;
/// The connections `incoming` accepts, calling `wait` after each failed accept.
fn accepted<T>(incoming: impl Iterator<Item = std::io::Result<T>>, mut wait: impl FnMut()) -> impl Iterator<Item = T> {
incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok())
}
/// Accept connections on `listener` under `limits`; requests arrive on the returned receiver.
fn serve_listener(listener: TcpListener, limits: Limits, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = sync_channel::<ControlRequest>(limits.queue.max(1));
let active = Arc::new(AtomicUsize::new(0));
let refusing = Arc::new(AtomicUsize::new(0));
};
log::info!("control server listening on 127.0.0.1:{port}");
std::thread::spawn(move || {
for mut stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) {
let _ = stream.set_write_timeout(Some(limits.write_timeout));
if active.fetch_add(1, Ordering::SeqCst) >= limits.max_clients {
active.fetch_sub(1, Ordering::SeqCst);
let _ = writeln!(stream, "{}", json!({"ok": false, "error": "busy: too many control connections"}));
refuse(stream, &refusing, limits.write_timeout.min(REFUSED_GRACE));
continue;
}
let slot = Slot(Arc::clone(&active));
for stream in listener.incoming().flatten() {
let tx = tx.clone();
let ctx = ctx.clone();
let spawned = std::thread::Builder::new().name("control-client".into()).spawn(move || {
let _slot = slot;
serve(stream, &tx, &ctx, limits);
});
if spawned.is_err() {
log::warn!("control server could not start a client thread");
}
std::thread::spawn(move || serve(stream, tx, ctx));
}
});
rx
}
/// Close a connection that was told it is refused. A peer that wrote a line before it read the
/// reply would see only a reset, so the connection is drained for up to `grace` first, on a
/// thread of its own: the accepting thread goes straight back to accepting. Past
/// [`MAX_REFUSING`] drains at once, the connection is closed without one.
fn refuse(stream: TcpStream, refusing: &Arc<AtomicUsize>, grace: Duration) {
if refusing.fetch_add(1, Ordering::SeqCst) >= MAX_REFUSING {
refusing.fetch_sub(1, Ordering::SeqCst);
return;
}
let slot = Slot(Arc::clone(refusing));
let spawned = std::thread::Builder::new().name("control-refused".into()).spawn(move || {
let _slot = slot;
if let Ok(read) = stream.try_clone() {
close_politely(&stream, &mut BufReader::new(read), grace);
}
});
if spawned.is_err() {
log::warn!("control server could not start a thread to close a refused connection");
}
}
/// Holds one connection slot; gives it back when the client thread ends, however it ends.
struct Slot(Arc<AtomicUsize>);
impl Drop for Slot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
enum Line {
Text(Vec<u8>),
TooLong,
Closed,
}
/// Read one `\n`-terminated line of at most `max` bytes without buffering more than `max + 1`.
fn read_line(r: &mut impl BufRead, max: usize) -> Line {
let mut buf = Vec::new();
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
match r.by_ref().take(limit).read_until(b'\n', &mut buf) {
Ok(0) | Err(_) => Line::Closed,
Ok(_) => {
if buf.last() == Some(&b'\n') {
buf.pop();
Line::Text(buf)
} else if buf.len() > max {
Line::TooLong
} else {
// EOF inside a line: serve what arrived, the next read reports Closed.
Line::Text(buf)
}
}
}
}
/// One request line, parsed.
enum Parsed {
Request {
id: Value,
method: String,
params: Value,
},
Blank,
/// Not a request: reply with this error and close the connection.
Reject(String),
}
fn parse(bytes: &[u8]) -> Parsed {
let Ok(text) = std::str::from_utf8(bytes) else {
return Parsed::Reject("not a control request (invalid UTF-8); closing the connection".into());
};
let text = text.trim();
if text.is_empty() {
return Parsed::Blank;
}
if is_http_request_line(text) {
return Parsed::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
}
let msg = match serde_json::from_str::<Value>(text) {
Ok(v) => v,
Err(e) => return Parsed::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")),
};
let Some(obj) = msg.as_object() else {
return Parsed::Reject("not a control request (expected a JSON object); closing the connection".into());
};
let Some(method) = obj.get("method").and_then(Value::as_str) else {
return Parsed::Reject("not a control request (missing string `method`); closing the connection".into());
};
Parsed::Request {
id: obj.get("id").cloned().unwrap_or(Value::Null),
method: method.to_string(),
params: obj.get("params").cloned().unwrap_or(json!({})),
}
}
/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`).
fn is_http_request_line(text: &str) -> bool {
const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"];
text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method))
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
}
/// Close after the last reply so the peer can still read it. A peer that had sent another line
/// before the reply arrived -- two lines in one write, which any script does -- leaves input
/// unread in the socket, and closing a socket with unread input resets the connection: the reply
/// already queued for the peer is discarded and it sees only the reset. Sending the FIN first and
/// then draining, briefly and boundedly, makes the close orderly and the reason survive.
fn close_politely(out: &TcpStream, reader: &mut BufReader<TcpStream>, grace: Duration) {
if out.shutdown(Shutdown::Write).is_err() {
return;
}
// Enough for a pipelined line or two; a peer that keeps talking is dropped at the deadline.
// The timeout is what is left of the grace before each read, not the whole of it: a peer that
// sends a byte just before each one expires would otherwise hold this thread, and its slot,
// for close to twice as long as the deadline says. The timeout is set on the handle that
// reads: on Windows, a read timeout set on one handle of a `try_clone` pair can fail to apply
// to reads through the other.
const MAX_DRAIN: usize = 64 << 10;
let until = Instant::now() + grace;
let mut sink = [0u8; 4 << 10];
let mut drained = 0;
while drained < MAX_DRAIN {
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() || reader.get_ref().set_read_timeout(Some(left)).is_err() {
break;
}
match reader.read(&mut sink) {
Ok(0) | Err(_) => break,
Ok(n) => drained += n,
}
}
}
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits) {
if stream.set_read_timeout(Some(limits.idle_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() {
return;
}
fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context) {
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
let mut reader = BufReader::new(read);
loop {
let line = match read_line(&mut reader, limits.max_line) {
Line::Text(t) => t,
Line::TooLong => {
let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("request line longer than {} bytes", limits.max_line)}));
close_politely(&out, &mut reader, limits.write_timeout);
break;
}
Line::Closed => break,
};
let reply = match parse(&line) {
Parsed::Blank => continue,
Parsed::Reject(e) => {
// The connection closes either way, but the peer is told why first: see
// `close_politely`, without which a peer that had pipelined another line had this
// reply reset away and saw nothing.
let _ = writeln!(out, "{}", json!({"ok": false, "error": e}));
close_politely(&out, &mut reader, limits.write_timeout);
break;
}
Parsed::Request { id, method, params } => {
for line in BufReader::new(read).lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let (req, rrx) = ControlRequest::new(method, params);
let state = Arc::clone(&req.state);
let mut r = match tx.try_send(req) {
Ok(()) => {
ctx.request_repaint();
match rrx.recv_timeout(limits.reply_timeout) {
Ok(v) => v,
Err(_) => {
// Give up on the request. While it was still queued this makes
// sure it never runs late (#719); if the app had already taken
// it, its outcome is unknown rather than a definite failure.
if ControlRequest::abandon(&state) {
json!({"ok": false, "error": "timeout"})
} else {
json!({"ok": false, "error": "timeout: the app had already started the request, so it may still run; its outcome is unknown"})
}
}
}
}
Err(TrySendError::Full(_)) => json!({"ok": false, "error": "busy: too many queued requests"}),
Err(TrySendError::Disconnected(_)) => break,
};
if tx.send(req).is_err() {
break;
}
ctx.request_repaint();
let mut r = rrx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
r
}
Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}),
};
if let Err(e) = writeln!(out, "{reply}") {
if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) {
log::debug!("control client stopped reading replies; closing");
}
if writeln!(out, "{reply}").is_err() {
break;
}
}
}
#[cfg(test)]
mod tests;
-299
View File
@@ -1,299 +0,0 @@
use super::*;
/// A failed accept is followed by a wait before the next one, so a listener that keeps
/// failing does not spin, and the connections around the failures still come through.
#[test]
fn a_failed_accept_waits_before_the_next() {
let failed = || Err(std::io::Error::other("no file descriptors left"));
let incoming = vec![failed(), Ok(1), failed(), failed(), Ok(2)];
let mut waits = 0;
let connections: Vec<i32> = super::accepted(incoming.into_iter(), || waits += 1).collect();
assert_eq!(connections, [1, 2]);
assert_eq!(waits, 3, "one wait per failed accept");
}
use std::net::SocketAddr;
use std::time::Instant;
fn small() -> Limits {
Limits {
max_clients: 2,
max_line: 64,
queue: 1,
idle_timeout: Duration::from_millis(300),
write_timeout: Duration::from_millis(300),
reply_timeout: Duration::from_millis(300),
}
}
fn server(limits: Limits) -> (SocketAddr, Receiver<ControlRequest>) {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = l.local_addr().unwrap();
(addr, serve_listener(l, limits, egui::Context::default()))
}
fn client(addr: SocketAddr) -> (BufReader<TcpStream>, TcpStream) {
let s = TcpStream::connect(addr).unwrap();
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
(BufReader::new(s.try_clone().unwrap()), s)
}
fn reply(r: &mut BufReader<TcpStream>) -> Option<Value> {
let mut s = String::new();
match r.read_line(&mut s) {
Ok(0) | Err(_) => None,
Ok(_) => serde_json::from_str(&s).ok(),
}
}
/// Answer every request with its method name until the server goes away.
fn ui(rx: Receiver<ControlRequest>) {
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
}
});
}
#[test]
fn request_round_trip() {
let (addr, rx) = server(small());
ui(rx);
let (mut r, mut w) = client(addr);
writeln!(w, r#"{{"id":7,"method":"ui.inspect"}}"#).unwrap();
let v = reply(&mut r).unwrap();
assert_eq!(v["id"], 7);
assert_eq!(v["result"], "ui.inspect");
}
/// Every reply line until the server closes the connection.
fn replies_until_closed(r: &mut BufReader<TcpStream>) -> Vec<Value> {
std::iter::from_fn(|| reply(r)).collect()
}
/// A browser can POST to the port: its request line closes the connection before the JSON
/// line in its body is read, so nothing is dispatched.
#[test]
fn an_http_request_closes_the_connection_before_its_body_is_dispatched() {
let (addr, rx) = server(Limits { max_line: 512, ..small() });
let (mut r, mut w) = client(addr);
w.write_all(
b"POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\n\r\n\
{\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"slide.new\"}}\n",
)
.unwrap();
let replies = replies_until_closed(&mut r);
assert_eq!(replies.len(), 1, "{replies:?}");
assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}");
assert!(rx.try_recv().is_err(), "the body was dispatched");
}
#[test]
fn a_line_that_is_not_a_request_closes_the_connection() {
let (addr, rx) = server(small());
ui(rx);
for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] {
let (mut r, mut w) = client(addr);
w.write_all(junk).unwrap();
w.write_all(b"{\"id\":2,\"method\":\"m\"}\n").unwrap();
let replies = replies_until_closed(&mut r);
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], false);
}
assert!(is_http_request_line("OPTIONS * HTTP/1.1"));
assert!(is_http_request_line("PRI * HTTP/2.0"));
assert!(!is_http_request_line("{\"method\":\"GET /\"}"));
}
/// A peer that pipelines -- two lines in one write, as a script does -- still reads why its
/// line was rejected. Closing with its second line unread resets the connection and discards
/// the reply already on its way, so the peer saw nothing at all; repeated here because it
/// depended on the timing of the two.
#[test]
fn a_pipelined_peer_still_reads_why_its_line_was_rejected() {
// A slot comes back only when the thread serving a peer ends, which can be after the next
// peer connects, so every peer has a slot of its own.
const PEERS: usize = 12;
let (addr, rx) = server(Limits { max_clients: PEERS, ..small() });
for _ in 0..PEERS {
let (mut r, mut w) = client(addr);
w.write_all(b"hello\n").unwrap();
// A second line, written after the first as a script writes it: it races the close.
let _ = w.write_all(b"{\"id\":2,\"method\":\"m\"}\n");
let replies = replies_until_closed(&mut r);
assert_eq!(replies.len(), 1, "{replies:?}");
assert_eq!(replies[0]["ok"], false);
assert!(replies[0]["error"].as_str().unwrap_or_default().contains("closing the connection"), "{replies:?}");
}
// The line after the rejected one is never dispatched, pipelined or not.
assert!(rx.try_recv().is_err(), "a line after the rejection was dispatched");
}
/// A peer refused because every connection is taken still reads why when it had already
/// written a line: closing with that line unread resets the connection and discards the
/// reply. Repeated because it depends on the timing of the two.
#[test]
fn a_pipelined_peer_refused_as_busy_still_reads_why() {
let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() });
ui(rx);
// Take the only slot, and make sure it is being served.
let (mut hr, mut hw) = client(addr);
writeln!(hw, r#"{{"id":1,"method":"m"}}"#).unwrap();
assert!(reply(&mut hr).is_some());
for _ in 0..50 {
let (mut r, mut w) = client(addr);
let _ = w.write_all(b"{\"id\":2,\"method\":\"m\"}\n");
let replies = replies_until_closed(&mut r);
assert_eq!(replies.len(), 1, "{replies:?}");
assert!(replies[0]["error"].as_str().unwrap_or_default().starts_with("busy"), "{replies:?}");
}
}
/// Peers refused as busy that stay connected without sending anything do not hold up the
/// connections after them: each one's drain runs to its deadline on a thread of its own, and
/// past `MAX_REFUSING` drains at once a refused connection is closed without one.
#[test]
fn silent_refused_peers_do_not_delay_the_next_refusal() {
let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() });
ui(rx);
let (mut hr, mut hw) = client(addr);
writeln!(hw, r#"{{"id":1,"method":"m"}}"#).unwrap();
assert!(reply(&mut hr).is_some());
// Twenty drains of 250 ms each, one after another, would take five seconds.
let silent: Vec<_> = (0..MAX_REFUSING + 4).map(|_| client(addr)).collect();
let start = Instant::now();
let (mut r, _w) = client(addr);
let refused = reply(&mut r).unwrap();
assert!(refused["error"].as_str().unwrap_or_default().starts_with("busy"), "{refused}");
assert!(start.elapsed() < Duration::from_secs(1), "refused after {:?}", start.elapsed());
drop(silent);
}
/// A peer that keeps its connection open after its line was rejected gives its slot back at
/// the drain deadline (the write timeout), not at the idle timeout.
#[test]
fn a_rejected_peer_that_stays_connected_frees_its_slot_at_the_deadline() {
let (addr, rx) = server(Limits { max_clients: 1, idle_timeout: Duration::from_secs(30), ..small() });
ui(rx);
let (mut r, mut w) = client(addr);
w.write_all(b"hello\n").unwrap();
assert_eq!(reply(&mut r).unwrap()["ok"], false);
// `w` stays open, sending nothing.
let deadline = Instant::now() + Duration::from_secs(4);
loop {
let (mut dr, mut dw) = client(addr);
writeln!(dw, r#"{{"id":2,"method":"m"}}"#).unwrap();
if reply(&mut dr).is_some_and(|v| v["ok"] == true) {
break;
}
assert!(Instant::now() < deadline, "slot never freed");
std::thread::sleep(Duration::from_millis(50));
}
drop(w);
}
#[test]
fn oversized_line_closes_connection() {
let (addr, rx) = server(small());
ui(rx);
let (mut r, mut w) = client(addr);
w.write_all(&[b'x'; 200]).unwrap();
let v = reply(&mut r).unwrap();
assert!(v["error"].as_str().unwrap().contains("longer than 64"));
assert!(reply(&mut r).is_none());
}
#[test]
fn idle_connection_is_closed() {
let (addr, rx) = server(small());
ui(rx);
let (mut r, mut w) = client(addr);
w.write_all(b"{\"id\":1,").unwrap(); // unterminated, then silence
let t = Instant::now();
assert!(reply(&mut r).is_none());
assert!(t.elapsed() < Duration::from_secs(4));
}
#[test]
fn connection_limit_refuses_then_frees_slot() {
// `a` sends nothing. Under a 300 ms idle timeout, a slow run could close it before the
// third peer connected, and that peer then took its slot instead of reading `busy`.
let (addr, rx) = server(Limits { idle_timeout: Duration::from_secs(30), ..small() });
ui(rx);
let a = client(addr);
let (mut br, mut bw) = client(addr);
// Make sure both are being served before the third arrives.
writeln!(bw, r#"{{"id":1,"method":"m"}}"#).unwrap();
assert!(reply(&mut br).is_some());
let (mut cr, _cw) = client(addr);
let v = reply(&mut cr).unwrap();
assert!(v["error"].as_str().unwrap().starts_with("busy"));
drop(a);
// The freed slot is reusable once the server notices the disconnect.
let deadline = Instant::now() + Duration::from_secs(4);
loop {
let (mut dr, mut dw) = client(addr);
writeln!(dw, r#"{{"id":2,"method":"m"}}"#).unwrap();
if reply(&mut dr).is_some_and(|v| v["ok"] == true) {
break;
}
assert!(Instant::now() < deadline, "slot never freed");
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
fn blocked_ui_times_out_and_full_queue_is_busy() {
let (addr, rx) = server(small());
// No UI: the request that reaches the one-slot queue first fills it and times out; the
// other finds it full. Each connection has its own thread, so either request can be first.
let (mut ar, mut aw) = client(addr);
let (mut br, mut bw) = client(addr);
writeln!(aw, r#"{{"id":1,"method":"m"}}"#).unwrap();
writeln!(bw, r#"{{"id":2,"method":"m"}}"#).unwrap();
let a = reply(&mut ar).unwrap();
let b = reply(&mut br).unwrap();
assert_eq!((&a["id"], &b["id"]), (&json!(1), &json!(2)));
let mut errors = [a["error"].as_str().unwrap_or_default(), b["error"].as_str().unwrap_or_default()];
errors.sort_unstable();
assert_eq!(errors, ["busy: too many queued requests", "timeout"], "{a} {b}");
drop(rx);
}
/// A request that timed out while it was still queued must not run when the window resumes (#719).
#[test]
fn timed_out_request_does_not_run_when_the_window_resumes() {
let (addr, rx) = server(Limits { max_line: 512, ..small() });
let (mut r, mut w) = client(addr);
writeln!(w, r#"{{"id":1,"method":"engine.execute","params":{{"command":"slide.new"}}}}"#).unwrap();
let t = reply(&mut r).unwrap();
assert_eq!(t["error"], "timeout");
// The window resumes and drains the queue, exactly as `SlideApp::drain_control` does.
let mut app = deckcraft_ui_egui::SlideApp::new(deckcraft_engine::Session::with_new(), deckcraft_ui_egui::Services::default());
let ctx = egui::Context::default();
let before = app.session.active().unwrap().doc.slides.len();
let req = rx.try_recv().expect("the timed-out request is still queued");
if req.take() {
let _ = deckcraft_ui_egui::control::handle(&mut app, &ctx, &req);
}
assert_eq!(app.session.active().unwrap().doc.slides.len(), before, "a request that timed out must not run when the window resumes");
drop(rx);
}
/// A request the app had already started when the reply timed out reports an unknown outcome,
/// not a definite failure (#719).
#[test]
fn a_request_already_started_when_the_reply_times_out_reports_an_unknown_outcome() {
let (addr, rx) = server(small());
let ui = std::thread::spawn(move || {
let req = rx.recv().expect("the request is queued");
assert!(req.take(), "the app claims the request");
// Still running it when the sender's wait expires.
std::thread::sleep(Duration::from_millis(450));
let _ = req.reply.send(json!({"ok": true, "result": "ran"}));
});
let (mut r, mut w) = client(addr);
writeln!(w, r#"{{"id":1,"method":"m"}}"#).unwrap();
let v = reply(&mut r).unwrap();
assert!(v["error"].as_str().unwrap().contains("outcome is unknown"), "{v}");
ui.join().unwrap();
}
-85
View File
@@ -1,85 +0,0 @@
//! Which windowing system to start on, on Linux and the BSDs.
//!
//! DeckCraft prefers X11 when `DISPLAY` is set (see `main`). A stale `DISPLAY` (left over from
//! an ended `ssh -X` session or a desktop with Xwayland turned off) used to make start-up fail
//! with winit's "failed to open display" even though a Wayland compositor was running. When a
//! local `DISPLAY` names an X server whose socket isn't there and Wayland is available, start on
//! Wayland instead. With no display at all, say so plainly.
use std::path::Path;
/// The windowing system to ask winit for.
#[derive(Debug, PartialEq, Eq)]
pub enum Choice {
X11,
/// Let winit decide (Wayland when `WAYLAND_DISPLAY` is set).
Default,
/// Neither `DISPLAY` nor `WAYLAND_DISPLAY`: there is nothing to open a window on.
None,
}
/// The X server number of a local `DISPLAY` (`:1`, `:1.0`, `unix:1`); `None` for a remote one
/// (`host:10.0`, as `ssh -X` sets) or one we can't read, which are left to X11 itself.
fn local_display_number(display: &str) -> Option<u32> {
let rest = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?;
rest.split('.').next()?.parse().ok()
}
/// Choose from the environment. `socket_exists` checks an X socket path (the filesystem in
/// [`choose_from_env`], a stub in tests).
pub fn choose(display: Option<&str>, wayland: Option<&str>, force_wayland: bool, socket_exists: impl Fn(&Path) -> bool) -> Choice {
let display = display.filter(|d| !d.is_empty());
let wayland = wayland.is_some_and(|w| !w.is_empty());
match display {
None if wayland => Choice::Default,
None => Choice::None,
Some(_) if force_wayland && wayland => Choice::Default,
Some(d) => match local_display_number(d) {
Some(n) if wayland && !socket_exists(&Path::new("/tmp/.X11-unix").join(format!("X{n}"))) => {
log::warn!("DISPLAY={d} has no X server; starting on Wayland");
Choice::Default
}
_ => Choice::X11,
},
}
}
/// [`choose`] for this process.
pub fn choose_from_env() -> Choice {
let display = std::env::var("DISPLAY").ok();
let wayland = std::env::var("WAYLAND_DISPLAY").ok();
choose(display.as_deref(), wayland.as_deref(), std::env::var_os("DECKCRAFT_WAYLAND").is_some(), |p| p.exists())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_stale_local_display_falls_back_to_wayland() {
let none = |_: &Path| false;
let all = |_: &Path| true;
assert_eq!(choose(Some(":1"), Some("wayland-0"), false, none), Choice::Default);
assert_eq!(choose(Some(":1.0"), Some("wayland-0"), false, none), Choice::Default);
assert_eq!(choose(Some("unix:0"), Some("wayland-0"), false, none), Choice::Default);
// A live X server, no Wayland, or a remote DISPLAY: X11 as before.
assert_eq!(choose(Some(":1"), Some("wayland-0"), false, all), Choice::X11);
assert_eq!(choose(Some(":1"), None, false, none), Choice::X11);
assert_eq!(choose(Some("host:10.0"), Some("wayland-0"), false, none), Choice::X11);
// The socket checked is the display's own.
assert_eq!(choose(Some(":3"), Some("w"), false, |p: &Path| p.ends_with("X3")), Choice::X11);
assert_eq!(choose(Some(":3"), Some("w"), false, |p: &Path| p.ends_with("X0")), Choice::Default);
}
#[test]
fn wayland_only_forced_and_no_display_at_all() {
let all = |_: &Path| true;
assert_eq!(choose(None, Some("wayland-0"), false, all), Choice::Default);
assert_eq!(choose(Some(""), Some("wayland-0"), false, all), Choice::Default);
assert_eq!(choose(Some(":0"), Some("wayland-0"), true, all), Choice::Default);
// Forcing Wayland without a compositor keeps X11 rather than failing.
assert_eq!(choose(Some(":0"), None, true, all), Choice::X11);
assert_eq!(choose(None, None, false, all), Choice::None);
assert_eq!(choose(Some(""), Some(""), false, all), Choice::None);
}
}
+5 -51
View File
@@ -1,14 +1,10 @@
//! Windows graphics instance configuration, applied before wgpu can initialize any driver.
use eframe::{
NativeOptions,
egui_wgpu::WgpuSetup,
wgpu::{Backends, Dx12Compiler},
};
use eframe::{NativeOptions, egui_wgpu::WgpuSetup, wgpu::Backends};
/// Default to DirectX 12 with FXC before creating the wgpu instance. Explicit
/// `WGPU_BACKEND` and `WGPU_DX12_COMPILER` choices, read by the caller, take precedence.
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>, compiler_override: Option<Dx12Compiler>) {
/// Restrict the wgpu instance to DirectX 12 unless `backend_override` (normally
/// `Backends::from_env()`, i.e. `WGPU_BACKEND`) names other backends.
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>) {
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
// eframe's default includes GL. Creating that backend can crash inside AMD's
// atio6axx.dll before adapter selection or any Rust error handling runs, so the
@@ -16,16 +12,6 @@ pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>
// out of the instance avoids it. This matches the verified WGPU_BACKEND=dx12
// workaround without mutating process environment variables.
create.instance_descriptor.backends = backend_override.unwrap_or(Backends::DX12);
// Auto loads whichever dxcompiler.dll the DLL search path finds; DeckCraft ships
// none, and without a matching dxil.dll the unsigned-DXIL warning fails wgpu's
// indirect-validation pipeline and loses the device before the first frame
// (issue #153). FXC uses the compiler that is part of Windows.
create.instance_descriptor.backend_options.dx12.shader_compiler = compiler_override.unwrap_or(Dx12Compiler::Fxc);
log::info!(
"Windows graphics: backends={:?}, DX12 compiler={:?}",
create.instance_descriptor.backends,
create.instance_descriptor.backend_options.dx12.shader_compiler
);
}
}
@@ -35,7 +21,7 @@ mod tests {
fn configured_backends(backend_override: Option<Backends>) -> Backends {
let mut options = NativeOptions::default();
configure(&mut options, backend_override, None);
configure(&mut options, backend_override);
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
@@ -52,38 +38,6 @@ mod tests {
assert_eq!(configured_backends(None), Backends::DX12);
}
#[test]
fn windows_default_uses_fxc_instead_of_searching_for_dxc() {
let mut options = NativeOptions::default();
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
// Auto can find an unrelated DXC without its matching DXIL runtime (issue #153).
create.instance_descriptor.backend_options.dx12.shader_compiler = Dx12Compiler::Auto;
}
configure(&mut options, None, None);
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
assert!(matches!(create.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Fxc));
}
#[test]
fn explicit_compiler_override_is_preserved() {
for compiler in [Dx12Compiler::Fxc, Dx12Compiler::Auto, Dx12Compiler::DynamicDxc { dxc_path: "custom/dxcompiler.dll".into() }] {
let mut options = NativeOptions::default();
configure(&mut options, None, Some(compiler.clone()));
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
match (compiler, create.instance_descriptor.backend_options.dx12.shader_compiler) {
(Dx12Compiler::Fxc, Dx12Compiler::Fxc) | (Dx12Compiler::Auto, Dx12Compiler::Auto) => {}
(Dx12Compiler::DynamicDxc { dxc_path: expected }, Dx12Compiler::DynamicDxc { dxc_path: actual }) => {
assert_eq!(actual, expected);
}
(expected, actual) => panic!("compiler override changed from {expected:?} to {actual:?}"),
}
}
}
#[test]
fn explicit_backend_override_is_preserved() {
for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] {
+22 -56
View File
@@ -95,35 +95,29 @@ fn matches(name: &str, target: &str) -> bool {
}
}
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch; a clock
/// set absurdly far ahead keeps its real year (years far outside chrono's own range are preserved)
/// instead of panicking.
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch.
pub fn timestamp(t: SystemTime) -> String {
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
let (y, dt) = utc_parts(since.as_secs(), since.subsec_nanos());
// `{:04}` rather than `%Y`, which writes a `+` before years past 9999.
format!("{y:04}-{}", dt.format("%m-%dT%H:%M:%S%.3fZ"))
let secs = since.as_secs();
let (days, rem) = (secs / 86_400, secs % 86_400);
let (y, m, d) = civil_from_days(days);
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
}
/// Unix seconds (+ nanos) → (proleptic Gregorian year, the same wall-clock instant moved into
/// chrono's range by whole 400-year cycles). The Gregorian calendar repeats every 400 years
/// (146_097 days), so month, day and time of day come from chrono and only the year is carried,
/// which keeps every input exact instead of collapsing out-of-range years to the epoch. `secs` is
/// `u64` (the clock is clamped at the epoch before 1970), so `days` always fits an `i64`.
fn utc_parts(secs: u64, nanos: u32) -> (i64, chrono::NaiveDateTime) {
use chrono::Datelike;
let (days, sod) = ((secs / 86_400) as i64, (secs % 86_400) as i64);
let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
// `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400.
let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt);
let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999)));
match (date, time) {
(Some(d), Some(t)) => {
let y = i128::from(d.year()) + i128::from(cycles) * 400;
(i64::try_from(y).unwrap_or(i64::MAX), d.and_time(t))
}
_ => (1970, chrono::NaiveDateTime::default()), // unreachable
}
/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's
/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch; saturating so an absurd
/// clock can't overflow).
fn civil_from_days(days: u64) -> (u64, u64, u64) {
let z = days.saturating_add(719_468);
let era = z / 146_097;
let doe = z % 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = era.saturating_mul(400).saturating_add(yoe).saturating_add(u64::from(m <= 2));
(y, m, d)
}
fn numbered(dir: &Path, n: usize) -> PathBuf {
@@ -148,19 +142,7 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
let message = message.strip_suffix('\n').unwrap_or(message);
// Messages can embed document-controlled text (a part name, a relationship id): control
// characters other than tab are escaped and each continuation line is marked, so such text
// cannot start a line that looks like a record of its own.
let mut text = String::with_capacity(message.len());
for c in message.chars() {
match c {
'\n' => text.push_str("\n | "),
'\t' => text.push(c),
c if c.is_control() => text.extend(c.escape_default()),
c => text.push(c),
}
}
format!("{ts} {level:<5} [{thread}] {target}: {text}\n")
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
}
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
@@ -407,17 +389,6 @@ mod tests {
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
// Before the epoch (a clock set wrong) clamps instead of panicking.
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
// A clock set absurdly far ahead (past chrono's own range) keeps its real year rather than
// collapsing to the epoch. Windows' SystemTime can't hold such an instant, so it is built
// with a checked add and only asserted where it exists.
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
}
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
}
// Years past 9999 keep the plain zero-padded year (no `+`).
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
}
#[test]
@@ -458,13 +429,8 @@ mod tests {
),
"2026-10-08T07:59:17.728Z WARN [main] deckcraft_pptx::opc: pptx: skipping oversized part ppt/media/image1.png\n"
);
// A multi-line message keeps its lines, each continuation marked; the record still ends in
// exactly one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n | b\n"));
// Injected line breaks and escape sequences cannot forge a record.
let line = format_line("t", log::Level::Warn, "w", "x", "part a\r\n2026 ERROR [m] y: forged\x1b[2J");
assert_eq!(line.matches('\n').count(), 2);
assert!(!line.contains('\r') && !line.contains('\x1b'));
// A multi-line message keeps its lines; the record still ends in exactly one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
}
#[test]
+57 -332
View File
@@ -1,8 +1,6 @@
//! DeckCraft desktop app.
//!
//! Usage: `deckcraft [--control <port>] [--sample] [--show] [files…]`
//! A PowerPoint Show (`.ppsx`) given last starts its slide show, as a double-click does in PowerPoint.
//! `deckcraft --help` prints the flags and exits. `deckcraft --version` prints the version and exits.
//!
//! `--control <port>` (or `DECKCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
//! `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`.
@@ -14,58 +12,29 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(target_os = "macos")]
mod apple_events;
mod audio;
mod control_server;
#[cfg(all(unix, not(target_os = "macos")))]
mod display;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod logging;
#[cfg(not(target_arch = "wasm32"))]
mod pasteboard;
use deckcraft_engine::Session;
use deckcraft_ui_egui::{Services, SlideApp};
struct App(
SlideApp,
/// Files opened from Finder and quit requests (see `apple_events`).
#[cfg(target_os = "macos")]
fmv_macos_events::Inbox,
);
struct App(SlideApp);
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
apple_events::poll(&self.1, &mut self.0, ctx);
self.0.logic(ctx);
}
/// Forward native raw input to the wrapped application once per pass.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(raw);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.ui(ui);
}
fn on_exit(&mut self) {
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.
self.0.start_pending_update();
// macOS (#279): end the process here, before eframe tears the window down. AccessKit's
// macOS adapter subclasses the window's content view and restores its class on teardown;
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
// `-[_NSTouchBarFinderObservation invalidate]` throws "not registered" and the quit ends
// in a crash report. eframe calls `on_exit` on every way of quitting (⌘Q, the close
// button, `app.quit`), once the unsaved-changes prompt has let the window close, and
// nothing after it is needed: the preferences are saved and the log file is unbuffered.
// `on_exit` only runs once the app exists, never on a failed start. Same as GridCraft #117.
#[cfg(target_os = "macos")]
self.0.cleanup_print_previews();
#[cfg(target_os = "macos")]
std::process::exit(0);
}
}
@@ -83,16 +52,24 @@ fn config_dir() -> Option<std::path::PathBuf> {
}
}
fn prefs_path() -> Option<std::path::PathBuf> {
config_dir().map(|b| b.join("ui.json"))
}
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 (ui, prefs) = deckcraft_ui_egui::settings::load(&dir);
if let Some(ui) = ui {
if let Some(p) = prefs_path()
&& let Ok(bytes) = std::fs::read(&p)
&& let Ok(ui) = serde_json::from_slice::<deckcraft_ui_egui::UiState>(&bytes)
{
app.ui = ui;
}
if let Some(prefs) = prefs {
if let Some(p) = prefs_path().map(|p| p.with_file_name("prefs.json"))
&& let Ok(bytes) = std::fs::read(&p)
&& let Ok(prefs) = serde_json::from_slice::<deckcraft_engine::Prefs>(&bytes)
{
app.session.prefs = prefs;
}
}
@@ -101,18 +78,18 @@ fn save_prefs(app: &SlideApp) {
if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() {
return;
}
if let Some(dir) = config_dir() {
deckcraft_ui_egui::settings::save(&dir, &app.ui, &app.session.prefs);
if let Some(p) = prefs_path() {
let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));
if let Ok(bytes) = serde_json::to_vec_pretty(&app.ui) {
let _ = std::fs::write(&p, bytes);
}
if let Ok(bytes) = serde_json::to_vec_pretty(&app.session.prefs) {
let _ = std::fs::write(p.with_file_name("prefs.json"), bytes);
}
}
}
/// The desktop services. `native_wayland`: the window is a Wayland client (not Xwayland).
fn services(native_wayland: bool) -> Services {
// On native Wayland, egui-winit owns the clipboard through winit's data device, which carries
// text and PNG but no HTML. `pasteboard` (arboard, built for X11 only) would put a copy on the
// Xwayland selection instead and skip egui's Wayland claim, so Ctrl+V would read something
// else. There, text goes through egui and pictures arrive as `PasteImage` events.
let pasteboard = !native_wayland;
fn services() -> Services {
Services {
pick_open: Some(Box::new(|purpose: &str| {
let d = rfd::FileDialog::new();
@@ -123,7 +100,6 @@ fn services(native_wayland: bool) -> Services {
&["wav", "mp3", "m4a", "m4b", "aac", "flac", "ogg", "oga", "opus", "aif", "aiff", "aifc", "caf", "wma", "weba", "mka"],
),
"video" => d.add_filter("Video", &["mp4", "m4v", "mov", "webm", "mkv", "wmv"]),
"theme" => d.add_filter("Themes and presentations", &["thmx", "pptx", "potx", "ppsx"]).add_filter("Office Theme", &["thmx"]),
_ => d
.add_filter("Presentations", &["deckcraft", "pptx", "potx", "ppsx"])
.add_filter("DeckCraft", &["deckcraft"])
@@ -135,9 +111,14 @@ fn services(native_wayland: bool) -> Services {
pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))),
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
clipboard_image: pasteboard.then(|| Box::new(pasteboard::image_png) as Box<dyn FnMut() -> Option<Vec<u8>>>),
clipboard_html: pasteboard.then(|| Box::new(pasteboard::html) as Box<dyn FnMut() -> Option<String>>),
clipboard_set_html: pasteboard.then(|| Box::new(pasteboard::set_html) as Box<dyn FnMut(&str, &str) -> bool>),
clipboard_image: Some(Box::new(|| {
let mut cb = arboard::Clipboard::new().ok()?;
let img = cb.get_image().ok()?;
let rgba = image::RgbaImage::from_raw(img.width as u32, img.height as u32, img.bytes.into_owned())?;
let mut out = Vec::new();
rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?;
Some(out)
})),
// Media is mixed and clocked by the output device; `DECKCRAFT_NO_AUDIO` plays silently.
audio_out: std::env::var_os("DECKCRAFT_NO_AUDIO")
.is_none()
@@ -146,88 +127,37 @@ fn services(native_wayland: bool) -> Services {
}
}
/// Displays winit lists for `window`, counting an output Wayland lists twice once. `None` when it
/// lists none: Presenter View then stays as it was.
#[cfg(all(unix, not(target_os = "macos")))]
fn display_count(window: &winit::window::Window) -> Option<usize> {
let n = window.available_monitors().collect::<std::collections::BTreeSet<_>>().len();
(n > 0).then_some(n)
}
const APP_ID: &str = "ai.storyteller.deckcraft";
const USAGE: &str = "\
Usage: deckcraft [--control PORT] [--sample] [--show] [FILE...]
--control PORT JSON control server on 127.0.0.1:PORT
--sample open the sample presentation
--show start the slide show
--help, -h print this help and exit
--version, -V print the version and exit
A PowerPoint Show (.ppsx) given last starts its slide show.
";
enum Startup {
Help,
Version,
Run { control_port: Option<u16>, files: Vec<String>, sample: bool, show: bool },
}
/// `--help` and `--version` leave before the window and the log file.
fn startup(mut control_port: Option<u16>, args: impl IntoIterator<Item = String>) -> Startup {
let mut files = Vec::new();
let mut sample = false;
let mut show = false;
let mut args = args.into_iter();
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--sample" => sample = true,
"--show" => show = true,
"--version" | "-V" => return Startup::Version,
"--help" | "-h" => return Startup::Help,
// The process serial number older macOS adds when Finder launches the app.
a if a.starts_with("-psn_") => {}
_ => files.push(a),
}
}
Startup::Run { control_port, files, sample, show }
}
fn app_icon() -> Option<egui::IconData> {
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()
}
/// Install logging, parse startup arguments and environment, launch the native app, and
/// propagate an eframe startup failure.
fn main() -> eframe::Result {
// 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<_>>()) {
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 => {
let mut control_port: Option<u16> = std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut sample = false;
let mut show = false;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--sample" => sample = true,
"--show" => show = true,
"--version" => {
println!("deckcraft {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show),
};
_ => files.push(a),
}
}
log::info!("DeckCraft {} ({} {})", env!("CARGO_PKG_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.
// The log file lives under the settings directory; opened after the arguments, so `--version`
// leaves 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))) {
Some(Ok(path)) => log::info!("log file {}", path.display()),
@@ -254,50 +184,21 @@ fn main() -> eframe::Result {
options.viewport = options.viewport.with_icon(icon);
}
#[cfg(all(unix, not(target_os = "macos")))]
let x11 = match display::choose_from_env() {
display::Choice::X11 => true,
display::Choice::Default => false,
display::Choice::None => {
// winit's own error says little to someone who started DeckCraft from a console.
log::error!("no display: DISPLAY and WAYLAND_DISPLAY are not set");
eprintln!("DeckCraft needs a graphical session: neither DISPLAY nor WAYLAND_DISPLAY is set.");
false
}
};
// `Default` lets winit choose, and winit takes Wayland whenever `WAYLAND_DISPLAY` is set.
#[cfg(all(unix, not(target_os = "macos")))]
let native_wayland = !x11 && std::env::var_os("WAYLAND_DISPLAY").is_some_and(|w| !w.is_empty());
#[cfg(not(all(unix, not(target_os = "macos"))))]
let native_wayland = false;
#[cfg(all(unix, not(target_os = "macos")))]
if x11 {
if std::env::var_os("DISPLAY").is_some() && std::env::var_os("DECKCRAFT_WAYLAND").is_none() {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
// Before eframe creates the wgpu instance: default Windows to DirectX 12 only (see graphics.rs).
#[cfg(target_os = "windows")]
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
graphics::configure(&mut options, eframe::wgpu::Backends::from_env());
eframe::run_native(
"DeckCraft",
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));
// 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)));
}
let mut app = SlideApp::new(Session::new(), services());
load_prefs(&mut app);
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();
@@ -315,191 +216,15 @@ fn main() -> eframe::Result {
if sample && let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) {
log::error!("sample: {e}");
}
// A .ppsx opened last starts its slide show (#862).
for (f, e) in app.open_from_system(&files) {
log::error!("{f}: {e}");
for f in files {
if let Err(e) = app.open_path(&f) {
log::error!("{f}: {e}");
}
}
if show {
app.start_show(0, false);
}
Ok(Box::new(App(
app,
#[cfg(target_os = "macos")]
apple_events.connect(&cc.egui_ctx),
)))
Ok(Box::new(App(app)))
}),
)
}
#[cfg(test)]
mod tests {
use super::*;
/// #279: on macOS the process ends inside `on_exit`, before eframe would tear the window down.
/// The check runs in a child (this test binary again), since on macOS it ends the process.
#[test]
fn on_exit_ends_the_process_on_macos() {
if std::env::var_os("DECKCRAFT_TEST_ON_EXIT").is_some() {
let mut app = App(
SlideApp::new(Session::new(), Services::default()),
#[cfg(target_os = "macos")]
fmv_macos_events::Inbox::default(),
);
println!("calling on_exit");
eframe::App::on_exit(&mut app);
println!("on_exit returned");
return;
}
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::on_exit_ends_the_process_on_macos", "--nocapture"])
.env("DECKCRAFT_TEST_ON_EXIT", "1")
.env("DECKCRAFT_NO_PREFS", "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{stdout}");
assert!(stdout.contains("calling on_exit"), "the child didn't run the test: {stdout}");
assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}");
}
/// The egui 0.37 migration (#1350) left `clipboard` out of eframe's features. egui then
/// simulated a clipboard inside the app: nothing pasted from other apps, and Ctrl+C/Ctrl+V
/// lost text that went out as HTML. Keep the OS clipboard on.
#[test]
fn eframe_uses_the_os_clipboard() {
let manifest = include_str!("../Cargo.toml");
let eframe = manifest.lines().find(|l| l.starts_with("eframe = ")).unwrap_or_default();
assert!(eframe.contains("\"clipboard\""), "eframe must enable the OS clipboard: {eframe}");
}
/// On native Wayland, the X11-only pasteboard would bypass egui's Wayland clipboard; elsewhere
/// it carries HTML and pictures beside egui's text.
#[test]
fn the_pasteboard_stays_off_native_wayland() {
let s = services(true);
assert!(s.clipboard_html.is_none() && s.clipboard_set_html.is_none() && s.clipboard_image.is_none());
let s = services(false);
assert!(s.clipboard_html.is_some() && s.clipboard_set_html.is_some() && s.clipboard_image.is_some());
}
#[test]
fn help_exits_instead_of_opening_a_file() {
assert!(matches!(startup(None, ["--help".to_string()]), Startup::Help));
assert!(matches!(startup(None, ["-h".to_string()]), Startup::Help));
assert!(matches!(startup(None, ["talk.pptx".to_string(), "--help".to_string()]), Startup::Help));
assert!(matches!(startup(None, ["--version".to_string()]), Startup::Version));
let launch = startup(Some(9), ["--sample".to_string(), "--control".to_string(), "4242".to_string(), "talk.pptx".to_string()]);
assert!(matches!(launch, Startup::Run { .. }));
if let Startup::Run { control_port, files, sample, show } = launch {
assert_eq!(control_port, Some(4242));
assert_eq!(files, ["talk.pptx".to_string()]);
assert!(sample);
assert!(!show);
}
}
#[test]
fn finder_process_serial_number_is_not_a_file() {
let launch = startup(None, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]);
assert!(matches!(launch, Startup::Run { .. }));
if let Startup::Run { files, .. } = launch {
assert_eq!(files, ["talk.pptx".to_string()]);
}
}
/// The `<string>` values of every `<array>` that follows a `<key>{key}</key>` line.
fn plist_strings(plist: &str, key: &str) -> Vec<String> {
let mut out = Vec::new();
let mut in_array = false;
for line in plist.lines() {
let line = line.trim();
if line == format!("<key>{key}</key>") {
in_array = true;
continue;
}
if in_array {
for part in line.split("<string>").skip(1) {
if let Some((s, _)) = part.split_once("</string>") {
out.push(s.to_string());
}
}
if line.ends_with("</array>") {
in_array = false;
}
}
}
out
}
/// Every desktop offers the same file types: macOS (`CFBundleTypeExtensions` and the native
/// type's extension in `Info.plist.in`), Windows (`SupportedTypes` in `deckcraft.wxs`) and
/// Linux (`MimeType` in the desktop file). A format added to one installer must reach the
/// others, and each must be one Finder, Explorer or the file manager can hand to DeckCraft.
#[test]
fn every_desktop_offers_the_same_file_types() {
let plist = include_str!("../../../packaging/macos/Info.plist.in");
let wxs = include_str!("../../../packaging/windows/deckcraft.wxs");
let desktop = include_str!("../../../packaging/linux/ai.storyteller.deckcraft.desktop");
let mut mac = plist_strings(plist, "CFBundleTypeExtensions");
// The native type is declared by its UTI; its extension is in the exported type.
mac.extend(plist_strings(plist, "public.filename-extension").into_iter().filter(|e| e == "deckcraft"));
mac.sort();
mac.dedup();
assert!(mac.iter().any(|e| e == "pptx") && mac.iter().any(|e| e == "deckcraft"), "Info.plist.in: {mac:?}");
// Every document type names a content type too, so "Change All" in Finder's Get Info works.
let names = plist.matches("<key>CFBundleTypeName</key>").count();
let content_types = plist.matches("<key>LSItemContentTypes</key>").count();
assert!(names > 0 && names == content_types, "{names} document types, {content_types} with LSItemContentTypes");
let mut win: Vec<String> = wxs
.lines()
.filter(|l| l.contains("SupportedTypes\" Name=\"."))
.filter_map(|l| l.split("Name=\".").nth(1)?.split('"').next().map(str::to_string))
.collect();
win.sort();
let mime_ext = |m: &str| match m {
"application/x-deckcraft" => Some("deckcraft"),
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => Some("pptx"),
"application/vnd.openxmlformats-officedocument.presentationml.template" => Some("potx"),
"application/vnd.openxmlformats-officedocument.presentationml.slideshow" => Some("ppsx"),
_ => None,
};
let mut linux: Vec<String> = desktop
.lines()
.find_map(|l| l.strip_prefix("MimeType="))
.unwrap_or_default()
.split(';')
.filter(|m| !m.is_empty())
.map(|m| mime_ext(m).unwrap_or(m).to_string()) // an unknown MIME type shows up in the diff
.collect();
linux.sort();
assert_eq!(mac, win, "macOS and Windows offer different file types");
assert_eq!(mac, linux, "macOS and Linux offer different file types");
}
/// #1114: a shortcut that names an MSI `<Icon>` shows a blank icon once an update deletes the
/// cached copy of it, and a taskbar pin (a copy of the shortcut) is never repaired. Shortcuts
/// take the icon embedded in `deckcraft.exe`; only `ARPPRODUCTICON` uses the MSI `<Icon>`.
#[test]
fn windows_shortcuts_use_the_icon_embedded_in_the_exe() {
let wxs = include_str!("../../../packaging/windows/deckcraft.wxs");
let shortcuts: Vec<&str> = wxs.split("<Shortcut").skip(1).filter_map(|s| s.split("/>").next()).collect();
assert!(!shortcuts.is_empty(), "deckcraft.wxs has no shortcut");
for shortcut in shortcuts {
assert!(!shortcut.contains("Icon="), "a shortcut names an MSI <Icon>:{shortcut}");
}
assert!(wxs.contains("<Property Id=\"ARPPRODUCTICON\""), "Apps and features keeps its icon");
}
/// The shortcuts take the exe's own icon, and `package.ps1 -SkipBuild` packages an existing
/// exe without `DECKCRAFT_REQUIRE_WINRES`, so the script has to refuse one with no icon.
#[test]
fn the_windows_package_script_rejects_an_exe_without_an_icon() {
let script = include_str!("../../../packaging/windows/package.ps1");
assert!(script.contains("ExtractIconEx"), "package.ps1 does not count the exe's icons");
assert!(script.contains("has no embedded icon"), "package.ps1 does not reject an iconless exe");
}
}
-77
View File
@@ -1,77 +0,0 @@
//! System pasteboard: HTML rich text, and a picture (TIFF on macOS, via arboard).
//!
//! Pages keeps bold, italic and underline when the pasteboard carries HTML plus the same plain
//! words. A shape with no text is copied as an image by the UI; this module only reads a picture
//! back (Keynote's TIFF) as PNG bytes.
/// HTML currently on the pasteboard, when there is some.
pub fn html() -> Option<String> {
let mut cb = arboard::Clipboard::new().ok()?;
let html = cb.get().html().ok()?;
let html = html.trim();
if html.is_empty() { None } else { Some(html.to_string()) }
}
/// Write `html` and the plain alternative `text`. `false` when the pasteboard refuses it.
pub fn set_html(html: &str, text: &str) -> bool {
let Ok(mut cb) = arboard::Clipboard::new() else { return false };
cb.set_html(html, Some(text)).is_ok()
}
/// The pasteboard picture as PNG bytes (TIFF on macOS is decoded by arboard).
pub fn image_png() -> Option<Vec<u8>> {
let mut cb = arboard::Clipboard::new().ok()?;
let img = cb.get_image().ok()?;
let width = u32::try_from(img.width).ok()?;
let height = u32::try_from(img.height).ok()?;
let rgba = image::RgbaImage::from_raw(width, height, img.bytes.into_owned())?;
let mut out = Vec::new();
rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?;
Some(out)
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
/// Puts HTML and a 1×1 picture on the macOS pasteboard and reads them back.
/// Restores whatever plain text was there. Other platforms return immediately.
#[test]
fn html_and_a_picture_round_trip_on_macos() {
if !cfg!(target_os = "macos") {
return;
}
let previous = arboard::Clipboard::new().ok().and_then(|mut cb| cb.get_text().ok());
let _restore = Restore(previous);
assert!(super::set_html("<b>DeckCraft</b>", "DeckCraft"), "set html");
let html = super::html().unwrap_or_default();
assert!(html.contains("<b>") || html.contains("<B>"), "{html}");
let text = arboard::Clipboard::new().ok().and_then(|mut cb| cb.get_text().ok()).unwrap_or_default();
assert_eq!(text, "DeckCraft");
let mut cb = arboard::Clipboard::new().expect("pasteboard");
let img = arboard::ImageData { width: 1, height: 1, bytes: Cow::Owned(vec![255, 0, 0, 255]) };
cb.set_image(img).expect("set image");
drop(cb);
let png = super::image_png().expect("png");
let decoded = image::load_from_memory(&png).expect("decode").to_rgba8();
let p = decoded.get_pixel(0, 0);
assert!(p[0] > 200 && p[1] < 40 && p[3] > 200, "{p:?}");
}
/// Puts the previous plain text back, including when the test fails halfway.
struct Restore(Option<String>);
impl Drop for Restore {
fn drop(&mut self) {
let Ok(mut cb) = arboard::Clipboard::new() else { return };
match self.0.take() {
Some(t) => {
let _ = cb.set_text(t);
}
None => {
let _ = cb.clear();
}
}
}
}
}
-4
View File
@@ -2,7 +2,3 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+5 -37
View File
@@ -1,10 +1,13 @@
# Contributor names for the About window.
# Contributor names for the About window (craftrules standards/contributors.md).
#
# Everyone who contributes is credited by GitHub username automatically. Anything more is up to
# you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a
# maintainer may add a person only when that person asked, recording where in consent_source.
#
# Copy this block, replacing your-github-username (every field is optional):
# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \
# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name]
#
# Or copy this block, replacing your-github-username (every field is optional):
#
# [people.your-github-username]
# real_name = "Your Name" # shown when the viewer picks "Real name"
@@ -38,38 +41,3 @@ sync_github_name = true
[people.Silvertree2010]
display_name = "Netter"
sync_github_name = false
[people.dotCooCoo]
real_name = "Robert Lee"
sync_github_name = true
[people.Momentum96]
sync_github_name = true
[people.NikitkaRa]
real_name = "Nikita Rakitin"
[people.RCShoemaker]
real_name = "Ryan C. Shoemaker"
[people.marcoarnulfo]
real_name = "Marco Arnulfo"
display_name = "Marco Arnulfo"
sync_github_name = false
[people.GhostMitra]
sync_github_name = true
[people.Katacc]
sync_github_name = true
[people.SofiaAFigueredo]
real_name = "Sofia Alves Figueredo"
[people.dylanmtaylor]
sync_github_name = true
[people.marshiyar]
display_name = "Arshiya"
real_name = "Arshiya Rahgozar"
sync_github_name = false
-10
View File
@@ -44,15 +44,6 @@ pub(crate) fn exit_base(effect: &str) -> &str {
"swivelOut" => "swivel",
"bounceOut" => "bounce",
"dissolveOut" => "dissolve",
"blindsOut" => "blinds",
"boxOut" => "box",
"checkerboardOut" => "checkerboard",
"diamondOut" => "diamond",
"peekOut" => "peek",
"stripsOut" => "strips",
"sinkDown" => "rise",
"spinnerOut" => "spinner",
"contract" => "expand",
other => other,
}
}
@@ -78,7 +69,6 @@ pub(crate) fn emphasis_persists(effect: &str) -> bool {
fn uses_default_smoothing(effect: &str) -> bool {
matches!(effect, "fly" | "float" | "rise" | "peek" | "lines" | "arcs" | "turns" | "shapes" | "loops" | "customPath")
|| deckcraft_model::anim::preset_path(effect).is_some()
}
impl EffectSpec {
-266
View File
@@ -1,266 +0,0 @@
//! Clicks in a slide show: which shape a click lands on, what it starts (a triggered animation, a
//! link, the next step) and what the show remembers about each slide it has visited.
//!
//! The rules follow PowerPoint, as observed on its slide show:
//! - the topmost visible shape under the pointer decides; a shape without an action on top of one
//! with an action blocks it (the click then counts as a click on the background);
//! - a shape with a triggered animation plays the next step of it per click, and starts over once all
//! its steps have played; clicking it while a step plays completes the step at once;
//! - a shape with a link and a triggered animation follows the link at once. The animation's clock
//! runs only while its slide is shown, so it goes on where it stopped when the show returns;
//! - with "advance on click" off a click never leaves the slide, but it still plays animation steps;
//! - a slide the show returns to (link or arrow keys) looks as it was left.
use deckcraft_model::text::Action;
use deckcraft_model::{Presentation, ShapeId};
use crate::{AnimState, LinkJump, ShowAction, ShowState, StepStamp, Timeline, TriggerPlay};
/// What was played on one slide.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct SlideRun {
/// The show has been on this slide.
pub visited: bool,
/// Main-sequence steps played when the show left the slide.
pub step: usize,
/// Triggered sequences started by clicks.
pub triggers: Vec<TriggerRun>,
/// Steps of triggered sequences started so far (the stamps of [`StepStamp`]).
pub clock: u64,
}
/// Progress of one triggered sequence.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct TriggerRun {
pub shape: ShapeId,
/// Clicks whose step has played to its end.
pub done: usize,
/// Seconds the current step has played; `None` when no step is playing.
pub elapsed: Option<f64>,
/// When each step of this run was started, by step.
pub stamps: Vec<u64>,
}
/// One shape of the slide for hit testing, in drawing order (back to front; a group before its
/// children), with whether the pointer is inside its box.
#[derive(Clone, Debug, PartialEq)]
pub struct HitShape {
pub id: ShapeId,
/// Index of the enclosing group in the same list.
pub parent: Option<usize>,
pub is_group: bool,
/// The shape's own action.
pub link: Option<Action>,
pub under_pointer: bool,
}
/// What the pointer is over: a shape that does something when clicked.
#[derive(Clone, Debug, PartialEq)]
pub struct Target {
pub shape: ShapeId,
pub link: Option<Action>,
}
/// What a click did.
#[derive(Clone, Debug, PartialEq)]
pub enum Click {
/// Nothing happened.
None,
/// A triggered animation started or was completed: redraw.
Animated,
/// Navigation inside the show (already applied to the state).
Show(ShowAction),
/// Open this URL outside the show.
Open(String),
/// End the show.
Exit,
}
impl From<LinkJump> for Click {
fn from(j: LinkJump) -> Click {
match j {
LinkJump::Show(a) => Click::Show(a),
LinkJump::Open(u) => Click::Open(u),
LinkJump::Exit => Click::Exit,
LinkJump::None => Click::None,
}
}
}
fn finite_or_zero(v: f64) -> f64 {
if v.is_finite() { v } else { 0.0 }
}
impl ShowState {
fn animated(&self, pres: &Presentation) -> bool {
!pres.show.without_animation
}
/// Does clicking `shape` start a triggered sequence? A sequence can be started again once it has
/// played to its end.
fn trigger_live(&self, pres: &Presentation, tl: &Timeline, shape: ShapeId) -> bool {
self.animated(pres) && tl.trigger_steps(shape) > 0
}
/// The playheads of the current slide's triggered sequences at the last tick, for
/// [`Timeline::state_with`].
pub fn trigger_plays(&self) -> Vec<TriggerPlay> {
match self.runs.get(&self.slide) {
Some(r) => r.triggers.iter().map(|t| TriggerPlay { trigger: t.shape, step: t.done, t: t.elapsed.unwrap_or(0.0) }).collect(),
None => vec![],
}
}
/// When the steps of the current slide's triggered sequences were started.
pub fn trigger_stamps(&self) -> Vec<StepStamp> {
let Some(r) = self.runs.get(&self.slide) else { return vec![] };
r.triggers.iter().flat_map(|t| t.stamps.iter().enumerate().map(|(step, &at)| StepStamp { trigger: t.shape, step, at })).collect()
}
/// Is a triggered animation of the current slide playing (so the picture changes every frame)?
pub fn trigger_playing(&self) -> bool {
self.runs.get(&self.slide).is_some_and(|r| r.triggers.iter().any(|t| t.elapsed.is_some()))
}
/// Animation state of `shape` on the current slide: main step `step` with `t_main` seconds
/// played, plus the triggered sequences.
pub fn anim_state(&self, tl: &Timeline, shape: ShapeId, t_main: f64) -> AnimState {
tl.state_ordered(shape, None, self.step, t_main, &self.trigger_plays(), &self.trigger_stamps())
}
/// Advance the clock of the playing triggered animations to `now` (seconds, any steady clock)
/// and complete the steps that reached their end. [`Click::Animated`] when the picture changed.
pub fn tick(&mut self, tl: &Timeline, now: f64) -> Click {
let dt = match self.last_now {
Some(last) if now.is_finite() => (now - last).clamp(0.0, 3600.0),
_ => 0.0,
};
if now.is_finite() {
self.last_now = Some(now);
}
let Some(run) = self.runs.get_mut(&self.slide) else { return Click::None };
let mut changed = false;
for t in run.triggers.iter_mut() {
let Some(e) = t.elapsed else { continue };
let e = finite_or_zero(e) + dt;
if e >= tl.trigger_step_duration(t.shape, t.done) {
t.done += 1;
t.elapsed = None;
changed = true;
} else {
t.elapsed = Some(e);
}
}
if changed { Click::Animated } else { Click::None }
}
/// Index of the topmost shape a click lands on: the front-most one under the pointer that is
/// shown. A group without an action does not count; its children and the space inside its box
/// are not it.
pub fn top(&self, pres: &Presentation, tl: &Timeline, shapes: &[HitShape], visible: &dyn Fn(ShapeId) -> bool) -> Option<usize> {
let shown = |mut i: usize| -> bool {
// A shape is shown when it and the groups around it are.
for _ in 0..=shapes.len() {
let Some(h) = shapes.get(i) else { return false };
if !visible(h.id) {
return false;
}
match h.parent {
Some(p) => i = p,
None => return true,
}
}
false
};
(0..shapes.len())
.rev()
.find(|&i| shapes.get(i).is_some_and(|h| h.under_pointer && !(h.is_group && !self.interactive(pres, tl, h)) && shown(i)))
}
fn interactive(&self, pres: &Presentation, tl: &Timeline, h: &HitShape) -> bool {
h.link.is_some() || self.trigger_live(pres, tl, h.id)
}
/// The shape under the pointer that a click would act on, `None` when a click would be a click
/// on the background. `visible` tells whether a shape is currently shown (not yet entered or
/// already exited shapes cannot be clicked).
pub fn target(&self, pres: &Presentation, tl: &Timeline, shapes: &[HitShape], visible: &dyn Fn(ShapeId) -> bool) -> Option<Target> {
// The topmost shape, or the group it is in, that has an action. A shape without one blocks
// what lies beneath it.
let mut at = self.top(pres, tl, shapes, visible);
for _ in 0..=shapes.len() {
let h = shapes.get(at?)?;
if self.interactive(pres, tl, h) {
return Some(Target { shape: h.id, link: h.link.clone() });
}
at = h.parent;
}
None
}
/// A mouse click. `shapes` and `visible` describe what is under the pointer (see
/// [`ShowState::target`]); `last_viewed` is the slide shown before this one.
pub fn click(
&mut self,
pres: &Presentation,
tl: &Timeline,
shapes: &[HitShape],
visible: &dyn Fn(ShapeId) -> bool,
now: f64,
last_viewed: Option<usize>,
) -> Click {
self.tick(tl, now);
if self.ended {
return Click::None;
}
let Some(t) = self.target(pres, tl, shapes, visible) else { return self.background_click(pres) };
let mut animated = false;
if self.trigger_live(pres, tl, t.shape) {
let slide = self.slide;
let run = self.runs.entry(slide).or_default();
let at = match run.triggers.iter().position(|r| r.shape == t.shape) {
Some(p) => p,
None => {
run.triggers.push(TriggerRun { shape: t.shape, done: 0, elapsed: None, stamps: vec![] });
run.triggers.len() - 1
}
};
let stamp = run.clock.saturating_add(1);
if let Some(r) = run.triggers.get_mut(at) {
if r.elapsed.is_some() {
// A click on a shape whose step is playing completes the step.
r.done += 1;
r.elapsed = None;
} else {
if r.done >= tl.trigger_steps(t.shape) {
// All steps have played: the sequence starts over.
r.done = 0;
r.stamps.clear();
}
r.stamps.push(stamp);
run.clock = stamp;
if tl.trigger_step_duration(t.shape, r.done) > 0.0 {
r.elapsed = Some(0.0);
} else {
r.done += 1;
}
}
animated = true;
}
}
match t.link {
// The link is followed at once, whatever the animation still has to play.
Some(a) => self.follow(pres, &a, last_viewed).into(),
None if animated => Click::Animated,
None => Click::None,
}
}
/// A click that is on no shape with an action: next animation step, then next slide, unless the
/// slide has "advance on click" off, which leaves only the animation steps.
fn background_click(&mut self, pres: &Presentation) -> Click {
let advance = pres.slides.get(self.slide).and_then(|s| s.transition.as_ref()).is_none_or(|t| t.advance_on_click);
let steps_left = self.playing || self.step < ShowState::steps(pres, self.slide);
if advance || steps_left { Click::Show(self.next(pres)) } else { Click::None }
}
}
+4 -15
View File
@@ -5,8 +5,7 @@
//! - [`transition_layers`]: a slide transition frame as textured quads of the old/new slide images.
//! - [`morph_frame`]: a Morph transition frame (shapes matched by [`morph_pairs`], moved by
//! [`morph_xfrm`]).
//! - [`ShowState`]: slide show navigation (hidden slides, custom shows, loop, timings), what was
//! played on each visited slide, and what a click does ([`ShowState::click`]).
//! - [`ShowState`]: slide show navigation (hidden slides, custom shows, loop, timings).
//!
//! Pure logic: no rendering, no UI toolkit. Every function accepts hostile numbers (NaN, huge or
//! negative times) and never panics.
@@ -15,34 +14,24 @@
mod easing;
mod effects;
mod interact;
mod mesh;
mod morph;
mod path;
mod show;
mod timeline;
mod transition;
mod transition_fx;
mod transition_geom;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_interact;
#[cfg(test)]
mod transition_tests;
pub use deckcraft_model::Rgba;
use serde::{Deserialize, Serialize};
pub use easing::ease;
pub use interact::{Click, HitShape, Target};
pub use mesh::{MeshVertex, layer_mesh};
pub use morph::{MorphFrame, MorphPath, MorphText, morph_crop, morph_frame, morph_pairs, morph_xfrm};
pub use morph::{MorphFrame, MorphPath, MorphText, morph_frame, morph_pairs, morph_xfrm};
pub use path::{MotionPath, default_path};
pub use show::{LinkJump, ShowAction, ShowState, safe_url, show_order};
pub use timeline::{EffectTiming, Sequence, StepStamp, Timeline, TriggerPlay};
pub use transition::{DEFAULT_ASPECT, Layer, Source, transition_frame, transition_layers, uses_slide_parts};
pub use timeline::{EffectTiming, Sequence, Timeline, TriggerPlay};
pub use transition::{Layer, Source, transition_layers};
/// Animation state of one shape (or one paragraph of a shape's text) at one moment of the show.
///
-139
View File
@@ -1,139 +0,0 @@
//! Triangle meshes for transition layers.
//!
//! A [`Layer`] is a textured quad. Drawn as two triangles, a trapezoid (a slide seen in
//! perspective) bends its texture along the diagonal, because GPUs and simple rasterisers
//! interpolate texture coordinates linearly in screen space. [`layer_mesh`] splits such quads into a
//! grid whose vertices follow the projective map from the source rectangle to the quad, so the
//! picture looks like a flat card turned in 3-D. Rectangles and parallelograms stay two triangles,
//! wedges one: the per-frame cost stays a handful of vertices per layer.
use crate::transition::Layer;
/// One mesh vertex: position in slide-unit space (0..1, y down), texture coordinate (0..1) and
/// opacity (the layer's alpha times its corner fade, interpolated).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeshVertex {
pub pos: [f64; 2],
pub uv: [f64; 2],
pub a: f64,
}
/// Grid cells per side for quads that need a projective subdivision.
const GRID: usize = 8;
/// The triangles of a layer: vertices and index triples into them.
pub fn layer_mesh(l: &Layer) -> (Vec<MeshVertex>, Vec<[u32; 3]>) {
let q = l.quad;
let uv = l.uv;
let fa = l.fade.map(|f| f * l.alpha);
// A wedge (triangle): the 4th corner repeats the 3rd.
if q[3] == q[2] && uv[3] == uv[2] {
let v = (0..3).map(|k| MeshVertex { pos: q[k], uv: uv[k], a: fa[k] }).collect();
return (v, vec![[0, 1, 2]]);
}
let affine = {
// Parallelogram: opposite edges equal.
let e1 = [q[1][0] - q[0][0], q[1][1] - q[0][1]];
let e2 = [q[2][0] - q[3][0], q[2][1] - q[3][1]];
(e1[0] - e2[0]).abs() < 1e-9 && (e1[1] - e2[1]).abs() < 1e-9
};
let h = if affine { None } else { square_to_quad(q) };
let Some(h) = h else {
let v = (0..4).map(|k| MeshVertex { pos: q[k], uv: uv[k], a: fa[k] }).collect();
return (v, vec![[0, 1, 2], [0, 2, 3]]);
};
// Small quads (tiles, shards) bend their texture too little to matter: fewer cells.
let span = q.iter().flat_map(|p| q.iter().map(move |r| (p[0] - r[0]).abs().max((p[1] - r[1]).abs()))).fold(0.0, f64::max);
let n = ((span * 2.0 * GRID as f64).ceil() as usize).clamp(1, GRID);
let mut v = Vec::with_capacity((n + 1) * (n + 1));
for j in 0..=n {
let b = j as f64 / n as f64;
for i in 0..=n {
let a = i as f64 / n as f64;
// Texture: bilinear in (a, b) over the four uv corners (exact for rectangles).
let top = lerp2(uv[0], uv[1], a);
let bot = lerp2(uv[3], uv[2], a);
let t = lerp2(top, bot, b);
let at = fa[0] + (fa[1] - fa[0]) * a;
let ab = fa[3] + (fa[2] - fa[3]) * a;
v.push(MeshVertex { pos: apply(&h, a, b), uv: t, a: at + (ab - at) * b });
}
}
let mut tris = Vec::with_capacity(n * n * 2);
let w = (n + 1) as u32;
for j in 0..n as u32 {
for i in 0..n as u32 {
let p = j * w + i;
tris.push([p, p + 1, p + w + 1]);
tris.push([p, p + w + 1, p + w]);
}
}
(v, tris)
}
fn lerp2(a: [f64; 2], b: [f64; 2], t: f64) -> [f64; 2] {
[a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
}
/// Projective map taking the unit square's corners (0,0), (1,0), (1,1), (0,1) to `q`'s tl, tr, br,
/// bl (Heckbert's square-to-quad). `None` when the quad is degenerate.
fn square_to_quad(q: [[f64; 2]; 4]) -> Option<[f64; 8]> {
let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = q;
let sx = x0 - x1 + x2 - x3;
let sy = y0 - y1 + y2 - y3;
let (dx1, dx2, dy1, dy2) = (x1 - x2, x3 - x2, y1 - y2, y3 - y2);
let den = dx1 * dy2 - dx2 * dy1;
if !den.is_finite() || den.abs() < 1e-12 {
return None;
}
let g = (sx * dy2 - dx2 * sy) / den;
let h = (dx1 * sy - sx * dy1) / den;
let m = [x1 - x0 + g * x1, x3 - x0 + h * x3, x0, y1 - y0 + g * y1, y3 - y0 + h * y3, y0, g, h];
m.iter().all(|v| v.is_finite()).then_some(m)
}
fn apply(m: &[f64; 8], u: f64, v: f64) -> [f64; 2] {
let w = m[6] * u + m[7] * v + 1.0;
let w = if w.abs() < 1e-9 { 1e-9_f64.copysign(w) } else { w };
[(m[0] * u + m[1] * v + m[2]) / w, (m[3] * u + m[4] * v + m[5]) / w]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::transition::{Layer, Source};
#[test]
fn rect_is_two_triangles() {
let (v, t) = layer_mesh(&Layer::full(Source::New, 1.0));
assert_eq!((v.len(), t.len()), (4, 2));
}
#[test]
fn trapezoid_is_subdivided_projectively() {
// A card turned about its left edge: the right edge is shorter.
let q = [[0.0, 0.0], [0.6, 0.2], [0.6, 0.8], [0.0, 1.0]];
let l = Layer::quad(Source::Old, [0.0, 0.0, 1.0, 1.0], q, 1.0);
let (v, t) = layer_mesh(&l);
assert_eq!(v.len(), (GRID + 1) * (GRID + 1));
assert_eq!(t.len(), GRID * GRID * 2);
// A small tile in perspective needs no more than a couple of triangles.
let small = Layer::quad(Source::Old, [0.0, 0.0, 1.0, 1.0], [[0.5, 0.5], [0.52, 0.505], [0.52, 0.515], [0.5, 0.52]], 1.0);
assert!(layer_mesh(&small).1.len() <= 2);
// Corners land on the quad's corners.
assert_eq!(v[0].pos, q[0]);
let last = v[v.len() - 1].pos;
assert!((last[0] - 0.6).abs() < 1e-9 && (last[1] - 0.8).abs() < 1e-9);
// The texture's middle column sits nearer the far (short) edge than halfway: foreshortening.
let mid = v[GRID / 2].pos[0];
assert!(mid > 0.3, "{mid}");
}
#[test]
fn degenerate_quads_do_not_blow_up() {
let q = [[0.5, 0.5]; 4];
let l = Layer::quad(Source::Old, [0.0, 0.0, 1.0, 1.0], q, 1.0);
let (v, _) = layer_mesh(&l);
assert!(v.iter().all(|p| p.pos[0].is_finite() && p.pos[1].is_finite()));
}
}
+32 -128
View File
@@ -1,7 +1,5 @@
//! Morph: matching shapes between two slides, interpolating their boxes and building the frames.
use std::collections::{HashMap, HashSet, VecDeque};
use deckcraft_model::resolve::{self, Ctx};
use deckcraft_model::{ColorRef, Fill, Geom, Presentation, Rgba, Shape, ShapeId, ShapeKind, Slide, Xfrm, walk};
@@ -14,69 +12,48 @@ fn text_of(s: &Shape) -> String {
/// Pairs of (shape on `a`, shape on `b`) that Morph animates from one to the other: first by
/// `!!name` (forced match), then by exact name, then by the same kind and text, then by the same
/// kind and preset geometry if neither carries text. A text box with neither a name nor its text on
/// the other slide stays unpaired and fades in place, as in PowerPoint (#119). Each shape is used
/// once; top-level shapes only (groups move whole).
///
/// Each pass compares a key of the two shapes, so the shapes of `b` are indexed by key once per
/// pass: matching costs the sum of the two shape lists, not their product.
/// kind and preset geometry. Each shape is used once; top-level shapes only (groups move whole).
pub fn morph_pairs(a: &Slide, b: &Slide) -> Vec<(ShapeId, ShapeId)> {
let mut pairs: Vec<(ShapeId, ShapeId)> = Vec::new();
let mut used_a = vec![false; a.shapes.len()];
let mut used_b = vec![false; b.shapes.len()];
// Each shape's text, worked out once rather than inside every comparison.
let text_a: Vec<String> = a.shapes.iter().map(text_of).collect();
let text_b: Vec<String> = b.shapes.iter().map(text_of).collect();
let forced = |s: &Shape, _: &str| (s.name.starts_with("!!")).then(|| MorphKey::Name(s.name.clone()));
let named = |s: &Shape, _: &str| (!s.name.is_empty()).then(|| MorphKey::Name(s.name.clone()));
let same_text = |s: &Shape, t: &str| (!t.trim().is_empty()).then(|| MorphKey::Text(s.kind_name(), t.to_string()));
let same_geom = |s: &Shape, t: &str| match s.geom.preset_name() {
Some(g) if t.trim().is_empty() => Some(MorphKey::Geom(s.kind_name(), g.to_string())),
_ => None,
};
let passes: [&dyn Fn(&Shape, &str) -> Option<MorphKey>; 4] = [&forced, &named, &same_text, &same_geom];
for key in passes {
// Unused shapes of `b` by key, in slide order: the front of each queue is the first unused
// match, which is the one a search through `b` would find.
let mut index: HashMap<MorphKey, VecDeque<usize>> = HashMap::new();
for (j, sb) in b.shapes.iter().enumerate() {
if used_b.get(j).copied().unwrap_or(true) {
continue;
let passes: [&dyn Fn(&Shape, &Shape) -> bool; 4] = [
&|x, y| x.name.starts_with("!!") && x.name == y.name,
&|x, y| !x.name.is_empty() && x.name == y.name,
&|x, y| {
if x.kind_name() != y.kind_name() {
return false;
}
if let Some(k) = key(sb, text_b.get(j).map_or("", String::as_str)) {
index.entry(k).or_default().push_back(j);
}
}
if index.is_empty() {
continue;
}
let tx = text_of(x);
!tx.trim().is_empty() && tx == text_of(y)
},
&|x, y| {
x.kind_name() == y.kind_name()
&& x.geom.preset_name().is_some()
&& x.geom.preset_name() == y.geom.preset_name()
&& text_of(x).trim().is_empty() == text_of(y).trim().is_empty()
},
];
for pass in passes {
for (i, sa) in a.shapes.iter().enumerate() {
if used_a.get(i).copied().unwrap_or(true) {
continue;
}
let Some(k) = key(sa, text_a.get(i).map_or("", String::as_str)) else { continue };
let Some(j) = index.get_mut(&k).and_then(VecDeque::pop_front) else { continue };
let Some(sb) = b.shapes.get(j) else { continue };
if let Some(u) = used_a.get_mut(i) {
*u = true;
let found = b.shapes.iter().enumerate().find(|(j, sb)| !used_b.get(*j).copied().unwrap_or(true) && pass(sa, sb));
if let Some((j, sb)) = found {
if let Some(u) = used_a.get_mut(i) {
*u = true;
}
if let Some(u) = used_b.get_mut(j) {
*u = true;
}
pairs.push((sa.id, sb.id));
}
if let Some(u) = used_b.get_mut(j) {
*u = true;
}
pairs.push((sa.id, sb.id));
}
}
pairs
}
/// What one [`morph_pairs`] pass matches shapes on.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum MorphKey {
Name(String),
Text(&'static str, String),
Geom(&'static str, String),
}
fn lerp(a: f64, b: f64, t: f64) -> f64 {
let v = a + (b - a) * t;
if v.is_finite() {
@@ -196,58 +173,9 @@ fn reshaped(a: &Shape, b: &Shape) -> bool {
a.geom != b.geom && outlined(a) && outlined(b) && Shape { geom: Geom::default(), ..content(a) } == Shape { geom: Geom::default(), ..content(b) }
}
/// The content of a shape apart from what Morph interpolates, with a picture's crop left out.
fn uncropped(s: &Shape) -> Shape {
let mut c = content(s);
if let ShapeKind::Picture { fill } = &mut c.kind {
fill.crop = [0.0; 4];
}
c
}
fn crop_of(s: &Shape) -> [f64; 4] {
match &s.kind {
ShapeKind::Picture { fill } => fill.crop,
_ => [0.0; 4],
}
}
/// Whether two pictures differ in their crop only (apart from box and fill), so the crop can morph.
fn recropped(a: &Shape, b: &Shape) -> bool {
matches!(a.kind, ShapeKind::Picture { .. }) && crop_of(a) != crop_of(b) && uncropped(a) == uncropped(b)
}
/// The crop (left, top, right, bottom) of a picture morphing from box `xa` cropped by `ca` to box
/// `xb` cropped by `cb`, when its box is `x` at progress `t`: the whole image moves and scales
/// linearly between where it lies on either slide, and the crop is what of it `x` shows. Falls back
/// to blending the crops when a crop leaves nothing visible.
pub fn morph_crop(ca: [f64; 4], xa: Xfrm, cb: [f64; 4], xb: Xfrm, x: Xfrm, t: f64) -> [f64; 4] {
// Along one axis: (box start, box size, crop before, crop after) → the crops at `t`.
let axis = |(pa, sa, la, ha): (f64, f64, f64, f64), (pb, sb, lb, hb): (f64, f64, f64, f64), (p, s): (f64, f64)| {
let (va, vb) = (1.0 - la - ha, 1.0 - lb - hb);
if va <= 1e-6 || vb <= 1e-6 {
return (lerp(la, lb, t), lerp(ha, hb, t));
}
// The whole image: its extent and start on either slide.
let (ea, eb) = (sa / va, sb / vb);
let e = lerp(ea, eb, t);
if !e.is_finite() || e.abs() <= 1e-9 {
return (lerp(la, lb, t), lerp(ha, hb, t));
}
let o = lerp(pa - la * ea, pb - lb * eb, t);
let lo = (p - o) / e;
(lo, 1.0 - lo - s / e)
};
let (l, r) = axis((xa.x, xa.w, ca[0], ca[2]), (xb.x, xb.w, cb[0], cb[2]), (x.x, x.w));
let (tp, bt) = axis((xa.y, xa.h, ca[1], ca[3]), (xb.y, xb.h, cb[1], cb[3]), (x.y, x.h));
let c = [l, tp, r, bt];
if c.iter().all(|v| v.is_finite()) { c } else { cb }
}
/// Morph frame from slide `a` to slide `b` at progress `t` (0..1, eased here). Paired shapes
/// ([`morph_pairs`]) move along [`morph_xfrm`]; when they differ only in solid fill colour the
/// colour blends, when pictures differ only in crop the crop morphs ([`morph_crop`]), when only
/// in geometry (and fill colour) the outline morphs ([`MorphFrame::paths`]),
/// colour blends, when only in geometry (and fill colour) the outline morphs ([`MorphFrame::paths`]),
/// otherwise the new shape fades in under the fading old one on the same moving
/// box; with the transition option `words` or `characters` their texts are listed in
/// [`MorphFrame::text`] to morph word by word or character by character. Unpaired shapes of `a` fade out, unpaired shapes of `b` fade in, and shapes of `b` for
@@ -276,23 +204,13 @@ pub fn morph_frame(pres: &Presentation, a: &Slide, b: &Slide, t: f64, hidden_b:
f.shapes.push((sh, old));
id
};
// Lookups by id, built once (the first shape or pair with an id wins, as a search would).
let paired_a: HashSet<ShapeId> = pairs.iter().map(|(ia, _)| *ia).collect();
let mut partner: HashMap<ShapeId, ShapeId> = HashMap::with_capacity(pairs.len());
for (ia, ib) in &pairs {
partner.entry(*ib).or_insert(*ia);
}
let mut a_by_id: HashMap<ShapeId, &Shape> = HashMap::with_capacity(a.shapes.len());
for x in &a.shapes {
a_by_id.entry(x.id).or_insert(x);
}
for sa in &a.shapes {
if !paired_a.contains(&sa.id) {
if !pairs.iter().any(|(ia, _)| *ia == sa.id) {
push(sa.clone(), true, 1.0 - s);
}
}
for sb in &b.shapes {
let pair = partner.get(&sb.id).and_then(|ia| a_by_id.get(ia).copied());
let pair = pairs.iter().find(|(_, ib)| *ib == sb.id).and_then(|(ia, _)| a.shapes.iter().find(|x| x.id == *ia));
let Some(sa) = pair else {
if !hidden_b(sb.id) {
push(sb.clone(), false, s);
@@ -305,18 +223,8 @@ pub fn morph_frame(pres: &Presentation, a: &Slide, b: &Slide, t: f64, hidden_b:
(_, xb) => xb,
};
let reshape = reshaped(sa, sb);
let recrop = recropped(sa, sb);
if reshape || recrop || content(sa) == content(sb) {
if reshape || content(sa) == content(sb) {
let mut m = Shape { xfrm: x, ..sb.clone() };
if recrop && let ShapeKind::Picture { fill } = &mut m.kind {
fill.crop = match (xa, xb, x) {
(Some(xa), Some(xb), Some(x)) => morph_crop(crop_of(sa), xa, crop_of(sb), xb, x, s),
_ => {
let (ca, cb) = (crop_of(sa), crop_of(sb));
[lerp(ca[0], cb[0], s), lerp(ca[1], cb[1], s), lerp(ca[2], cb[2], s), lerp(ca[3], cb[3], s)]
}
};
}
if let (Some(fa), Some(fb)) = (solid_color(ca.as_ref(), sa), solid_color(cb.as_ref(), sb))
&& fa != fb
{
@@ -329,11 +237,7 @@ pub fn morph_frame(pres: &Presentation, a: &Slide, b: &Slide, t: f64, hidden_b:
} else {
let new = push(Shape { xfrm: x, ..sb.clone() }, false, s);
let old = push(Shape { xfrm: x, ..sa.clone() }, true, 1.0 - s);
// The same text in shapes that differ otherwise (a title slide's centred title and a
// content slide's title: other placeholder, size, alignment) moves and resizes word
// by word even with the Objects option, as PowerPoint does, instead of cross-fading.
let same_text = text_of(sa).trim() == text_of(sb).trim();
if (by_text || same_text)
if by_text
&& has_text(sa)
&& has_text(sb)
&& let (Some(from), Some(to)) = (box_of(ca.as_ref(), sa), box_of(cb.as_ref(), sb))
+2 -23
View File
@@ -49,7 +49,7 @@ fn tokenize(s: &str) -> Vec<Tok> {
n1.is_ascii_digit() || ((n1 == '-' || n1 == '+') && n2.is_ascii_digit())
} {
i += 2;
while cs.get(i).is_some_and(char::is_ascii_digit) {
while cs.get(i).is_some_and(|d| d.is_ascii_digit()) {
i += 1;
}
break;
@@ -288,27 +288,6 @@ pub fn default_path(effect: &str, option: &str) -> String {
}
},
"loops" => "M 0 0 C 0.08 -0.1 0.16 0 0.08 0.05 C 0 0.1 -0.08 0.1 -0.08 0 C -0.08 -0.1 0 -0.05 0 0 E".into(),
other => deckcraft_model::anim::preset_path(other).unwrap_or_default(),
}
}
#[cfg(test)]
mod preset_path_tests {
use super::*;
#[test]
fn every_extra_motion_path_preset_starts_at_its_shape_and_moves() {
use deckcraft_model::anim::{ANIMATIONS, AnimClass, preset_path};
let extra: Vec<_> = ANIMATIONS.iter().filter(|a| a.2 == AnimClass::Path && preset_path(a.0).is_some()).collect();
assert!(extra.len() >= 30);
for a in extra {
assert_eq!(default_path(a.0, ""), preset_path(a.0).unwrap_or_default());
let mp = MotionPath::parse(&default_path(a.0, ""));
let (x, y) = mp.at(0.0);
assert!(x.abs() < 1e-9 && y.abs() < 1e-9, "{} starts at its shape", a.0);
let far = mp.points.iter().map(|p| p.0.abs() + p.1.abs()).fold(0.0, f64::max);
assert!(far > 0.05, "{} moves", a.0);
assert!(mp.points.iter().all(|p| p.0.abs() < 0.5 && p.1.abs() < 0.5), "{} stays near its shape", a.0);
}
_ => String::new(),
}
}
+37 -177
View File
@@ -1,13 +1,10 @@
//! Slide show navigation: click steps, slide order (hidden slides, custom shows, ranges), loop
//! and automatic advance.
use std::collections::{BTreeMap, HashMap};
use deckcraft_model::text::{Action, Hyperlink};
use deckcraft_model::{Presentation, SlideId};
use deckcraft_model::Presentation;
use deckcraft_model::text::Action;
use crate::Timeline;
use crate::interact::SlideRun;
/// What the UI should do after a navigation call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -29,8 +26,18 @@ pub enum ShowAction {
Exit,
}
// Which links the show opens on a click; PDF export writes the same ones.
pub use deckcraft_model::text::safe_url;
/// Can a link from a (possibly untrusted) deck be opened outside the show? Only web pages and
/// mail: `file:`, `javascript:`, relative paths and other schemes (OS protocol handlers) are not
/// opened on a click.
pub fn safe_url(url: &str) -> bool {
let u = url.trim();
let Some((scheme, rest)) = u.split_once(':') else { return false };
match scheme.to_ascii_lowercase().as_str() {
"http" | "https" => rest.starts_with("//") && rest.len() > 2,
"mailto" => !rest.is_empty(),
_ => false,
}
}
/// What a clicked link does in the show (`ShowState::follow`).
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -45,10 +52,8 @@ pub enum LinkJump {
None,
}
/// Where a slide show is. Besides the current position it remembers what was played on every slide
/// the show has visited (main steps, triggered sequences), so a slide reached again by a link or
/// the arrow keys looks the way it was left, as in PowerPoint.
#[derive(Clone, Debug, PartialEq, Default)]
/// Where a slide show is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct ShowState {
/// Index into `presentation.slides`.
pub slide: usize,
@@ -58,32 +63,6 @@ pub struct ShowState {
pub playing: bool,
/// On the end screen.
pub ended: bool,
/// The current slide was reached by going back (← / Backspace), so the show plays the
/// transition of the slide it left, in reverse, as PowerPoint does (#1531).
pub backward: bool,
/// The show has entered a slide (so `slide` and `step` are meaningful and can be saved).
active: bool,
/// The time of the last [`ShowState::tick`] (seconds), for the triggered animations' clocks.
pub(crate) last_now: Option<f64>,
/// What was played on each visited slide (index into `presentation.slides`).
pub(crate) runs: BTreeMap<usize, SlideRun>,
/// One-shot visit order (Custom Show from the dialog or a click). `None` uses [`show_order`].
order: Option<Vec<usize>>,
/// Name of the custom show being played, when there is one.
custom: Option<String>,
/// Return to Zoom: (zoom slide, last zoomed slide). Advancing past the last zoomed slide goes
/// back to the zoom slide, fully built.
pub zoom: Option<(usize, usize)>,
}
/// Index of each slide by id (the first slide wins a duplicate id), so resolving a custom show
/// costs the sum of its two lists, not their product.
fn slide_indices(pres: &Presentation) -> HashMap<SlideId, usize> {
let mut map = HashMap::with_capacity(pres.slides.len());
for (i, s) in pres.slides.iter().enumerate() {
map.entry(s.id).or_insert(i);
}
map
}
/// Slide indices the show visits in order: the custom show or range from Set Up Slide Show, minus
@@ -91,10 +70,7 @@ fn slide_indices(pres: &Presentation) -> HashMap<SlideId, usize> {
pub fn show_order(pres: &Presentation) -> Vec<usize> {
let n = pres.slides.len();
let base: Vec<usize> = match pres.show.custom_show.as_ref().and_then(|name| pres.custom_shows.iter().find(|c| &c.name == name)) {
Some(cs) => {
let index = slide_indices(pres);
cs.slides.iter().filter_map(|id| index.get(id).copied()).collect()
}
Some(cs) => cs.slides.iter().filter_map(|id| pres.slides.iter().position(|s| s.id == *id)).collect(),
None => match pres.show.range {
Some((a, b)) => {
let a = (a.max(1) as usize).saturating_sub(1);
@@ -107,15 +83,6 @@ pub fn show_order(pres: &Presentation) -> Vec<usize> {
base.into_iter().filter(|i| pres.slides.get(*i).is_some_and(|s| !s.hidden)).collect()
}
/// Visible slides of custom show `name`, in that show's order.
fn custom_indices(pres: &Presentation, name: &str) -> Option<Vec<usize>> {
let cs = pres.custom_shows.iter().find(|c| c.name == name)?;
let index = slide_indices(pres);
let order: Vec<usize> =
cs.slides.iter().filter_map(|id| index.get(id).copied()).filter(|&i| pres.slides.get(i).is_some_and(|s| !s.hidden)).collect();
if order.is_empty() { None } else { Some(order) }
}
fn looping(pres: &Presentation) -> bool {
pres.show.loop_until_esc || pres.show.show_type == "kiosk"
}
@@ -137,48 +104,9 @@ impl ShowState {
} else {
s.ended = true;
}
if let Some(name) = pres.show.custom_show.clone() {
s.custom = Some(name);
}
s
}
/// Play custom show `name` from its first slide, without changing Set Up Slide Show.
/// `None` when that show is missing or has no visible slides.
pub fn play_custom(pres: &Presentation, name: &str) -> Option<ShowState> {
let order = custom_indices(pres, name)?;
let &first = order.first()?;
let mut s = ShowState::start_at(pres, first);
s.order = Some(order);
s.custom = Some(name.to_string());
Some(s)
}
/// Name of the custom show this playback is limited to.
pub fn custom_name(&self) -> Option<&str> {
self.custom.as_deref().filter(|s| !s.is_empty())
}
/// The slide that follows the current one in this show.
pub fn peek_next(&self, pres: &Presentation) -> Option<usize> {
self.next_index(pres)
}
pub fn first_index(&self, pres: &Presentation) -> Option<usize> {
self.visit(pres).first().copied()
}
pub fn last_index(&self, pres: &Presentation) -> Option<usize> {
self.visit(pres).last().copied()
}
fn visit(&self, pres: &Presentation) -> Vec<usize> {
match &self.order {
Some(order) => order.iter().copied().filter(|&i| pres.slides.get(i).is_some_and(|s| !s.hidden)).collect(),
None => show_order(pres),
}
}
/// The timeline of slide `i`.
pub fn timeline(pres: &Presentation, i: usize) -> Timeline {
match pres.slides.get(i) {
@@ -192,42 +120,15 @@ impl ShowState {
if pres.show.without_animation { 0 } else { ShowState::timeline(pres, i).steps() }
}
/// Save what was played on the current slide before the show moves away from it. A main step
/// that is playing is taken to its end. Triggered animations keep their place: their clock only
/// runs while the slide is shown, and they go on from there when the show comes back.
fn leave(&mut self, pres: &Presentation) {
if !self.active {
return;
}
let done = if self.playing { self.step + 1 } else { self.step };
let step = done.min(ShowState::steps(pres, self.slide));
self.runs.entry(self.slide).or_default().step = step;
self.playing = false;
}
/// Show slide `i`: as it was left when the show has been there before, otherwise from the start.
fn enter(&mut self, pres: &Presentation, i: usize) {
self.leave(pres);
self.active = true;
self.slide = i;
self.step = 0;
self.ended = false;
self.backward = false;
// Time spent elsewhere never counts for this slide's triggered animations.
self.last_now = None;
let steps = ShowState::steps(pres, i);
let run = self.runs.entry(i).or_default();
if run.visited {
self.step = run.step.min(steps);
self.playing = false;
} else {
run.visited = true;
self.step = 0;
self.playing = !pres.show.without_animation && ShowState::timeline(pres, i).step_is_auto(0);
}
self.playing = !pres.show.without_animation && ShowState::timeline(pres, i).step_is_auto(0);
}
fn next_index(&self, pres: &Presentation) -> Option<usize> {
let order = self.visit(pres);
let order = show_order(pres);
match order.iter().position(|&i| i == self.slide) {
Some(p) => order.get(p + 1).copied(),
None => order.iter().copied().find(|&i| i > self.slide),
@@ -235,7 +136,7 @@ impl ShowState {
}
fn prev_index(&self, pres: &Presentation) -> Option<usize> {
let order = self.visit(pres);
let order = show_order(pres);
match order.iter().position(|&i| i == self.slide) {
Some(p) => p.checked_sub(1).and_then(|q| order.get(q).copied()),
None => order.iter().copied().rev().find(|&i| i < self.slide),
@@ -259,22 +160,12 @@ impl ShowState {
self.playing = true;
return ShowAction::PlayStep(self.step);
}
if let Some((back, until)) = self.zoom
&& until == self.slide
&& back < pres.slides.len()
{
self.zoom = None;
self.enter(pres, back);
self.step = ShowState::steps(pres, back);
self.playing = false;
return ShowAction::Slide(back);
}
match self.next_index(pres) {
Some(i) => {
self.enter(pres, i);
ShowAction::Slide(i)
}
None if looping(pres) => match self.visit(pres).first() {
None if looping(pres) => match show_order(pres).first() {
Some(&i) => {
self.enter(pres, i);
ShowAction::Slide(i)
@@ -303,8 +194,7 @@ impl ShowState {
ShowAction::FinishStep(n)
}
/// ← / Backspace: undo the last step, else go to the previous slide fully built. An automatic
/// first step (With/After Previous) is part of the slide appearing, so it is never undone.
/// ← / Backspace: undo the last step, else go to the previous slide fully built.
pub fn prev(&mut self, pres: &Presentation) -> ShowAction {
if self.ended {
self.ended = false;
@@ -313,36 +203,26 @@ impl ShowState {
}
self.step = ShowState::steps(pres, self.slide);
self.playing = false;
self.backward = false;
return ShowAction::Slide(self.slide);
}
// #844: undoing the automatic first step left the slide as before it appeared, and the show
// played the step again at once, so Back never got past the slide.
let undo = if self.playing { Some(self.step) } else { self.step.checked_sub(1) };
let auto_first = undo == Some(0) && !pres.show.without_animation && ShowState::timeline(pres, self.slide).step_is_auto(0);
if let Some(k) = undo
&& !auto_first
{
if self.playing {
self.playing = false;
self.step = k;
return ShowAction::StepBack(k);
return ShowAction::StepBack(self.step);
}
if self.step > 0 {
self.step -= 1;
return ShowAction::StepBack(self.step);
}
let target = match self.prev_index(pres) {
Some(i) => Some(i),
None if looping(pres) => self.visit(pres).last().copied().filter(|&i| i != self.slide),
None if looping(pres) => show_order(pres).last().copied().filter(|&i| i != self.slide),
None => None,
};
match target {
Some(i) => {
// A slide the show has been to looks as it was left; one it has not been to is
// shown fully built.
let seen = self.runs.get(&i).is_some_and(|r| r.visited);
self.enter(pres, i);
if !seen {
self.step = ShowState::steps(pres, i);
self.playing = false;
}
self.backward = true;
self.slide = i;
self.step = ShowState::steps(pres, i);
self.playing = false;
ShowAction::Slide(i)
}
None => ShowAction::None,
@@ -354,7 +234,6 @@ impl ShowState {
if i >= pres.slides.len() {
return ShowAction::None;
}
self.zoom = None;
self.enter(pres, i);
ShowAction::Slide(i)
}
@@ -368,18 +247,11 @@ impl ShowState {
Action::Slide { slide } => pres.slides.iter().position(|s| s.id == *slide),
Action::NextSlide => self.next_index(pres),
Action::PreviousSlide => self.prev_index(pres),
Action::FirstSlide => self.visit(pres).first().copied(),
Action::LastSlide => self.visit(pres).last().copied(),
Action::FirstSlide => show_order(pres).first().copied(),
Action::LastSlide => show_order(pres).last().copied(),
Action::LastViewed => last_viewed,
Action::CustomShow { name, .. } => {
let Some(order) = custom_indices(pres, name) else { return LinkJump::None };
let Some(&i) = order.first() else { return LinkJump::None };
self.order = Some(order);
self.custom = Some(name.clone());
return LinkJump::Show(self.goto(pres, i));
}
// Programs and media actions aren't followed.
Action::Program { .. } | Action::PlayMedia => None,
// Custom shows, programs and media actions aren't followed (yet).
Action::CustomShow { .. } | Action::Program { .. } | Action::PlayMedia => None,
};
match target {
Some(i) => LinkJump::Show(self.goto(pres, i)),
@@ -387,18 +259,6 @@ impl ShowState {
}
}
/// Follow a clicked link, honouring a zoom's Return to Zoom (see [`Hyperlink::zoom_return`]).
pub fn follow_link(&mut self, pres: &Presentation, link: &Hyperlink, last_viewed: Option<usize>) -> LinkJump {
let from = self.slide;
let jump = self.follow(pres, &link.action, last_viewed);
if let Some(until) = link.zoom_return.and_then(|id| pres.slides.iter().position(|s| s.id == id))
&& matches!(jump, LinkJump::Show(ShowAction::Slide(_)))
{
self.zoom = Some((from, until));
}
jump
}
/// Seconds after which the current slide advances by itself (Advance Slide ▸ After), when the
/// show uses timings.
pub fn advance_after(&self, pres: &Presentation) -> Option<f64> {
+1 -422
View File
@@ -7,10 +7,7 @@ use deckcraft_model::{
AnimClass, AnimStart, Animation, ColorRef, CustomShow, Presentation, Rgba, Shape, ShapeId, Slide, SlideId, TextBody, Transition, Xfrm,
};
use crate::{
AnimState, Layer, LinkJump, MotionPath, ShowAction, ShowState, Source, Timeline, TriggerPlay, default_path, ease, morph_crop, morph_frame,
morph_pairs, morph_xfrm, show_order, transition_frame, transition_layers,
};
use crate::*;
const W: f64 = 960.0;
const H: f64 = 540.0;
@@ -347,36 +344,6 @@ fn empty_slide() {
assert_eq!(tl.locate(5.0), (0, 0.0));
}
#[test]
fn start_of_seeks_the_play_all_clock_to_an_effect() {
let mut late = anim(4, AnimClass::Entrance, "fade", AnimStart::WithPrevious);
late.delay_ms = 250;
let mut triggered = anim(4, AnimClass::Emphasis, "pulse", AnimStart::OnClick);
triggered.trigger = Some(ShapeId(1));
let tl = Timeline::new(
&slide_with(vec![
anim(1, AnimClass::Entrance, "fade", AnimStart::OnClick),
anim(2, AnimClass::Exit, "fadeOut", AnimStart::OnClick),
anim(3, AnimClass::Entrance, "fade", AnimStart::OnClick),
late,
triggered,
]),
W,
H,
);
assert_eq!(tl.start_of(0), Some(0.0));
assert_eq!(tl.start_of(2), Some(2.0));
assert_eq!(tl.start_of(3), Some(2.25));
assert_eq!(tl.start_of(4), None, "a triggered effect is not on the play-all clock");
assert_eq!(tl.start_of(9), None);
// Playing from the third effect: what came before has played, the rest has not.
let at = tl.start_of(2).unwrap();
assert!(tl.state_at(ShapeId(1), None, at).visible, "entered before");
assert!(!tl.state_at(ShapeId(2), None, at).visible, "exited before");
assert!(!tl.state_at(ShapeId(3), None, at).visible, "not entered yet");
assert!(!tl.state_at(ShapeId(4), None, at).visible, "not entered yet");
}
#[test]
fn locate_play_all_clock() {
let tl = Timeline::new(
@@ -562,61 +529,6 @@ fn morph_pairs_by_name_text_and_geometry() {
assert!(morph_pairs(&Slide::default(), &b).is_empty());
}
#[test]
fn morph_pairs_leaves_unrelated_text_boxes_alone() {
// A text box that leaves and an unrelated one that arrives fade in place (#119).
let p = deckcraft_model::defaults::new_presentation(None);
let mut a = Slide::default();
let mut b = Slide::default();
let tb = |id, name, x, text| Shape { xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)), text: Some(TextBody::from_text(text)), ..shape(id, name) };
a.shapes = vec![tb(1, "TextBox 1", 0.0, "Gone")];
b.shapes = vec![tb(2, "TextBox 2", 400.0, "New")];
assert!(morph_pairs(&a, &b).is_empty());
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
let xs: Vec<(&str, f64)> = f.shapes.iter().map(|(s, _)| (s.name.as_str(), s.xfrm.map_or(f64::NAN, |x| x.x))).collect();
assert_eq!(xs, [("TextBox 1", 0.0), ("TextBox 2", 400.0)]);
// Empty shapes of one kind and geometry still pair, and a named text box keeps its partner.
a.shapes.push(shape(3, "Rect A"));
b.shapes.push(shape(4, "Rect B"));
b.shapes[0].name = "TextBox 1".into();
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2)), (ShapeId(3), ShapeId(4))]);
}
#[test]
fn morph_crop_moves_the_image_linearly() {
let bx = |x, w| Xfrm::new(x, 0.0, w, 100.0);
// Same box, the crop pans from the left half to the right half of a 200-wide image.
let c = morph_crop([0.0, 0.0, 0.5, 0.0], bx(0.0, 100.0), [0.5, 0.0, 0.0, 0.0], bx(0.0, 100.0), bx(0.0, 100.0), 0.5);
assert!(c.iter().zip([0.25, 0.0, 0.25, 0.0]).all(|(a, b)| (a - b).abs() < 1e-9), "{c:?}");
// The box shrinks over an image that stays put: only the right crop grows.
let c = morph_crop([0.0; 4], bx(0.0, 100.0), [0.0, 0.0, 0.5, 0.0], bx(0.0, 50.0), bx(0.0, 75.0), 0.5);
assert!(c.iter().zip([0.0, 0.0, 0.25, 0.0]).all(|(a, b)| (a - b).abs() < 1e-9), "{c:?}");
// Nothing visible on one side: the crops blend.
let c = morph_crop([0.5, 0.0, 0.5, 0.0], bx(0.0, 100.0), [0.0; 4], bx(0.0, 100.0), bx(0.0, 100.0), 0.5);
assert!(c.iter().all(|v| v.is_finite()) && (c[0] - 0.25).abs() < 1e-9, "{c:?}");
}
#[test]
fn morph_frame_morphs_a_picture_crop() {
// A picture recropped on the next slide stays one picture whose crop morphs (#118).
let p = deckcraft_model::defaults::new_presentation(None);
let pic = |id, crop| Shape {
kind: deckcraft_model::ShapeKind::Picture { fill: deckcraft_model::style::PictureFill { crop, ..Default::default() } },
..shape(id, "Picture 1")
};
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![pic(1, [0.0, 0.0, 0.5, 0.0])];
b.shapes = vec![pic(2, [0.5, 0.0, 0.0, 0.0])];
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
assert_eq!(f.shapes.len(), 1);
assert!(f.opacity.is_empty());
let deckcraft_model::ShapeKind::Picture { fill } = &f.shapes[0].0.kind else { panic!("not a picture") };
let want = 0.5 * f.mix;
assert!((fill.crop[0] - want).abs() < 1e-9 && (fill.crop[2] - (0.5 - want)).abs() < 1e-9, "{:?}", fill.crop);
assert_eq!(morph_frame(&p, &a, &b, 1.0, &|_| false).shapes[0].0.kind, b.shapes[0].kind);
}
#[test]
fn morph_xfrm_interpolates() {
let a = Xfrm { rot: 350.0, ..Xfrm::new(0.0, 0.0, 100.0, 100.0) };
@@ -763,26 +675,6 @@ fn show_skips_hidden_slides() {
assert_eq!(s.goto(&p, 99), ShowAction::None);
}
#[test]
fn show_remembers_a_slide_was_reached_by_going_back() {
// #1531: the UI plays the left slide's transition reversed only for Back.
let p = pres(3);
let mut s = ShowState::new(&p);
assert_eq!(s.next(&p), ShowAction::Slide(1));
assert!(!s.backward);
assert_eq!(s.prev(&p), ShowAction::Slide(0));
assert!(s.backward);
assert_eq!(s.next(&p), ShowAction::Slide(1));
assert!(!s.backward);
assert_eq!(s.goto(&p, 0), ShowAction::Slide(0));
assert!(!s.backward, "a jump is not Back");
// Back from the end screen shows the last slide again, without a transition to reverse.
assert_eq!(s.goto(&p, 2), ShowAction::Slide(2));
assert_eq!(s.next(&p), ShowAction::End);
assert_eq!(s.prev(&p), ShowAction::Slide(2));
assert!(!s.backward);
}
#[test]
fn show_loops() {
let mut p = pres(3);
@@ -810,37 +702,6 @@ fn show_custom_show_and_range() {
assert_eq!(show_order(&p), vec![0, 1, 2, 3, 4]);
}
#[test]
fn playing_a_custom_show_stays_on_its_slides() {
use deckcraft_model::text::Action;
let mut p = pres(5);
p.custom_shows = vec![CustomShow { name: "Ends".into(), slides: vec![SlideId(1000), SlideId(1004)] }];
assert!(p.show.custom_show.is_none());
let mut s = ShowState::play_custom(&p, "Ends").expect("the show exists");
assert_eq!(s.custom_name(), Some("Ends"));
assert_eq!(s.slide, 0);
assert_eq!(s.peek_next(&p), Some(4));
assert_eq!(s.next(&p), ShowAction::Slide(4));
assert_eq!(s.next(&p), ShowAction::End);
assert_eq!(s.prev(&p), ShowAction::Slide(4));
assert_eq!(s.prev(&p), ShowAction::Slide(0));
assert!(ShowState::play_custom(&p, "Missing").is_none());
assert!(p.show.custom_show.is_none(), "one-shot playback does not change Set Up");
Arc::make_mut(&mut p.slides[4]).hidden = true;
let only = ShowState::play_custom(&p, "Ends").expect("the visible slide remains");
assert_eq!(only.first_index(&p), Some(0));
assert_eq!(only.last_index(&p), Some(0));
let mut s = ShowState::new(&p);
p.slides[4] = Arc::new(Slide { id: SlideId(1004), ..Default::default() });
assert_eq!(s.follow(&p, &Action::CustomShow { name: "Ends".into(), returns: true }, None), LinkJump::Show(ShowAction::Slide(0)));
assert_eq!(s.custom_name(), Some("Ends"));
assert_eq!(s.next(&p), ShowAction::Slide(4));
assert_eq!(s.follow(&p, &Action::CustomShow { name: "Missing".into(), returns: true }, None), LinkJump::None);
assert_eq!(s.slide, 4, "an unknown custom show leaves the current slide");
}
#[test]
fn show_steps_through_builds() {
let mut p = pres(2);
@@ -861,30 +722,6 @@ fn show_steps_through_builds() {
assert_eq!(s.step, 1);
}
#[test]
fn show_back_leaves_a_slide_whose_first_step_is_automatic() {
// #844: undoing the automatic first step left the slide as before it appeared, and the show
// played that step again at once, so Back never reached the slide before.
for start in [AnimStart::WithPrevious, AnimStart::AfterPrevious] {
let mut p = pres(2);
Arc::make_mut(&mut p.slides[1]).shapes = vec![shape(1, "A"), shape(2, "B")];
Arc::make_mut(&mut p.slides[1]).animations =
vec![anim(1, AnimClass::Entrance, "fade", start), anim(2, AnimClass::Entrance, "fade", AnimStart::OnClick)];
let mut s = ShowState::new(&p);
assert_eq!(s.next(&p), ShowAction::Slide(1));
assert!(s.playing, "{start:?}");
// While the automatic step plays.
assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}");
assert_eq!(s.next(&p), ShowAction::Slide(1));
// Once it has played, the click step is undone first, then Back leaves the slide.
assert_eq!(s.next(&p), ShowAction::PlayStep(1));
assert_eq!(s.step_done(&p), ShowAction::FinishStep(1));
assert_eq!(s.prev(&p), ShowAction::StepBack(1), "{start:?}");
assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}");
assert_eq!((s.step, s.playing), (0, false));
}
}
#[test]
fn show_auto_advance() {
let mut p = pres(2);
@@ -952,261 +789,3 @@ fn show_follows_links() {
assert_eq!(s.follow(&p, &Action::LastViewed, None), LinkJump::None);
assert_eq!(s.slide, 3);
}
/// #420: late in the Honeycomb every cell has settled, so the incoming hexagons must cover the
/// whole slide — the old row count stopped at ~75% of a 16:9 slide and left the bottom black.
#[test]
fn honeycomb_cells_reach_the_bottom_before_the_slide_ends() {
let sign = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| (a[0] - c[0]) * (b[1] - c[1]) - (b[0] - c[0]) * (a[1] - c[1]);
let inside = |p: [f64; 2], t: [[f64; 2]; 3]| {
// The dark seams between cells are the effect: at t=0.99 they are ~0.012% of the width
// open, so a 1% pad forgives them and still fails genuinely uncovered ground.
let c = [(t[0][0] + t[1][0] + t[2][0]) / 3.0, (t[0][1] + t[1][1] + t[2][1]) / 3.0];
let t = t.map(|v| [c[0] + (v[0] - c[0]) * 1.01, c[1] + (v[1] - c[1]) * 1.01]);
let (d1, d2, d3) = (sign(p, t[0], t[1]), sign(p, t[1], t[2]), sign(p, t[2], t[0]));
!((d1 < 0.0 || d2 < 0.0 || d3 < 0.0) && (d1 > 0.0 || d2 > 0.0 || d3 > 0.0))
};
for aspect in [16.0 / 9.0, 3.0 / 2.0, 4.0 / 3.0, 11.0 / 8.5, 1.0] {
// t = 0.99: every cell is settled and the seams are nearly closed.
let ls = transition_frame("honeycomb", "", 0.99, aspect);
let tris: Vec<[[f64; 2]; 3]> =
ls.iter().filter(|l| l.source == Source::New && l.alpha >= 1.0).map(|l| [l.quad[0], l.quad[1], l.quad[2]]).collect();
assert!(!tris.is_empty());
let mut sy = 0.0;
while sy <= 1.0 {
for sx in [0.0, 0.2, 0.4, 0.6, 0.8, 0.99, 1.0] {
let p = [sx, sy];
assert!(tris.iter().any(|t| inside(p, *t)), "honeycomb aspect {aspect} t=0.99: {sx},{sy} is uncovered (no settled cell reaches it)");
}
sy += 0.02;
}
}
}
/// #147: exits PowerPoint plays downward leave downward here too.
#[test]
fn sink_down_and_peek_out_to_bottom_move_down() {
for (effect, option) in [("sinkDown", ""), ("peekOut", "b"), ("floatOut", "d")] {
let mut a = anim(1, AnimClass::Exit, effect, AnimStart::OnClick);
a.option = option.into();
let tl = Timeline::new(&slide_with(vec![a]), W, H);
let s = tl.state(ShapeId(1), None, 0, 0.5);
assert!(s.offset_y > 0.0, "{effect} {option}: {s:?}");
}
}
#[test]
fn trigger_sequences_keep_first_appearance_order_when_interleaved() {
let mut anims = vec![];
for (i, tr) in [7u32, 5, 7, 0, 9, 5].iter().enumerate() {
let mut a = anim(1 + (i as u32 % 4), AnimClass::Entrance, "fade", AnimStart::OnClick);
a.trigger = (*tr != 0).then_some(ShapeId(*tr));
anims.push(a);
}
let tl = Timeline::new(&slide_with(anims), W, H);
assert_eq!(tl.trigger_shapes(), vec![ShapeId(7), ShapeId(5), ShapeId(9)]);
assert_eq!(tl.trigger_steps(ShapeId(7)), 2);
assert_eq!(tl.trigger_steps(ShapeId(5)), 2);
assert_eq!(tl.trigger_steps(ShapeId(9)), 1);
assert_eq!(tl.steps(), 1);
}
#[test]
fn many_distinct_triggers_past_the_effect_cap_build_in_order() {
// One sequence per animation: grouping used to rescan every animation per trigger
// (~1.2e10 steps here), now it is one pass, and nothing past the cap is looked at.
let n = 110_000u32;
let anims: Vec<Animation> = (0..n)
.map(|i| {
let mut a = anim(1, AnimClass::Entrance, "appear", AnimStart::OnClick);
a.trigger = Some(ShapeId(1000 + i));
a
})
.collect();
let tl = Timeline::new(&slide_with(anims), W, H);
assert_eq!(tl.effects().len(), 100_000);
let shapes = tl.trigger_shapes();
assert_eq!(shapes.len(), 100_000);
assert!(shapes.iter().enumerate().all(|(i, s)| *s == ShapeId(1000 + i as u32)));
}
/// #316: the same text in two shapes that differ otherwise (a title slide's big centred title,
/// a content slide's title) morphs word by word with the default Objects option, instead of
/// the old box cross-fading into the new one.
#[test]
fn same_text_morphs_even_by_objects() {
let p = deckcraft_model::defaults::new_presentation(None);
let titled = |id, x, size: f64, text: &str| {
let mut body = TextBody::from_text(text);
for para in &mut body.paragraphs {
for r in &mut para.runs {
r.props.size = Some(size);
}
}
Shape { xfrm: Some(Xfrm::new(x, 100.0, 600.0, 120.0)), text: Some(body), ..shape(id, "Title 1") }
};
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![titled(1, 100.0, 60.0, "TEST")];
b.shapes = vec![titled(2, 40.0, 44.0, "TEST")];
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
assert_eq!(f.text.len(), 1, "the shared text morphs");
assert!(!f.text[0].chars);
// Different texts still cross-fade with the Objects option.
b.shapes = vec![titled(2, 40.0, 44.0, "Other")];
assert!(morph_frame(&p, &a, &b, 0.5, &|_| false).text.is_empty());
}
#[test]
fn media_in_the_click_sequence_cues_and_does_not_hold_the_click() {
// #116: a video set to play in the click sequence starts with its step, and the step doesn't
// last as long as the video (the next click goes on while it plays).
let play = Animation { duration_ms: 5000, ..anim(1, AnimClass::Media, "play", AnimStart::OnClick) };
let tl = Timeline::new(&slide_with(vec![play.clone(), anim(2, AnimClass::Exit, "fadeOut", AnimStart::OnClick)]), W, H);
assert_eq!(tl.steps(), 2);
assert_eq!(tl.step_duration(0), 0.0);
let cues = tl.media_cues(0, f64::NEG_INFINITY, 0.0);
assert_eq!(cues.iter().map(|e| (e.shape, e.anim)).collect::<Vec<_>>(), [(ShapeId(1), 0)]);
assert!(tl.media_cues(0, 0.0, f64::INFINITY).is_empty(), "set off once");
assert!(tl.media_cues(1, f64::NEG_INFINITY, f64::INFINITY).is_empty(), "only media effects");
// An After Previous effect still waits for the video.
let tl = Timeline::new(&slide_with(vec![play, anim(2, AnimClass::Entrance, "fade", AnimStart::AfterPrevious)]), W, H);
assert!((tl.step_duration(0) - 6.0).abs() < 1e-9, "{}", tl.step_duration(0));
}
/// Zoom with Return to Zoom: after the zoomed slides the show goes back to the zoom slide, fully
/// built; without it, or after jumping elsewhere, the show carries on in order.
#[test]
fn show_returns_to_the_zoom_slide() {
use deckcraft_model::text::{Action, Hyperlink};
let p = pres(6);
let link = |to: u32, last: Option<u32>| Hyperlink {
action: Action::Slide { slide: SlideId(1000 + to) },
tooltip: String::new(),
highlight_click: false,
zoom_return: last.map(|l| SlideId(1000 + l)),
sound: None,
stop_sound: false,
};
let mut s = ShowState::new(&p);
// A section zoom on slide 0 for slides 2–3.
assert_eq!(s.follow_link(&p, &link(2, Some(3)), None), LinkJump::Show(ShowAction::Slide(2)));
assert_eq!(s.next(&p), ShowAction::Slide(3));
assert_eq!(s.next(&p), ShowAction::Slide(0), "back to the zoom");
assert_eq!(s.step, ShowState::steps(&p, 0));
assert_eq!(s.next(&p), ShowAction::Slide(1), "then on in order");
// Without Return to Zoom the show carries on.
let mut s = ShowState::new(&p);
s.follow_link(&p, &link(4, None), None);
assert_eq!(s.next(&p), ShowAction::Slide(5));
// Jumping elsewhere (See All Slides, a number) forgets the zoom.
let mut s = ShowState::new(&p);
s.follow_link(&p, &link(2, Some(2)), None);
s.goto(&p, 4);
assert_eq!(s.next(&p), ShowAction::Slide(5));
}
#[test]
fn custom_show_resolves_duplicate_ids_to_the_first_slide() {
let mut p = pres(3);
Arc::make_mut(&mut p.slides[2]).id = p.slides[0].id;
p.custom_shows = vec![CustomShow { name: "Dup".into(), slides: vec![p.slides[0].id, SlideId(1001), SlideId(424_242)] }];
p.show.custom_show = Some("Dup".into());
assert_eq!(show_order(&p), vec![0, 1]);
}
#[test]
fn custom_show_with_many_entries_resolves_quickly() {
let mut p = pres(20_000);
let ids: Vec<SlideId> = p.slides.iter().map(|s| s.id).collect();
p.custom_shows = vec![CustomShow { name: "All".into(), slides: ids.iter().rev().copied().collect() }];
p.show.custom_show = Some("All".into());
let t = std::time::Instant::now();
let order = show_order(&p);
assert_eq!(order.len(), 20_000);
assert_eq!(order[0], 19_999);
assert!(t.elapsed().as_secs() < 5);
}
#[test]
fn timeline_targets_the_first_shape_with_a_duplicate_id() {
let mut s = slide_with(vec![anim(7, AnimClass::Entrance, "fade", AnimStart::OnClick)]);
s.shapes[0] = shape(7, "first");
s.shapes[1] = shape(7, "second");
s.shapes[0].xfrm = Some(Xfrm::new(10.0, 10.0, 20.0, 20.0));
let tl = Timeline::new(&s, W, H);
assert_eq!(tl.effects().len(), 1);
assert_eq!(tl.steps(), 1);
}
#[test]
fn many_by_paragraph_animations_on_one_shape_share_paragraph_targets() {
let mut s = slide_with(vec![]);
s.shapes[0].text = Some(TextBody::from_text("one\ntwo\nthree"));
s.animations = (0..2_000)
.map(|_| {
let mut a = anim(1, AnimClass::Path, "customPath", AnimStart::OnClick);
a.text_build = TextBuild::ByParagraph;
a.path = Some("M 0 0 L 0.5 0.5 E".into());
a
})
.collect();
let tl = Timeline::new(&s, W, H);
assert_eq!(tl.effects().len(), 6_000);
assert_eq!(tl.paragraph_targets(ShapeId(1)), vec![0, 1, 2]);
}
#[test]
fn morph_pairs_take_the_first_unused_match_in_slide_order() {
let mut a = Slide::default();
let mut b = Slide::default();
a.shapes = vec![shape(1, "Same"), shape(2, "Same"), shape(3, "Other")];
b.shapes = vec![shape(11, "Same"), shape(12, "Same"), shape(13, "Same")];
// By name first, in slide order; the shape of `a` left over pairs by kind and geometry with
// the shape of `b` left over.
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(11)), (ShapeId(2), ShapeId(12)), (ShapeId(3), ShapeId(13))]);
}
#[test]
fn morph_of_large_slides_stays_linear() {
let n = 20_000u32;
let text = |i: u32, side: &str| Some(TextBody::from_text(&format!("{side} {i}")));
let mut a = Slide::default();
let mut b = Slide::default();
// Text no shape on the other slide shares: every pass looks for a partner and finds none.
a.shapes = (0..n).map(|i| Shape { text: text(i, "a"), ..shape(i + 1, "") }).collect();
b.shapes = (0..n).map(|i| Shape { text: text(i, "b"), ..shape(n + i + 1, "") }).collect();
// One named pair at opposite ends.
a.shapes[0].name = "Logo".into();
b.shapes[n as usize - 1].name = "Logo".into();
// No wall-clock bound (it would flake on a loaded runner): at this size a quadratic pairing
// takes minutes, so a regression shows as a test that hangs rather than a failed assertion.
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2 * n))]);
let p = deckcraft_model::defaults::new_presentation(None);
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
// Every shape fades in place; the named pair differs in text, so it cross-fades as two.
assert_eq!(f.shapes.len(), 2 * n as usize);
}
#[test]
fn paragraph_states_of_a_large_build_stay_linear() {
let n = 20_000usize;
let mut s = slide_with(vec![]);
let mut body = TextBody::from_text(&vec!["line"; n].join("\n"));
// One first-level paragraph owning every other paragraph.
for p in body.paragraphs.iter_mut().skip(1) {
p.level = 1;
}
s.shapes[0].text = Some(body);
let mut a = anim(1, AnimClass::Entrance, "fade", AnimStart::OnClick);
a.text_build = TextBuild::ByParagraph;
s.animations = vec![a];
let tl = Timeline::new(&s, W, H);
// No wall-clock bound, as above: a per-paragraph scan of the slide would take minutes here.
assert_eq!(tl.paragraph_targets(ShapeId(1)).len(), n);
for p in 0..n {
assert!(!tl.state(ShapeId(1), Some(p), 0, 0.0).visible);
assert!(tl.state(ShapeId(1), Some(p), 1, 0.0).visible);
}
assert_eq!(tl.animated_shapes(), [ShapeId(1)]);
}
-364
View File
@@ -1,364 +0,0 @@
//! Clicks, triggered animations and what the show remembers about visited slides.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
use deckcraft_model::text::Action;
use deckcraft_model::{AnimClass, AnimStart, Animation, Presentation, Shape, ShapeId, Slide, SlideId, Transition, Xfrm};
use crate::{Click, HitShape, LinkJump, ShowAction, ShowState, Target, Timeline};
fn shape(id: u32) -> Shape {
Shape { id: ShapeId(id), name: format!("S{id}"), xfrm: Some(Xfrm::new(100.0, 100.0, 200.0, 100.0)), ..Default::default() }
}
/// A triggered exit (`Disappear` when `ms` is 0, else a fade out) of `target`, started by clicking `trigger`.
fn exit_on_click(trigger: u32, target: u32, ms: u32) -> Animation {
let effect = if ms == 0 { "disappear" } else { "fadeOut" };
Animation {
shape: ShapeId(target),
class: AnimClass::Exit,
effect: effect.into(),
start: AnimStart::OnClick,
duration_ms: ms,
trigger: Some(ShapeId(trigger)),
..Default::default()
}
}
fn slide(id: u32, shapes: Vec<Shape>, animations: Vec<Animation>, advance_on_click: bool) -> Arc<Slide> {
let transition = (!advance_on_click).then(|| Transition { advance_on_click: false, ..Default::default() });
Arc::new(Slide { id: SlideId(id), shapes, animations, transition, ..Default::default() })
}
fn to_slide(n: u32) -> Option<Action> {
Some(Action::Slide { slide: SlideId(n) })
}
fn hit(id: u32, link: Option<Action>) -> HitShape {
HitShape { id: ShapeId(id), parent: None, is_group: false, link, under_pointer: true }
}
/// Test driver: a show plus the click helpers the slide show window uses.
struct Run {
pres: Presentation,
show: ShowState,
/// Hit shapes of each slide, back to front.
hits: Vec<Vec<HitShape>>,
now: f64,
}
impl Run {
fn new(pres: Presentation, hits: Vec<Vec<HitShape>>) -> Run {
let show = ShowState::new(&pres);
Run { pres, show, hits, now: 0.0 }
}
fn tl(&self) -> Timeline {
ShowState::timeline(&self.pres, self.show.slide)
}
fn visible(&self, id: ShapeId) -> bool {
let st = self.show.anim_state(&self.tl(), id, 0.0);
st.visible && st.opacity > 0.0
}
fn opacity(&self, id: u32) -> f64 {
self.show.anim_state(&self.tl(), ShapeId(id), 0.0).opacity
}
fn click(&mut self) -> Click {
let (tl, hits) = (self.tl(), self.hits[self.show.slide].clone());
let vis: Vec<(ShapeId, bool)> = hits.iter().map(|h| (h.id, self.visible(h.id))).collect();
let visible = move |id: ShapeId| vis.iter().find(|v| v.0 == id).is_none_or(|v| v.1);
self.show.click(&self.pres, &tl, &hits, &visible, self.now, None)
}
fn target(&self) -> Option<Target> {
let (tl, hits) = (self.tl(), &self.hits[self.show.slide]);
self.show.target(&self.pres, &tl, hits, &|id| self.visible(id))
}
/// Let `secs` pass on the shown slide, in small frames.
fn wait(&mut self, secs: f64) {
let end = self.now + secs;
while self.now < end - 1e-9 {
self.now = (self.now + 0.05).min(end);
let tl = self.tl();
self.show.tick(&tl, self.now);
}
}
}
/// The test deck: slide 1 has a text box (3), a linked button that also disappears (2) and a
/// picture on top of both that disappears (4); slide 2 has a button back to slide 1.
fn two_slides(advance_on_click: bool) -> Run {
let s1 = slide(1000, vec![shape(3), shape(2), shape(4)], vec![exit_on_click(4, 4, 0), exit_on_click(2, 2, 0)], advance_on_click);
let s2 = slide(1001, vec![shape(1)], vec![], advance_on_click);
let pres = Presentation { slides: vec![s1, s2], ..Default::default() };
Run::new(pres, vec![vec![hit(3, None), hit(2, to_slide(1001)), hit(4, None)], vec![hit(1, to_slide(1000))]])
}
#[test]
fn hidden_shapes_stay_hidden_when_the_show_comes_back() {
let mut r = two_slides(false);
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(4)), "the picture is on top");
// Click the picture: it disappears; the button beneath it is now the target.
assert_eq!(r.click(), Click::Animated);
assert!(!r.visible(ShapeId(4)));
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(2)));
// Click the button: its animation starts and the link is followed.
assert_eq!(r.click(), Click::Show(ShowAction::Slide(1)));
assert_eq!(r.show.slide, 1);
// Slide 2: the button goes back.
assert_eq!(r.click(), Click::Show(ShowAction::Slide(0)));
assert_eq!(r.show.slide, 0);
// Both are still gone, and nothing on the slide can be clicked any more.
assert!(!r.visible(ShapeId(4)) && !r.visible(ShapeId(2)) && r.visible(ShapeId(3)));
assert_eq!(r.target(), None);
// "Advance on click" is off: a click anywhere does nothing, however often.
for _ in 0..3 {
assert_eq!(r.click(), Click::None);
}
assert_eq!(r.show.slide, 0);
}
#[test]
fn background_click_advances_when_the_slide_allows_it() {
let mut r = two_slides(true);
r.click(); // the picture disappears
r.click(); // the button disappears and links to slide 2
r.click(); // the button there links back
assert_eq!(r.show.slide, 0);
assert_eq!(r.target(), None);
assert_eq!(r.click(), Click::Show(ShowAction::Slide(1)));
}
#[test]
fn advance_on_click_off_still_plays_animation_steps() {
let main = Animation { shape: ShapeId(1), class: AnimClass::Entrance, effect: "fade".into(), duration_ms: 500, ..Default::default() };
let s1 = slide(1000, vec![shape(1)], vec![main], false);
let s2 = slide(1001, vec![], vec![], false);
let pres = Presentation { slides: vec![s1, s2], ..Default::default() };
let mut r = Run::new(pres, vec![vec![hit(1, None)], vec![]]);
// The first click plays the step, the next finishes it; then the slide stays.
assert!(matches!(r.click(), Click::Show(ShowAction::PlayStep(0))));
assert!(matches!(r.click(), Click::Show(ShowAction::FinishStep(0))));
assert_eq!(r.click(), Click::None);
assert_eq!(r.show.slide, 0);
// The arrow keys still move on.
assert_eq!(r.show.next(&r.pres), ShowAction::Slide(1));
}
#[test]
fn a_shape_without_an_action_blocks_the_one_beneath_it() {
let s = slide(1000, vec![shape(1), shape(2)], vec![], true);
let pres = Presentation { slides: vec![s, slide(1001, vec![], vec![], true)], ..Default::default() };
let mut r = Run::new(pres, vec![vec![hit(1, to_slide(1001)), hit(2, None)], vec![]]);
assert_eq!(r.target(), None, "the plain shape on top blocks the button");
// So the click is a background click, not the button's link.
assert_eq!(r.click(), Click::Show(ShowAction::Slide(1)));
// Reversed, the button is on top and is the target.
let s = slide(1000, vec![shape(2), shape(1)], vec![], true);
let pres = Presentation { slides: vec![s, slide(1001, vec![], vec![], true)], ..Default::default() };
let r = Run::new(pres, vec![vec![hit(2, None), hit(1, to_slide(1001))], vec![]]);
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(1)));
}
#[test]
fn groups_answer_for_their_children() {
let s = slide(1000, vec![shape(1)], vec![], true);
let pres = Presentation { slides: vec![s, slide(1001, vec![], vec![], true)], ..Default::default() };
let group = |link| HitShape { id: ShapeId(10), parent: None, is_group: true, link, under_pointer: true };
let child = HitShape { id: ShapeId(11), parent: Some(1), is_group: false, link: None, under_pointer: true };
// A child of a group with an action acts as the group.
let r = Run::new(pres.clone(), vec![vec![hit(5, None), group(to_slide(1001)), child.clone()], vec![]]);
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(10)));
// Empty space inside the box of a group without an action blocks nothing.
let behind = hit(5, to_slide(1001));
let r = Run::new(pres, vec![vec![behind, group(None)], vec![]]);
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(5)));
}
#[test]
fn pointer_outside_a_shape_is_not_on_it() {
let s = slide(1000, vec![shape(1)], vec![], true);
let pres = Presentation { slides: vec![s], ..Default::default() };
let mut h = hit(1, to_slide(1000));
h.under_pointer = false;
let r = Run::new(pres, vec![vec![h]]);
assert_eq!(r.target(), None);
}
#[test]
fn each_click_plays_one_step_of_a_trigger_and_a_click_completes_a_playing_step() {
// Clicking shape 1 fades shape 2 out over 5 s, then shape 3 over 5 s.
let s = slide(1000, vec![shape(1), shape(2), shape(3)], vec![exit_on_click(1, 2, 5000), exit_on_click(1, 3, 5000)], true);
let pres = Presentation { slides: vec![s], ..Default::default() };
let mut r = Run::new(pres, vec![vec![hit(2, None), hit(3, None), hit(1, None)]]);
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(1)));
assert_eq!(r.click(), Click::Animated);
r.wait(2.0);
assert!(r.show.trigger_playing());
assert!(r.opacity(2) < 1.0 && r.opacity(2) > 0.0, "part way through the fade");
assert!(r.visible(ShapeId(3)));
// A click on the shape while its step plays completes the step at once...
assert_eq!(r.click(), Click::Animated);
assert!(!r.visible(ShapeId(2)) && !r.show.trigger_playing());
// ...and the next click plays the next step.
assert_eq!(r.click(), Click::Animated);
r.wait(5.2);
assert!(!r.visible(ShapeId(3)));
// All steps have played, and the shape still answers: its sequence starts over.
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(1)));
assert_eq!(r.click(), Click::Animated);
assert!(r.visible(ShapeId(2)) && r.visible(ShapeId(3)), "the first lap's effects are undone");
r.wait(5.2);
assert!(!r.visible(ShapeId(2)) && r.visible(ShapeId(3)));
}
#[test]
fn a_ring_of_triggers_goes_round_and_round() {
// Soccer's score: clicking shape k hides it and shows shape k+1; the last shows the first again.
let ring = 4u32;
let anims: Vec<Animation> = (1..=ring)
.flat_map(|k| {
let next = k % ring + 1;
let show = Animation {
shape: ShapeId(next),
class: AnimClass::Entrance,
effect: "appear".into(),
start: AnimStart::WithPrevious,
duration_ms: 0,
trigger: Some(ShapeId(k)),
..Default::default()
};
[exit_on_click(k, k, 0), show]
})
.collect();
let shapes: Vec<Shape> = (1..=ring).map(shape).collect();
let s = slide(1000, shapes, anims, true);
let pres = Presentation { slides: vec![s], ..Default::default() };
let hits: Vec<HitShape> = (1..=ring).map(|k| hit(k, None)).collect();
let mut r = Run::new(pres, vec![hits]);
let showing = |r: &Run| -> Vec<u32> { (1..=ring).filter(|k| r.visible(ShapeId(*k))).collect() };
assert_eq!(showing(&r), vec![1]);
for lap in 0..3 {
for k in 1..=ring {
assert_eq!(showing(&r), vec![k], "lap {lap}, before click {k}");
assert_eq!(r.target().map(|t| t.shape), Some(ShapeId(k)));
assert_eq!(r.click(), Click::Animated);
}
}
assert_eq!(showing(&r), vec![1]);
}
#[test]
fn a_link_is_followed_at_once_and_the_animation_goes_on_where_it_stopped() {
// Shape 1 fades shape 4 over 5 s; shape 2 links to slide 2.
let s1 = slide(1000, vec![shape(1), shape(2), shape(4)], vec![exit_on_click(1, 4, 5000)], false);
let s2 = slide(1001, vec![shape(5)], vec![], false);
let pres = Presentation { slides: vec![s1, s2], ..Default::default() };
let mut r = Run::new(pres, vec![vec![hit(4, None), hit(2, to_slide(1001)), hit(1, None)], vec![hit(5, to_slide(1000))]]);
// Click the animated shape, wait 2 s, click the link.
r.click();
r.wait(2.0);
assert_eq!(r.show.trigger_plays()[0].t.round(), 2.0);
// The second shape is not over the first one, so click the link directly.
let tl = r.tl();
let hits = vec![hit(2, to_slide(1001))];
assert_eq!(r.show.click(&r.pres, &tl, &hits, &|_| true, r.now, None), Click::Show(ShowAction::Slide(1)));
// However long the show stays away, the animation does not run.
r.wait(60.0);
assert_eq!(r.click(), Click::Show(ShowAction::Slide(0)));
// Back on the slide it has 3 s left.
assert!((r.show.trigger_plays()[0].t - 2.0).abs() < 0.1);
assert!(r.show.trigger_playing());
r.wait(2.5);
assert!(r.show.trigger_playing() && r.opacity(4) > 0.0);
r.wait(1.0);
assert!(!r.show.trigger_playing() && !r.visible(ShapeId(4)));
}
#[test]
fn a_shape_with_a_link_and_an_animation_follows_the_link_without_waiting() {
let s1 = slide(1000, vec![shape(2)], vec![exit_on_click(2, 2, 5000)], false);
let s2 = slide(1001, vec![shape(5)], vec![], false);
let pres = Presentation { slides: vec![s1, s2], ..Default::default() };
let mut r = Run::new(pres, vec![vec![hit(2, to_slide(1001))], vec![hit(5, to_slide(1000))]]);
assert_eq!(r.click(), Click::Show(ShowAction::Slide(1)));
r.wait(30.0);
assert_eq!(r.click(), Click::Show(ShowAction::Slide(0)));
// The whole animation is still ahead.
assert!(r.visible(ShapeId(2)) && r.opacity(2) > 0.95);
assert!(r.show.trigger_playing());
r.wait(5.5);
assert!(!r.visible(ShapeId(2)));
}
#[test]
fn a_slide_comes_back_the_way_it_was_left() {
let steps: Vec<Animation> = (1..=3)
.map(|i| Animation { shape: ShapeId(i), class: AnimClass::Entrance, effect: "appear".into(), duration_ms: 0, ..Default::default() })
.collect();
let s1 = slide(1000, vec![shape(1), shape(2), shape(3)], steps, true);
let s2 = slide(1001, vec![], vec![], true);
let s3 = slide(1002, vec![], vec![], true);
let pres = Presentation { slides: vec![s1, s2, s3], ..Default::default() };
let mut s = ShowState::new(&pres);
s.next(&pres);
s.step_done(&pres);
assert_eq!(s.step, 1);
// A link away and back: still after step 1.
assert_eq!(s.follow(&pres, &Action::Slide { slide: SlideId(1002) }, None), LinkJump::Show(ShowAction::Slide(2)));
assert_eq!(s.follow(&pres, &Action::Slide { slide: SlideId(1000) }, None), LinkJump::Show(ShowAction::Slide(0)));
assert_eq!((s.step, s.playing), (1, false));
// So does the back arrow.
s.goto(&pres, 1);
assert_eq!(s.prev(&pres), ShowAction::Slide(0));
assert_eq!(s.step, 1);
// A slide the show has not been to is entered at its start; going back to one shows it fully
// built.
let mut s = ShowState::new(&pres);
s.goto(&pres, 2);
assert_eq!(s.prev(&pres), ShowAction::Slide(1));
assert_eq!(s.step, ShowState::steps(&pres, 1));
}
#[test]
fn a_playing_main_step_is_finished_when_the_show_leaves() {
let a = Animation { shape: ShapeId(1), class: AnimClass::Entrance, effect: "fade".into(), duration_ms: 500, ..Default::default() };
let s1 = slide(1000, vec![shape(1)], vec![a], true);
let s2 = slide(1001, vec![], vec![], true);
let pres = Presentation { slides: vec![s1, s2], ..Default::default() };
let mut s = ShowState::new(&pres);
assert_eq!(s.next(&pres), ShowAction::PlayStep(0));
s.goto(&pres, 1);
s.goto(&pres, 0);
assert_eq!((s.step, s.playing), (1, false));
}
#[test]
fn show_without_animation_ignores_triggers() {
let s = slide(1000, vec![shape(1), shape(2)], vec![exit_on_click(1, 2, 0)], true);
let mut pres = Presentation { slides: vec![s], ..Default::default() };
pres.show.without_animation = true;
let r = Run::new(pres, vec![vec![hit(2, None), hit(1, None)]]);
assert_eq!(r.target(), None);
}
#[test]
fn clocks_and_pointers_with_hostile_numbers_are_harmless() {
let mut r = two_slides(true);
let tl = r.tl();
for now in [f64::NAN, f64::INFINITY, -1.0e300, 1.0e300, 0.0] {
r.show.tick(&tl, now);
let _ = r.show.click(&r.pres, &tl, &[], &|_| true, now, None);
}
// A parent index that points nowhere, or in a circle, is not followed forever.
let bad = vec![
HitShape { id: ShapeId(1), parent: Some(7), is_group: true, link: None, under_pointer: true },
HitShape { id: ShapeId(2), parent: Some(2), is_group: false, link: None, under_pointer: true },
];
assert_eq!(r.show.target(&r.pres, &tl, &bad, &|_| true), None);
}
+56 -195
View File
@@ -1,11 +1,8 @@
//! A slide's animation sequence: click steps, effect start times and per-shape state over time.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use deckcraft_model::anim::{BuildRole, TextBuild, paragraph_build_roles};
use deckcraft_model::anim::TextBuild;
use deckcraft_model::style::Fill;
use deckcraft_model::{AnimClass, AnimStart, Animation, ColorScheme, Rgba, SchemeSlot, Shape, ShapeId, Slide, Xfrm};
use deckcraft_model::{AnimClass, AnimStart, Animation, ColorScheme, Rgba, SchemeSlot, ShapeId, Slide, Xfrm};
use crate::AnimState;
use crate::effects::{EffectSpec, exit_base, motion_path};
@@ -13,6 +10,7 @@ use crate::effects::{EffectSpec, exit_base, motion_path};
/// Delay between paragraphs of a by-paragraph build that isn't on click (seconds).
pub const PARAGRAPH_STAGGER: f64 = 0.5;
const MAX_EFFECTS: usize = 100_000;
const MAX_PARAGRAPHS: usize = 1_000;
const MAX_ITERATIONS: f64 = 1.0e6;
/// Which sequence an effect belongs to.
@@ -59,16 +57,6 @@ pub struct TriggerPlay {
pub t: f64,
}
/// When a step of a triggered sequence was started, counted in started steps on the slide. Effects
/// of different triggers apply in this order, so that a shape hidden by one trigger and shown again
/// by another ends up as the later of the two left it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StepStamp {
pub trigger: ShapeId,
pub step: usize,
pub at: u64,
}
#[derive(Clone, Debug, Default)]
struct StepInfo {
auto: bool,
@@ -86,9 +74,7 @@ enum After {
#[derive(Clone, Debug)]
struct Effect {
timing: EffectTiming,
/// Shared by every paragraph effect of one animation, so a large motion path is not copied
/// per paragraph.
spec: Arc<EffectSpec>,
spec: EffectSpec,
after: After,
}
@@ -103,41 +89,6 @@ pub struct Timeline {
/// By-paragraph builds animate first-level paragraphs; deeper paragraphs follow their parent:
/// (shape, member paragraph, owner paragraph).
groups: Vec<(ShapeId, usize, usize)>,
/// Lookups built with the timeline, so evaluating a shape or paragraph costs its own effects
/// rather than a scan of every effect, group and colour on the slide.
index: TimelineIndex,
}
#[derive(Clone, Debug, Default)]
struct TimelineIndex {
/// Effects (indices into `effects`, in order) by target shape and paragraph.
by_target: HashMap<(ShapeId, Option<usize>), Vec<usize>>,
/// Effects (indices into `effects`, in order) by target shape.
by_shape: HashMap<ShapeId, Vec<usize>>,
/// Owner paragraph of each member paragraph (the first group recorded wins).
owner: HashMap<(ShapeId, usize), usize>,
/// Groups (member, owner) by shape, in order.
groups_by_shape: HashMap<ShapeId, Vec<(usize, usize)>>,
/// Base colour by shape (the first recorded wins).
color: HashMap<ShapeId, Rgba>,
}
impl TimelineIndex {
fn build(effects: &[Effect], groups: &[(ShapeId, usize, usize)], colors: &[(ShapeId, Rgba)]) -> TimelineIndex {
let mut ix = TimelineIndex::default();
for (i, e) in effects.iter().enumerate() {
ix.by_target.entry((e.timing.shape, e.timing.paragraph)).or_default().push(i);
ix.by_shape.entry(e.timing.shape).or_default().push(i);
}
for &(shape, member, owner) in groups {
ix.owner.entry((shape, member)).or_insert(owner);
ix.groups_by_shape.entry(shape).or_default().push((member, owner));
}
for &(shape, c) in colors {
ix.color.entry(shape).or_insert(c);
}
ix
}
}
enum Status {
@@ -200,74 +151,56 @@ impl Timeline {
let accent = scheme.map(|s| s.get(SchemeSlot::Accent1)).unwrap_or(Rgba::rgb(0x15, 0x60, 0x82));
let mut tl = Timeline::default();
if slide.animations.is_empty() {
return tl;
}
// Every shape by id, built once: resolving each animation's target by tree search would
// cost shapes x animations.
let shapes = shape_index(&slide.shapes);
// Paragraph targets of each shape, worked out for its first by-paragraph animation only.
let mut para_cache: HashMap<ShapeId, Arc<Vec<Option<usize>>>> = HashMap::new();
// Group the animations by sequence in one pass, sequences in order of first appearance
// (main first), so many distinct triggers cost linear work, not a scan per trigger.
let mut seqs: Vec<(Sequence, Vec<usize>)> = vec![(Sequence::Main, Vec::new())];
let mut seq_index: HashMap<Sequence, usize> = HashMap::from([(Sequence::Main, 0)]);
for (ai, a) in slide.animations.iter().enumerate() {
let s = a.trigger.map(Sequence::Trigger).unwrap_or(Sequence::Main);
let i = *seq_index.entry(s).or_insert_with(|| {
seqs.push((s, Vec::new()));
seqs.len() - 1
});
if let Some((_, members)) = seqs.get_mut(i) {
members.push(ai);
// Sequences in order of first appearance: main first.
let mut seqs: Vec<Sequence> = vec![Sequence::Main];
for a in &slide.animations {
if let Some(tr) = a.trigger {
let s = Sequence::Trigger(tr);
if !seqs.contains(&s) {
seqs.push(s);
}
}
}
// Paragraph groups already recorded (the list itself keeps their order).
let mut grouped: HashSet<(ShapeId, usize, usize)> = HashSet::new();
for (seq, members) in seqs {
if tl.effects.len() >= MAX_EFFECTS {
break;
}
for seq in seqs {
let mut steps: Vec<StepInfo> = Vec::new();
let mut group_begin = 0.0f64;
let mut max_end = 0.0f64;
for ai in members {
let Some(a) = slide.animations.get(ai) else { continue };
for (ai, a) in slide.animations.iter().enumerate() {
let aseq = a.trigger.map(Sequence::Trigger).unwrap_or(Sequence::Main);
if aseq != seq {
continue;
}
if tl.effects.len() >= MAX_EFFECTS {
break;
}
let shape = shapes.get(&a.shape).copied();
let shape = slide.shape(a.shape);
// Paragraph targets of this animation.
let paras: Arc<Vec<Option<usize>>> = match (a.paragraph, a.text_build) {
(Some(p), _) => Arc::new(vec![Some(p as usize)]),
let paras: Vec<Option<usize>> = match (a.paragraph, a.text_build) {
(Some(p), _) => vec![Some(p as usize)],
(None, TextBuild::ByParagraph) => {
let cached = para_cache.entry(a.shape).or_insert_with(|| {
let mut v: Vec<Option<usize>> = vec![];
if let Some(t) = shape.and_then(|s| s.text.as_ref()) {
for (i, role) in paragraph_build_roles(t).into_iter().enumerate() {
match role {
BuildRole::Top => v.push(Some(i)),
BuildRole::Member(o) => {
if grouped.insert((a.shape, i, o)) {
tl.groups.push((a.shape, i, o));
}
}
BuildRole::Unowned => {}
}
let mut v: Vec<Option<usize>> = vec![];
if let Some(t) = shape.and_then(|s| s.text.as_ref()) {
let filled = |p: &deckcraft_model::text::Paragraph| p.runs.iter().any(|r| !r.text.trim().is_empty());
let top = t.paragraphs.iter().filter(|p| filled(p)).map(|p| p.level).min().unwrap_or(0);
let mut owner: Option<usize> = None;
for (i, p) in t.paragraphs.iter().enumerate() {
if p.level <= top && filled(p) && v.len() < MAX_PARAGRAPHS {
owner = Some(i);
v.push(Some(i));
} else if let Some(o) = owner
&& !tl.groups.contains(&(a.shape, i, o))
{
tl.groups.push((a.shape, i, o));
}
}
if v.is_empty() {
v.push(None)
}
Arc::new(v)
});
Arc::clone(cached)
}
if v.is_empty() { vec![None] } else { v }
}
_ => Arc::new(vec![None]),
_ => vec![None],
};
let xf = xfrm_of(a.shape).or_else(|| shape.and_then(|s| s.xfrm)).unwrap_or(Xfrm::new(sw / 4.0, sh / 4.0, sw / 2.0, sh / 2.0));
let xf = sanitize_xfrm(xf, sw, sh);
let spec = Arc::new(build_spec(a, xf, sw, sh, &resolve));
let spec = build_spec(a, xf, sw, sh, &resolve);
let dur = secs(a.duration_ms);
let delay = secs(a.delay_ms);
let until_next_click = a.repeat == u32::MAX;
@@ -316,9 +249,7 @@ impl Timeline {
max_end = max_end.max(end);
let step = steps.len().saturating_sub(1);
if let Some(s) = steps.last_mut() {
// Media plays on by itself once started: it holds back an After Previous
// effect (`max_end`), but not the next click (#116).
s.duration = s.duration.max(if a.class == AnimClass::Media { start } else { end });
s.duration = s.duration.max(end);
}
tl.effects.push(Effect {
timing: EffectTiming {
@@ -336,7 +267,7 @@ impl Timeline {
span,
class: a.class,
},
spec: Arc::clone(&spec),
spec: spec.clone(),
after: after.clone(),
});
}
@@ -347,19 +278,17 @@ impl Timeline {
}
}
// Base colours of animated shapes.
let mut colored: HashSet<ShapeId> = HashSet::new();
for e in &tl.effects {
let id = e.timing.shape;
if !colored.insert(id) {
if tl.colors.iter().any(|(s, _)| *s == id) {
continue;
}
let c = match shapes.get(&id).copied().and_then(|s| s.fill.as_ref()) {
let c = match slide.shape(id).and_then(|s| s.fill.as_ref()) {
Some(Fill::Solid { color }) => resolve(color),
_ => accent,
};
tl.colors.push((id, c));
}
tl.index = TimelineIndex::build(&tl.effects, &tl.groups, &tl.colors);
tl
}
@@ -379,20 +308,6 @@ impl Timeline {
self.main.get(i).map(|s| s.duration).unwrap_or(0.0)
}
/// Media effects (Play, Pause, Stop) of main step `step` that start after `from` and by `to`
/// seconds into it, in order: what a show running the step from `from` to `to` sets off.
pub fn media_cues(&self, step: usize, from: f64, to: f64) -> Vec<EffectTiming> {
let mut v: Vec<EffectTiming> = self
.effects
.iter()
.map(|e| &e.timing)
.filter(|e| e.class == AnimClass::Media && e.sequence == Sequence::Main && e.step == step && e.start > from && e.start <= to)
.cloned()
.collect();
v.sort_by(|a, b| a.start.total_cmp(&b.start));
v
}
/// Total duration of the main sequence played without pauses.
pub fn total_duration(&self) -> f64 {
self.main.iter().map(|s| s.duration).sum()
@@ -410,19 +325,6 @@ impl Timeline {
(self.main.len(), 0.0)
}
/// Where effect `anim` (index into `slide.animations`) starts on the play-everything clock:
/// Animation Pane ▸ Play From. `None` for a triggered effect or one that isn't on the slide.
pub fn start_of(&self, anim: usize) -> Option<f64> {
let e = self
.effects
.iter()
.map(|e| &e.timing)
.filter(|e| e.anim == anim && e.sequence == Sequence::Main)
.min_by(|a, b| a.step.cmp(&b.step).then(a.start.total_cmp(&b.start)))?;
let before: f64 = self.main.iter().take(e.step).map(|s| s.duration).sum();
Some(before + e.start)
}
/// Shapes that start an interactive sequence when clicked.
pub fn trigger_shapes(&self) -> Vec<ShapeId> {
self.triggers.iter().map(|(s, _)| *s).collect()
@@ -449,12 +351,8 @@ impl Timeline {
/// Paragraph indices of `shape` animated separately (by-paragraph builds).
pub fn paragraph_targets(&self, shape: ShapeId) -> Vec<usize> {
let mine = self.index.by_shape.get(&shape).map_or(&[][..], Vec::as_slice);
let mut v: Vec<usize> = mine.iter().filter_map(|&i| self.effects.get(i)).filter_map(|e| e.timing.paragraph).collect();
let owners: HashSet<usize> = v.iter().copied().collect();
if let Some(groups) = self.index.groups_by_shape.get(&shape) {
v.extend(groups.iter().filter(|(_, owner)| owners.contains(owner)).map(|(member, _)| *member));
}
let mut v: Vec<usize> = self.effects.iter().filter(|e| e.timing.shape == shape).filter_map(|e| e.timing.paragraph).collect();
v.extend(self.groups.iter().filter(|g| g.0 == shape && v.contains(&g.2)).map(|g| g.1).collect::<Vec<_>>());
v.sort_unstable();
v.dedup();
v
@@ -462,8 +360,13 @@ impl Timeline {
/// Shapes with any effect.
pub fn animated_shapes(&self) -> Vec<ShapeId> {
let mut seen: HashSet<ShapeId> = HashSet::new();
self.effects.iter().map(|e| e.timing.shape).filter(|s| seen.insert(*s)).collect()
let mut v: Vec<ShapeId> = Vec::new();
for e in &self.effects {
if !v.contains(&e.timing.shape) {
v.push(e.timing.shape);
}
}
v
}
/// State of `shape` (or of one of its paragraphs, `para`) when `step` main steps have been
@@ -476,24 +379,9 @@ impl Timeline {
/// [`Timeline::state`] with the playheads of triggered sequences.
pub fn state_with(&self, shape: ShapeId, para: Option<usize>, step: usize, t: f64, triggers: &[TriggerPlay]) -> AnimState {
self.state_ordered(shape, para, step, t, triggers, &[])
}
/// [`Timeline::state_with`] applying the effects of triggered sequences in the order their steps
/// were started (`stamps`), after those of the main sequence. Without stamps they apply in
/// Animation Pane order.
pub fn state_ordered(
&self,
shape: ShapeId,
para: Option<usize>,
step: usize,
t: f64,
triggers: &[TriggerPlay],
stamps: &[StepStamp],
) -> AnimState {
let para = para.map(|p| self.index.owner.get(&(shape, p)).copied().unwrap_or(p));
let mine = self.index.by_target.get(&(shape, para)).map_or(&[][..], Vec::as_slice).iter().filter_map(|&i| self.effects.get(i));
let base_color = self.index.color.get(&shape).copied().unwrap_or(Rgba::rgb(0x15, 0x60, 0x82));
let para = para.map(|p| self.groups.iter().find(|g| g.0 == shape && g.1 == p).map(|g| g.2).unwrap_or(p));
let mine = self.effects.iter().filter(|e| e.timing.shape == shape && e.timing.paragraph == para);
let base_color = self.colors.iter().find(|(s, _)| *s == shape).map(|(_, c)| *c).unwrap_or(Rgba::rgb(0x15, 0x60, 0x82));
let mut st = AnimState::default();
// Initial visibility comes from the first effect in the Animation Pane order.
let mut ordered: Vec<&Effect> = mine.collect();
@@ -503,16 +391,7 @@ impl Timeline {
{
st.visible = false;
}
// Then play in time order: main sequence first, then triggered sequences as they were clicked.
if !stamps.is_empty() {
let when = |e: &Effect| match e.timing.sequence {
Sequence::Main => 0,
Sequence::Trigger(tr) => {
stamps.iter().find(|s| s.trigger == tr && s.step == e.timing.step).map_or(u64::MAX, |s| s.at.saturating_add(1))
}
};
ordered.sort_by_key(|e| (when(e), e.timing.anim));
}
// Then play in time order: main sequence first, then triggered sequences.
for e in &ordered {
let (pstep, pt) = match e.timing.sequence {
Sequence::Main => (step, t),
@@ -586,31 +465,13 @@ fn status(e: &EffectTiming, step: usize, t: f64) -> Status {
Status::Active(p.clamp(0.0, 1.0))
}
/// Shapes by id in the order `Slide::shape` searches (a shape before its children, groups at most
/// 64 deep); the first shape with an id wins a duplicate.
fn shape_index(shapes: &[Shape]) -> HashMap<ShapeId, &Shape> {
fn walk<'a>(shapes: &'a [Shape], depth: usize, out: &mut HashMap<ShapeId, &'a Shape>) {
if depth > 64 {
return;
}
for s in shapes {
out.entry(s.id).or_insert(s);
walk(s.children(), depth + 1, out);
}
}
let mut out = HashMap::new();
walk(shapes, 0, &mut out);
out
}
fn build_spec(a: &Animation, xf: Xfrm, sw: f64, sh: f64, resolve: &dyn Fn(&deckcraft_model::ColorRef) -> Rgba) -> EffectSpec {
let effect = if a.class == AnimClass::Exit { exit_base(&a.effect).to_string() } else { a.effect.clone() };
let path = if a.class == AnimClass::Path { Some(motion_path(&a.effect, &a.option, a.path.as_deref())) } else { None };
EffectSpec {
class: a.class,
effect,
// Sink Down is Rise Up played backwards, leaving downward.
option: if a.effect == "sinkDown" { "d".into() } else { a.option.clone() },
option: a.option.clone(),
accel: a.smooth_start,
decel: a.smooth_end,
bounce: a.bounce_end,
+821 -96
View File
@@ -1,18 +1,15 @@
//! Slide transitions as layers of textured quads.
//!
//! A frame is drawn over black: each [`Layer`] maps part of a source image (old slide, new slide,
//! their backgrounds or contents alone, or a solid colour) onto a quad in slide-unit space (0..1, y
//! down), with an opacity per corner. Perspective comes from projecting 3-D cards
//! ([`crate::layer_mesh`] keeps their textures straight); soft edges come from per-corner opacity
//! ramps; wedges are triangles (4th corner repeats the 3rd).
//!
//! The motions, curves, directions and option meanings were measured frame by frame on
//! PowerPoint's video export of synthetic decks (`plan/powerpoint/tools/synth_transitions.ps1`).
//! The effects themselves live in [`crate::transition_fx`].
//! or a solid colour) onto a quad in slide-unit space (0..1, y down). Fake 3-D comes from
//! trapezoids; wedges are triangles (4th corner repeats the 3rd).
use std::f64::consts::PI;
use serde::{Deserialize, Serialize};
use crate::clampf;
use crate::easing::smooth;
/// What a layer shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -23,35 +20,6 @@ pub enum Source {
New,
Black,
White,
/// The outgoing slide's background (background fill plus master and layout graphics) alone.
OldBack,
/// The incoming slide's background alone.
NewBack,
/// The outgoing slide's own shapes alone, over transparency.
OldContent,
/// The incoming slide's own shapes alone, over transparency.
NewContent,
}
impl Source {
/// The whole-slide source to draw instead when the parts aren't available: a background
/// becomes its slide, content becomes nothing.
pub fn whole(self) -> Option<Source> {
match self {
Source::OldBack => Some(Source::Old),
Source::NewBack => Some(Source::New),
Source::OldContent | Source::NewContent => None,
s => Some(s),
}
}
/// Does this source need the slide rendered in parts (background / content)?
pub fn is_part(self) -> bool {
matches!(self, Source::OldBack | Source::NewBack | Source::OldContent | Source::NewContent)
}
}
fn ones() -> [f64; 4] {
[1.0; 4]
}
/// One textured quad of a transition frame.
@@ -66,18 +34,12 @@ pub struct Layer {
/// are the corners of `src`; triangles and mirrored flaps carry their own. Draw with these.
pub uv: [[f64; 2]; 4],
pub alpha: f64,
/// Opacity of each corner (tl, tr, br, bl), multiplied by `alpha` and interpolated across the
/// quad: soft edges and feathered masks.
#[serde(default = "ones")]
pub fade: [f64; 4],
}
pub(crate) type R = [f64; 4];
pub(crate) type P = [f64; 2];
pub(crate) type Q = [[f64; 2]; 4];
pub(crate) const FULL: R = [0.0, 0.0, 1.0, 1.0];
type R = [f64; 4];
const FULL: R = [0.0, 0.0, 1.0, 1.0];
pub(crate) fn corners(r: R) -> Q {
fn corners(r: R) -> [[f64; 2]; 4] {
[[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]]
}
@@ -88,39 +50,23 @@ impl Layer {
}
/// `src` rectangle of the source drawn into the `dst` rectangle.
pub fn rect(source: Source, src: R, dst: R, alpha: f64) -> Layer {
Layer { source, src, quad: corners(dst), uv: corners(src), alpha, fade: ones() }
Layer { source, src, quad: corners(dst), uv: corners(src), alpha }
}
/// `src` rectangle of the source drawn onto a quad.
pub fn quad(source: Source, src: R, quad: Q, alpha: f64) -> Layer {
Layer { source, src, quad, uv: corners(src), alpha, fade: ones() }
pub fn quad(source: Source, src: R, quad: [[f64; 2]; 4], alpha: f64) -> Layer {
Layer { source, src, quad, uv: corners(src), alpha }
}
/// The part of the source under `dst` drawn in place.
pub(crate) fn inplace(source: Source, dst: R, alpha: f64) -> Layer {
fn inplace(source: Source, dst: R, alpha: f64) -> Layer {
Layer::rect(source, dst, dst, alpha)
}
/// A triangle with its own texture coordinates and corner opacities.
pub(crate) fn tri_uv(source: Source, p: [P; 3], uv: [P; 3], fade: [f64; 3], alpha: f64) -> Layer {
let xs = [uv[0][0], uv[1][0], uv[2][0]];
let ys = [uv[0][1], uv[1][1], uv[2][1]];
/// A triangle of the source drawn in place.
fn tri(source: Source, a: [f64; 2], b: [f64; 2], c: [f64; 2], alpha: f64) -> Layer {
let xs = [a[0], b[0], c[0]];
let ys = [a[1], b[1], c[1]];
let mn = |v: [f64; 3]| v.iter().copied().fold(f64::INFINITY, f64::min);
let mx = |v: [f64; 3]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
Layer {
source,
src: [mn(xs), mn(ys), mx(xs), mx(ys)],
quad: [p[0], p[1], p[2], p[2]],
uv: [uv[0], uv[1], uv[2], uv[2]],
alpha,
fade: [fade[0], fade[1], fade[2], fade[2]],
}
}
/// With corner opacities.
pub(crate) fn faded(mut self, fade: [f64; 4]) -> Layer {
self.fade = fade;
self
}
/// A black copy of this layer's shape at `k` of its opacity: shading a card.
pub(crate) fn shade(&self, k: f64) -> Layer {
Layer { source: Source::Black, alpha: self.alpha * k.clamp(0.0, 1.0), ..*self }
Layer { source, src: [mn(xs), mn(ys), mx(xs), mx(ys)], quad: [a, b, c, c], uv: [a, b, c, c], alpha }
}
fn sanitized(mut self) -> Layer {
let f = |v: f64| if v.is_finite() { v.clamp(-1.0e6, 1.0e6) } else { 0.0 };
@@ -135,48 +81,827 @@ impl Layer {
c[0] = c[0].clamp(0.0, 1.0);
c[1] = c[1].clamp(0.0, 1.0);
}
for a in self.fade.iter_mut() {
*a = clampf(*a, 0.0, 1.0, 0.0);
}
self.alpha = clampf(self.alpha, 0.0, 1.0, 0.0);
self
}
}
/// Slide aspect assumed by [`transition_layers`] (16:9).
pub const DEFAULT_ASPECT: f64 = 16.0 / 9.0;
// ---------- geometry helpers ----------
/// Layers of the transition `kind` (a [`deckcraft_model::anim::TRANSITIONS`] id) with `option` at
/// progress `t` (0..1) on a 16:9 slide. See [`transition_frame`].
pub fn transition_layers(kind: &str, option: &str, t: f64) -> Vec<Layer> {
transition_frame(kind, option, t, DEFAULT_ASPECT)
fn offset(r: R, dx: f64, dy: f64) -> R {
[r[0] + dx, r[1] + dy, r[2] + dx, r[3] + dy]
}
/// Layers of the transition `kind` with `option` at linear progress `t` (0..1; the effect applies
/// its own easing) on a slide `aspect` wide per unit of height. Draw in order over black. At
/// `t >= 1` the result is the new slide alone; at `t <= 0` (or NaN) the old slide alone. Morph
/// returns a plain crossfade (the UI renders morph frames with [`crate::morph_frame`]). Layers
/// with [`Source::is_part`] sources need the slides rendered as background and content
/// ([`uses_slide_parts`]).
pub fn transition_frame(kind: &str, option: &str, t: f64, aspect: f64) -> Vec<Layer> {
fn moved(source: Source, dx: f64, dy: f64, alpha: f64) -> Layer {
Layer::rect(source, FULL, offset(FULL, dx, dy), alpha)
}
/// The whole source scaled about (cx, cy) and moved.
fn scaled(source: Source, s: f64, cx: f64, cy: f64, dx: f64, dy: f64, alpha: f64) -> Layer {
let r = [cx + (0.0 - cx) * s + dx, cy + (0.0 - cy) * s + dy, cx + (1.0 - cx) * s + dx, cy + (1.0 - cy) * s + dy];
Layer::rect(source, FULL, r, alpha)
}
/// Rotate a point about a pivot (degrees).
fn rot(p: [f64; 2], c: [f64; 2], deg: f64) -> [f64; 2] {
let (s, co) = deg.to_radians().sin_cos();
let (x, y) = (p[0] - c[0], p[1] - c[1]);
[c[0] + x * co - y * s, c[1] + x * s + y * co]
}
fn rot_quad(q: [[f64; 2]; 4], c: [f64; 2], deg: f64) -> [[f64; 2]; 4] {
[rot(q[0], c, deg), rot(q[1], c, deg), rot(q[2], c, deg), rot(q[3], c, deg)]
}
/// Horizontal perspective: left/right edges shortened by `li`/`ri` (fraction of height, each end).
fn persp_h(r: R, li: f64, ri: f64) -> [[f64; 2]; 4] {
let h = r[3] - r[1];
[[r[0], r[1] + li * h], [r[2], r[1] + ri * h], [r[2], r[3] - ri * h], [r[0], r[3] - li * h]]
}
/// Vertical perspective: top/bottom edges shortened by `ti`/`bi` (fraction of width, each end).
fn persp_v(r: R, ti: f64, bi: f64) -> [[f64; 2]; 4] {
let w = r[2] - r[0];
[[r[0] + ti * w, r[1]], [r[2] - ti * w, r[1]], [r[2] - bi * w, r[3]], [r[0] + bi * w, r[3]]]
}
/// Mirror a rectangle horizontally and/or vertically, or swap its axes (canonical → direction).
fn map_rect(r: R, mx: bool, my: bool, swap: bool) -> R {
let mut r = if swap { [r[1], r[0], r[3], r[2]] } else { r };
if mx {
r = [1.0 - r[2], r[1], 1.0 - r[0], r[3]];
}
if my {
r = [r[0], 1.0 - r[3], r[2], 1.0 - r[1]];
}
r
}
/// Motion direction of an option: l, r, u, d and diagonals.
fn dir(opt: &str, default: (f64, f64)) -> (f64, f64) {
let mut d = (0.0, 0.0);
if opt.contains('l') {
d.0 = -1.0;
}
if opt.contains('r') {
d.0 = 1.0;
}
if opt.contains('u') {
d.1 = -1.0;
}
if opt.contains('d') {
d.1 = 1.0;
}
if d == (0.0, 0.0) { default } else { d }
}
fn hash64(mut x: u64) -> u64 {
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^ (x >> 31)
}
/// Deterministic pseudo-random value in [0, 1).
fn rnd(i: u64) -> f64 {
(hash64(i) >> 11) as f64 / (1u64 << 53) as f64
}
fn ramp(t: f64, order: f64, window: f64) -> f64 {
let w = window.clamp(0.01, 1.0);
((t - order * (1.0 - w)) / w).clamp(0.0, 1.0)
}
fn grid(cols: usize, rows: usize) -> Vec<(usize, usize, R)> {
let mut v = Vec::with_capacity(cols * rows);
for r in 0..rows {
for c in 0..cols {
let cell = [c as f64 / cols as f64, r as f64 / rows as f64, (c + 1) as f64 / cols as f64, (r + 1) as f64 / rows as f64];
v.push((c, r, cell));
}
}
v
}
fn center(r: R) -> [f64; 2] {
[(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]
}
fn scale_rect(r: R, s: f64) -> R {
let c = center(r);
let hw = (r[2] - r[0]) / 2.0 * s;
let hh = (r[3] - r[1]) / 2.0 * s;
[c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh]
}
// ---------- effects ----------
/// Layers of the transition `kind` (a [`deckcraft_model::anim::TRANSITIONS`] id) with `option` at
/// progress `t` (0..1). Draw in order over black. At `t >= 1` the result is the new slide alone;
/// at `t <= 0` (or NaN) the old slide alone. Morph returns a plain crossfade (the UI renders morph
/// frames with [`crate::morph_frame`]).
pub fn transition_layers(kind: &str, option: &str, t: f64) -> Vec<Layer> {
let t = clampf(t, 0.0, 1.0, 0.0);
let aspect = if aspect.is_finite() && aspect > 0.01 { aspect.min(100.0) } else { DEFAULT_ASPECT };
let v = if t >= 1.0 {
vec![Layer::full(Source::New, 1.0)]
} else if t <= 0.0 {
vec![Layer::full(Source::Old, 1.0)]
} else {
crate::transition_fx::layers(kind, option, t, aspect, 0)
layers(kind, option, t, 0)
};
v.into_iter().map(Layer::sanitized).filter(|l| l.alpha > 0.0 && l.fade.iter().any(|a| *a > 0.0)).collect()
v.into_iter().map(Layer::sanitized).filter(|l| l.alpha > 0.0).collect()
}
/// Does `kind` animate the slides' backgrounds and contents separately (PowerPoint's Dynamic
/// Content transitions and Reveal)? Then the frame uses [`Source::OldBack`] & co.
pub fn uses_slide_parts(kind: &str, option: &str) -> bool {
fn crossfade(t: f64) -> Vec<Layer> {
vec![Layer::full(Source::Old, 1.0), Layer::full(Source::New, t)]
}
const RANDOM_KINDS: &[&str] = &[
"fade",
"push",
"wipe",
"split",
"reveal",
"randomBar",
"shape",
"uncover",
"cover",
"fallOver",
"drape",
"curtains",
"wind",
"prestige",
"fracture",
"crush",
"peelOff",
"pageCurlDouble",
"airplane",
"origami",
"dissolve",
"checker",
"blinds",
"clock",
"ripple",
"honeycomb",
"glitter",
"vortex",
"shred",
"switch",
"flip",
"gallery",
"cube",
"doors",
"box",
"comb",
"zoom",
"pan",
"ferris",
"conveyor",
"rotate",
"window",
"orbit",
"flythrough",
];
fn layers(kind: &str, option: &str, t: f64, depth: u32) -> Vec<Layer> {
use Source::{Black, New, Old, White};
let o = option;
let s = smooth(t);
match kind {
"pan" | "ferris" | "conveyor" | "rotate" | "window" | "orbit" | "flythrough" => true,
"reveal" => !option.starts_with("black"),
_ => false,
"none" => vec![Layer::full(New, 1.0)],
"cut" => {
if o == "throughBlack" && t < 0.5 {
vec![Layer::full(Black, 1.0)]
} else {
vec![Layer::full(New, 1.0)]
}
}
"fade" if o == "throughBlack" => {
if t < 0.5 {
vec![Layer::full(Black, 1.0), Layer::full(Old, 1.0 - 2.0 * t)]
} else {
vec![Layer::full(Black, 1.0), Layer::full(New, 2.0 * t - 1.0)]
}
}
"fade" | "morph" => crossfade(t),
"push" | "pan" => {
let (dx, dy) = dir(o, (0.0, -1.0));
vec![moved(Old, dx * s, dy * s, 1.0), moved(New, dx * (s - 1.0), dy * (s - 1.0), 1.0)]
}
"uncover" => {
let (dx, dy) = dir(o, (-1.0, 0.0));
vec![Layer::full(New, 1.0), moved(Old, dx * s, dy * s, 1.0)]
}
"cover" => {
let (dx, dy) = dir(o, (-1.0, 0.0));
vec![Layer::full(Old, 1.0), moved(New, dx * (s - 1.0), dy * (s - 1.0), 1.0)]
}
"wipe" => wipe(o, t),
"split" => {
let horz = o.starts_with("horz");
let mut v = vec![Layer::full(Old, 1.0)];
let rects: Vec<R> = if o.ends_with("In") {
vec![[0.0, 0.0, s / 2.0, 1.0], [1.0 - s / 2.0, 0.0, 1.0, 1.0]]
} else {
vec![[0.5 - s / 2.0, 0.0, 0.5 + s / 2.0, 1.0]]
};
for r in rects {
v.push(Layer::inplace(New, map_rect(r, false, false, horz), 1.0));
}
v
}
"reveal" => {
let dx = if o.ends_with("Right") { 1.0 } else { -1.0 };
if o.starts_with("black") {
if t < 0.5 {
vec![Layer::full(Black, 1.0), moved(Old, dx * t * 0.4, 0.0, 1.0 - 2.0 * t)]
} else {
vec![Layer::full(Black, 1.0), moved(New, -dx * (1.0 - t) * 0.2, 0.0, 2.0 * t - 1.0)]
}
} else {
vec![Layer::full(New, 1.0), moved(Old, dx * s * 0.6, 0.0, 1.0 - t)]
}
}
"randomBar" => {
let horz = o == "horz";
let n = 48;
let mut v = vec![Layer::full(Old, 1.0)];
for i in 0..n {
if t > rnd(i as u64 + 17) * 0.98 {
let r = [i as f64 / n as f64, 0.0, (i + 1) as f64 / n as f64, 1.0];
v.push(Layer::inplace(New, map_rect(r, false, false, horz), 1.0));
}
}
v
}
"shape" => {
let form = match o {
"circle" | "diamond" | "plus" => o,
_ => "box",
};
let inward = o == "in";
if inward {
let mut v = vec![Layer::full(New, 1.0)];
v.extend(shape_form(Old, form, 1.0 - s));
v
} else {
let mut v = vec![Layer::full(Old, 1.0)];
v.extend(shape_form(New, form, s));
v
}
}
"flash" => {
if t < 0.5 {
vec![Layer::full(Old, 1.0), Layer::full(White, (2.0 * t).min(1.0))]
} else {
vec![Layer::full(New, 1.0), Layer::full(White, 2.0 - 2.0 * t)]
}
}
"fallOver" => {
let sg = if o == "r" { 1.0 } else { -1.0 };
let a = t * t * PI / 2.0;
let top = 1.0 - a.cos();
let ins = 0.12 * a.sin();
let sh = sg * 0.15 * a.sin();
let q = [[ins + sh, top], [1.0 - ins + sh, top], [1.0, 1.0], [0.0, 1.0]];
vec![Layer::full(New, 1.0), Layer::quad(Old, FULL, q, 1.0 - t.powi(3))]
}
"drape" => {
let k = t * t;
let q = [[0.0, 0.0], [1.0 - 0.3 * k, k], [1.0 - 0.3 * k, 1.0 + k], [0.0, 1.0]];
let q = if o == "r" { mirror_q(q) } else { q };
vec![Layer::full(New, 1.0), Layer::quad(Old, FULL, q, 1.0 - k)]
}
"curtains" => {
let w = 0.5 * (1.0 - s);
let lq = [[0.0, 0.0], [w, 0.12 * s], [w, 1.0 - 0.12 * s], [0.0, 1.0]];
let rq = [[1.0 - w, 0.12 * s], [1.0, 0.0], [1.0, 1.0], [1.0 - w, 1.0 - 0.12 * s]];
vec![
scaled(New, 0.9 + 0.1 * s, 0.5, 0.5, 0.0, 0.0, 1.0),
Layer::quad(Old, [0.0, 0.0, 0.5, 1.0], lq, 1.0),
Layer::quad(Old, [0.5, 0.0, 1.0, 1.0], rq, 1.0),
]
}
"wind" => {
let d = if o == "r" { 1.0 } else { -1.0 };
let r = offset(FULL, d * 1.2 * s, -0.1 * s);
let q = [[r[0] + d * 0.2 * s, r[1]], [r[2] + d * 0.2 * s, r[1]], [r[2], r[3]], [r[0], r[3]]];
vec![moved(New, -d * 0.3 * (1.0 - s), 0.0, smooth((t * 1.5).min(1.0))), Layer::quad(Old, FULL, q, 1.0 - t)]
}
"prestige" => vec![scaled(Old, 1.0 - 0.3 * s, 0.5, 0.5, 0.0, 0.2 * s, 1.0 - t), scaled(New, 0.7 + 0.3 * s, 0.5, 0.5, 0.0, 0.0, s)],
"fracture" => {
let mut v = vec![Layer::full(New, 1.0)];
for (c, r, cell) in grid(8, 6) {
let i = (r * 8 + c) as u64;
let q = ramp(t, rnd(i + 101) * 0.5, 0.5);
let cc = center(cell);
let (dx, dy) = ((cc[0] - 0.5) * 1.5 * q, (cc[1] - 0.5) * 1.5 * q + 0.5 * q * q);
let quad = rot_quad(corners(offset(cell, dx, dy)), [cc[0] + dx, cc[1] + dy], (rnd(i + 7) - 0.5) * 180.0 * q);
v.push(Layer::quad(Old, cell, quad, 1.0 - q));
}
v
}
"crush" => {
let mut v = vec![Layer::full(New, 1.0)];
for (c, r, cell) in grid(4, 4) {
let i = (r * 4 + c) as u64;
let cc = center(cell);
let k = 1.0 - s;
let pos = [0.5 + (cc[0] - 0.5) * k, 0.5 + (cc[1] - 0.5) * k];
let half = scale_rect(cell, k * (0.8 + 0.2 * rnd(i + 3)));
let half = offset(half, pos[0] - cc[0], pos[1] - cc[1]);
let quad = rot_quad(corners(half), pos, (rnd(i + 5) - 0.5) * 60.0 * s);
v.push(Layer::quad(Old, cell, quad, 1.0 - t * t));
}
v
}
"peelOff" => {
let mut v = vec![Layer::full(New, 1.0)];
v.extend(peel(Old, [0.0, 0.0, 1.0, 1.0], s, o == "r"));
v
}
"pageCurlDouble" => {
let mut v = vec![Layer::full(New, 1.0)];
let left_first = o != "r";
v.extend(peel(Old, [0.0, 0.0, 0.5, 1.0], s, !left_first));
v.extend(peel(Old, [0.5, 0.0, 1.0, 1.0], s, left_first));
v
}
"airplane" => {
let d = if o == "r" { 1.0 } else { -1.0 };
let k = 1.0 - 0.8 * s;
let r = offset(scale_rect(FULL, k), d * 1.2 * s * s, -0.5 * s * s);
let q = persp_h(r, if d > 0.0 { 0.3 * s } else { 0.0 }, if d > 0.0 { 0.0 } else { 0.3 * s });
vec![Layer::full(New, 1.0), Layer::quad(Old, FULL, q, 1.0 - t * t)]
}
"origami" => {
let d = if o == "r" { 1.0 } else { -1.0 };
let mut v = vec![Layer::full(New, 1.0)];
if t < 0.5 {
let f = t * 2.0;
let w = 0.5 * (1.0 - 0.8 * f);
v.push(Layer::quad(Old, [0.0, 0.0, 0.5, 1.0], persp_h([0.5 - w, 0.0, 0.5, 1.0], 0.15 * f, 0.0), 1.0));
v.push(Layer::quad(Old, [0.5, 0.0, 1.0, 1.0], persp_h([0.5, 0.0, 0.5 + w, 1.0], 0.0, 0.15 * f), 1.0));
} else {
let f = (t - 0.5) * 2.0;
let r = offset(scale_rect([0.4, 0.0, 0.6, 1.0], 1.0 - 0.6 * f), d * f * 0.8, -0.3 * f);
v.push(Layer::quad(Old, FULL, persp_v(r, 0.1, 0.0), 1.0 - f));
}
v
}
"dissolve" => {
let mut v = vec![Layer::full(Old, 1.0)];
for (c, r, cell) in grid(32, 18) {
if t > rnd((r * 32 + c) as u64 + 991) * 0.98 {
v.push(Layer::inplace(New, cell, 1.0));
}
}
v
}
"checker" => {
let vert = o == "vert";
let (n, m) = (10usize, 8usize);
let mut v = vec![Layer::full(Old, 1.0)];
for (c, r, cell) in grid(n, m) {
let across = if vert { c } else { r };
let f = (t * 2.0 - (across % 2) as f64 * 0.5).clamp(0.0, 1.0);
if f <= 0.0 {
continue;
}
let rc = if vert {
[cell[0], cell[1], cell[2], cell[1] + (cell[3] - cell[1]) * f]
} else {
[cell[0], cell[1], cell[0] + (cell[2] - cell[0]) * f, cell[3]]
};
v.push(Layer::inplace(New, rc, 1.0));
}
v
}
"blinds" => {
let horz = o == "horz";
let n = 8;
let mut v = vec![Layer::full(Old, 1.0)];
for i in 0..n {
let x0 = i as f64 / n as f64;
let r = [x0, 0.0, x0 + s / n as f64, 1.0];
v.push(Layer::inplace(New, map_rect(r, false, false, horz), 1.0));
}
v
}
"clock" => clock(o, s),
"ripple" => {
let origin = match o {
"lu" => [0.0, 0.0],
"ru" => [1.0, 0.0],
"ld" => [0.0, 1.0],
"rd" => [1.0, 1.0],
_ => [0.5, 0.5],
};
let maxd = if origin == [0.5, 0.5] { 0.71 } else { 1.42 };
let mut v = vec![Layer::full(Old, 1.0)];
for (_, _, cell) in grid(24, 14) {
let cc = center(cell);
let d = ((cc[0] - origin[0]).powi(2) + (cc[1] - origin[1]).powi(2)).sqrt() / maxd;
let a = ramp(t, d.min(1.0), 0.3);
if a > 0.0 {
let sc = 1.0 + 0.15 * (a * PI).sin();
v.push(Layer::rect(New, cell, scale_rect(cell, sc), a));
}
}
v
}
"honeycomb" => {
let (cols, rows) = (12usize, 8usize);
let mut v = vec![Layer::full(Old, 1.0)];
for c in 0..cols {
let odd = c % 2 == 1;
let extra = if odd { 1 } else { 0 };
for r in 0..rows + extra {
let y0 = (r as f64 - if odd { 0.5 } else { 0.0 }) / rows as f64;
let cell = [c as f64 / cols as f64, y0.max(0.0), (c + 1) as f64 / cols as f64, (y0 + 1.0 / rows as f64).min(1.0)];
let a = ramp(t, rnd((c * 64 + r) as u64 + 4242), 0.35);
if a > 0.0 {
v.push(Layer::rect(New, cell, scale_rect(cell, 0.3 + 0.7 * a), a));
}
}
}
v
}
"glitter" => {
let (dx, dy) = dir(o, (-1.0, 0.0));
let mut v = vec![Layer::full(Old, 1.0)];
for (c, r, cell) in grid(20, 12) {
let cc = center(cell);
let grad = if dx < 0.0 {
1.0 - cc[0]
} else if dx > 0.0 {
cc[0]
} else if dy < 0.0 {
1.0 - cc[1]
} else {
cc[1]
};
let order = 0.6 * grad + 0.4 * rnd((r * 20 + c) as u64 + 77);
let a = ramp(t, order, 0.25);
if a > 0.0 {
let quad = rot_quad(corners(cell), cc, (1.0 - a) * 90.0);
v.push(Layer::quad(New, cell, quad, a));
}
}
v
}
"vortex" => {
let (dx, dy) = dir(o, (-1.0, 0.0));
let mut v = vec![Layer::full(New, 1.0)];
for (c, r, cell) in grid(16, 9) {
let i = (r * 16 + c) as u64;
let cc = center(cell);
let grad = 0.5 + 0.5 * ((cc[0] - 0.5) * -dx + (cc[1] - 0.5) * -dy);
let q = ramp(t, 0.5 * grad + 0.5 * rnd(i + 31), 0.4);
let ang = q * 2.0 * PI + rnd(i) * PI;
let rad = q * 1.2;
let (ox, oy) = (dx * q * 0.8 + rad * ang.cos() * 0.3, dy * q * 0.8 + rad * ang.sin() * 0.3);
let pos = [cc[0] + ox, cc[1] + oy];
let quad = rot_quad(corners(offset(scale_rect(cell, 1.0 - 0.5 * q), ox, oy)), pos, q * 360.0);
v.push(Layer::quad(Old, cell, quad, 1.0 - q));
}
v
}
"shred" => {
let mut v = vec![Layer::full(New, 1.0)];
if o == "particles" {
for (c, r, cell) in grid(24, 14) {
let i = (r * 24 + c) as u64;
let q = ramp(t, rnd(i + 555) * 0.6 + 0.4 * (1.0 - center(cell)[1]), 0.4);
let dy = q * q * 1.2;
let dx = (rnd(i + 9) - 0.5) * 0.3 * q;
v.push(Layer::rect(Old, cell, offset(scale_rect(cell, 1.0 - 0.6 * q), dx, dy), 1.0 - q));
}
} else {
let n = 16;
for i in 0..n {
let x0 = i as f64 / n as f64;
let x1 = (i + 1) as f64 / n as f64;
let q = ramp(t, i as f64 / n as f64 * 0.3 + 0.1 * rnd(i as u64), 0.7);
let dy = if i % 2 == 0 { 1.1 * q * q } else { -1.1 * q * q };
v.push(Layer::rect(Old, [x0, 0.0, x1, 1.0], [x0, dy, x1, 1.0 + dy], 1.0));
}
}
v
}
"switch" => {
let d = if o == "r" { 1.0 } else { -1.0 };
let k = (t * PI).sin();
let old = Layer::quad(
Old,
FULL,
persp_h(
offset(scale_rect(FULL, 1.0 - 0.25 * t), d * 0.45 * k, 0.0),
if d > 0.0 { 0.0 } else { 0.08 * k },
if d > 0.0 { 0.08 * k } else { 0.0 },
),
1.0,
);
let new = Layer::quad(
New,
FULL,
persp_h(
offset(scale_rect(FULL, 0.75 + 0.25 * t), -d * 0.45 * k, 0.0),
if d > 0.0 { 0.08 * k } else { 0.0 },
if d > 0.0 { 0.0 } else { 0.08 * k },
),
1.0,
);
if t < 0.5 { vec![new, old] } else { vec![old, new] }
}
"flip" => {
let a = PI * s;
let w = a.cos().abs();
let k = 0.1 * a.sin();
let r = [0.5 - w / 2.0, 0.0, 0.5 + w / 2.0, 1.0];
let right = o != "l";
if t < 0.5 {
let q = if right { persp_h(r, -k / 2.0, k) } else { persp_h(r, k, -k / 2.0) };
vec![Layer::quad(Old, FULL, q, 1.0)]
} else {
let q = if right { persp_h(r, k, -k / 2.0) } else { persp_h(r, -k / 2.0, k) };
vec![Layer::quad(New, FULL, q, 1.0)]
}
}
"gallery" | "conveyor" => {
let d = if o == "r" { 1.0 } else { -1.0 };
let k = (s * PI).sin();
let sc = 1.0 - if kind == "gallery" { 0.25 } else { 0.1 } * k;
let gap = if kind == "gallery" { 1.15 } else { 1.05 };
let old = offset(scale_rect(FULL, sc), d * s * gap, 0.0);
let new = offset(scale_rect(FULL, sc), d * (s - 1.0) * gap, 0.0);
let p = 0.08 * k;
vec![
Layer::quad(Old, FULL, if d > 0.0 { persp_h(old, 0.0, p) } else { persp_h(old, p, 0.0) }, 1.0),
Layer::quad(New, FULL, if d > 0.0 { persp_h(new, p, 0.0) } else { persp_h(new, 0.0, p) }, 1.0),
]
}
"cube" | "box" | "rotate" => {
let (dx, dy) = dir(o, (-1.0, 0.0));
let vertical = dy != 0.0 && dx == 0.0;
let neg = if vertical { dy < 0.0 } else { dx < 0.0 };
let k = (s * PI).sin();
let (far_old, far_new, shared) = match kind {
"cube" => (0.18 * s, 0.18 * (1.0 - s), 0.05 * k),
"box" => (0.0, 0.0, 0.18 * k),
_ => (0.25 * s, 0.25 * (1.0 - s), 0.0),
};
// Canonical: moving toward -x; old on the left [0, 1-s], new on the right [1-s, 1].
let split = 1.0 - s;
let (old_q, new_q) = if kind == "rotate" {
if t < 0.5 {
(Some(canon_q([0.0, 0.0, (1.0 - 2.0 * t).max(0.0), 1.0], far_old, 0.0)), None)
} else {
(None, Some(canon_q([1.0 - (2.0 * t - 1.0), 0.0, 1.0, 1.0], 0.0, far_new)))
}
} else {
(Some(canon_q([0.0, 0.0, split, 1.0], far_old, shared)), Some(canon_q([split, 0.0, 1.0, 1.0], shared, far_new)))
};
let fix = |q: [[f64; 2]; 4]| -> [[f64; 2]; 4] {
let q = if neg { q } else { mirror_q(q) };
if vertical { swap_q(q) } else { q }
};
let mut v = vec![Layer::full(Black, 1.0)];
if let Some(q) = old_q {
v.push(Layer::quad(Old, FULL, fix(q), 1.0));
}
if let Some(q) = new_q {
v.push(Layer::quad(New, FULL, fix(q), 1.0));
}
v
}
"doors" | "window" => {
let horz = o == "horz";
let (zoom0, persp) = if kind == "doors" { (0.85, 0.1) } else { (0.6, 0.2) };
let w = 0.5 * (1.0 - s);
let k = persp * s;
let left = [[0.0, 0.0], [w, -k], [w, 1.0 + k], [0.0, 1.0]];
let right = [[1.0 - w, -k], [1.0, 0.0], [1.0, 1.0], [1.0 - w, 1.0 + k]];
let (l, r) = if horz { (swap_q(left), swap_q(right)) } else { (left, right) };
let (sl, sr) = if horz { ([0.0, 0.0, 1.0, 0.5], [0.0, 0.5, 1.0, 1.0]) } else { ([0.0, 0.0, 0.5, 1.0], [0.5, 0.0, 1.0, 1.0]) };
vec![scaled(New, zoom0 + (1.0 - zoom0) * s, 0.5, 0.5, 0.0, 0.0, s.max(0.2)), Layer::quad(Old, sl, l, 1.0), Layer::quad(Old, sr, r, 1.0)]
}
"comb" => {
let vert = o == "vert";
let n = 8;
let mut v = Vec::new();
for i in 0..n {
let a = i as f64 / n as f64;
let b = (i + 1) as f64 / n as f64;
let d = if i % 2 == 0 { 1.0 } else { -1.0 };
let band = if vert { [a, 0.0, b, 1.0] } else { [0.0, a, 1.0, b] };
let (ox, oy) = if vert { (0.0, d * s) } else { (d * s, 0.0) };
let (nx, ny) = if vert { (0.0, -d * (1.0 - s)) } else { (-d * (1.0 - s), 0.0) };
v.push(Layer::rect(Old, band, offset(band, ox, oy), 1.0));
v.push(Layer::rect(New, band, offset(band, nx, ny), 1.0));
}
v
}
"zoom" => {
if o == "out" {
vec![scaled(New, 1.5 - 0.5 * s, 0.5, 0.5, 0.0, 0.0, s), scaled(Old, 1.0 - 0.7 * s, 0.5, 0.5, 0.0, 0.0, 1.0 - t)]
} else {
vec![scaled(Old, 1.0 + s, 0.5, 0.5, 0.0, 0.0, 1.0 - t), scaled(New, s.max(0.01), 0.5, 0.5, 0.0, 0.0, s)]
}
}
"orbit" => {
let (dx, dy) = dir(o, (-1.0, 0.0));
let k = (s * PI).sin();
let old = scaled(Old, 1.0 - 0.4 * k, 0.5, 0.5, dx * s + dy.abs() * 0.15 * k, dy * s + dx.abs() * 0.15 * k, 1.0 - 0.5 * s);
let new = scaled(New, 1.0 - 0.4 * k, 0.5, 0.5, dx * (s - 1.0) - dy.abs() * 0.15 * k, dy * (s - 1.0) - dx.abs() * 0.15 * k, 0.5 + 0.5 * s);
if t < 0.5 { vec![new, old] } else { vec![old, new] }
}
"flythrough" => {
let bounce = o.ends_with("Bounce");
let ns = |base: f64| if bounce { base + 0.08 * (s * PI).sin() } else { base };
if o.starts_with("out") {
vec![scaled(Old, 1.0 - 0.5 * s, 0.5, 0.5, 0.0, 0.0, 1.0 - t), scaled(New, ns(1.5 - 0.5 * s), 0.5, 0.5, 0.0, 0.0, s)]
} else {
vec![scaled(New, ns(0.5 + 0.5 * s), 0.5, 0.5, 0.0, 0.0, s), scaled(Old, 1.0 + 1.5 * s, 0.5, 0.5, 0.0, 0.0, 1.0 - t)]
}
}
"ferris" => {
let d = if o == "r" { 1.0 } else { -1.0 };
let pivot = [0.5, 2.5];
let a = 50.0 * s * d;
let oq = rot_quad(corners(FULL), pivot, a);
let nq = rot_quad(corners(FULL), pivot, a - 50.0 * d);
vec![Layer::quad(Old, FULL, oq, 1.0), Layer::quad(New, FULL, nq, 1.0)]
}
"random" if depth == 0 => {
let h = option.bytes().fold(0x51ED_u64, |h, b| hash64(h ^ b as u64));
let k = RANDOM_KINDS.get((h % RANDOM_KINDS.len() as u64) as usize).copied().unwrap_or("fade");
let opt = deckcraft_model::anim::TRANSITIONS.iter().find(|x| x.0 == k).and_then(|x| x.4.first().copied()).unwrap_or("");
layers(k, opt, t, depth + 1)
}
_ => crossfade(t),
}
}
fn mirror_q(q: [[f64; 2]; 4]) -> [[f64; 2]; 4] {
// Mirror x and keep the tl, tr, br, bl order (swap left/right corners).
let m = |p: [f64; 2]| [1.0 - p[0], p[1]];
[m(q[1]), m(q[0]), m(q[3]), m(q[2])]
}
fn swap_q(q: [[f64; 2]; 4]) -> [[f64; 2]; 4] {
// Transpose x/y; corners reordered so tl, tr, br, bl still map to the source's corners.
let s = |p: [f64; 2]| [p[1], p[0]];
[s(q[0]), s(q[3]), s(q[2]), s(q[1])]
}
fn canon_q(r: R, left_inset: f64, right_inset: f64) -> [[f64; 2]; 4] {
persp_h(r, left_inset, right_inset)
}
fn wipe(o: &str, t: f64) -> Vec<Layer> {
let mut v = vec![Layer::full(Source::Old, 1.0)];
let diag = o.len() == 2;
if diag {
// Diagonal: columns revealed by a slanted edge.
let (mx, my) = (o.contains('l'), o.contains('u'));
let n = 32;
for i in 0..n {
let x0 = i as f64 / n as f64;
let x1 = (i + 1) as f64 / n as f64;
let h = (2.0 * t - (x0 + x1) / 2.0).clamp(0.0, 1.0);
if h > 0.0 {
v.push(Layer::inplace(Source::New, map_rect([x0, 0.0, x1, h], mx, my, false), 1.0));
}
}
return v;
}
let (mx, swap) = match o {
"l" => (true, false),
"d" => (false, true),
"u" => (true, true),
_ => (false, false),
};
let soft = 0.15;
let e = t * (1.0 + soft);
let solid = (e - soft).clamp(0.0, 1.0);
if solid > 0.0 {
v.push(Layer::inplace(Source::New, map_rect([0.0, 0.0, solid, 1.0], mx, false, swap), 1.0));
}
let n = 6;
for k in 0..n {
let a = e - soft + soft * k as f64 / n as f64;
let b = e - soft + soft * (k + 1) as f64 / n as f64;
let (a, b) = (a.clamp(0.0, 1.0), b.clamp(0.0, 1.0));
if b > a {
let alpha = 1.0 - (k as f64 + 0.5) / n as f64;
v.push(Layer::inplace(Source::New, map_rect([a, 0.0, b, 1.0], mx, false, swap), alpha));
}
}
v
}
/// A centred shape of the source at size `f` (0 = nothing, 1 = covers the slide), as strips.
fn shape_form(src: Source, form: &str, f: f64) -> Vec<Layer> {
let f = f.clamp(0.0, 1.0);
if f <= 0.0 {
return vec![];
}
match form {
"plus" => {
let h = f / 2.0;
vec![Layer::inplace(src, [0.0, 0.5 - h, 1.0, 0.5 + h], 1.0), Layer::inplace(src, [0.5 - h, 0.0, 0.5 + h, 1.0], 1.0)]
}
"circle" | "diamond" => {
let n = 40;
let r = if form == "circle" { f * 0.75 } else { f * 1.02 };
let mut v = Vec::new();
for i in 0..n {
let y0 = i as f64 / n as f64;
let y1 = (i + 1) as f64 / n as f64;
let dy = ((y0 + y1) / 2.0 - 0.5).abs();
let half = if form == "circle" { if r > dy { (r * r - dy * dy).sqrt() } else { 0.0 } } else { r - dy };
if half > 0.0 {
let half = half.min(0.5);
v.push(Layer::inplace(src, [0.5 - half, y0, 0.5 + half, y1], 1.0));
}
}
v
}
_ => vec![Layer::inplace(src, scale_rect(FULL, f), 1.0)],
}
}
/// A peeling page: the part of `area` not yet peeled stays, the peeled part shows as a mirrored flap.
fn peel(src: Source, area: R, s: f64, toward_right: bool) -> Vec<Layer> {
let w = area[2] - area[0];
let p = s * w;
if toward_right {
let edge = area[0] + p;
let stay = [edge, area[1], area[2], area[3]];
let flap_src = [area[0], area[1], edge, area[3]];
let x2 = edge + p;
let flap = Layer {
source: src,
src: flap_src,
quad: [[x2, area[1]], [edge, area[1]], [edge, area[3]], [x2, area[3]]],
uv: corners(flap_src),
alpha: 0.85,
};
vec![Layer::inplace(src, stay, 1.0), flap]
} else {
let edge = area[2] - p;
let stay = [area[0], area[1], edge, area[3]];
let flap_src = [edge, area[1], area[2], area[3]];
let x2 = edge - p;
let flap = Layer {
source: src,
src: flap_src,
quad: [[edge, area[1]], [x2, area[1]], [x2, area[3]], [edge, area[3]]],
uv: corners(flap_src),
alpha: 0.85,
};
vec![Layer::inplace(src, stay, 1.0), flap]
}
}
/// Point on the unit square's boundary seen from the centre at angle `a` (radians, clockwise from
/// 12 o'clock).
fn boundary(a: f64) -> [f64; 2] {
let (dx, dy) = (a.sin(), -a.cos());
let m = dx.abs().max(dy.abs()).max(1e-9);
[0.5 + 0.5 * dx / m, 0.5 + 0.5 * dy / m]
}
fn clock(o: &str, s: f64) -> Vec<Layer> {
let mut v = vec![Layer::full(Source::Old, 1.0)];
let c = [0.5, 0.5];
let sweep = s * 2.0 * PI;
let (a0, a1) = match o {
"counterClockwise" => (-sweep, 0.0),
"wedge" => (-sweep / 2.0, sweep / 2.0),
_ => (0.0, sweep),
};
let span = a1 - a0;
if span <= 0.0 {
return v;
}
let n = ((span / (PI / 24.0)).ceil() as usize).clamp(1, 96);
let mut angles: Vec<f64> = (0..=n).map(|k| a0 + span * k as f64 / n as f64).collect();
// Square corners inside the sweep, so the fan reaches them.
for k in -8i32..=8 {
let a = PI / 4.0 + k as f64 * PI / 2.0;
if a > a0 && a < a1 {
angles.push(a);
}
}
angles.sort_by(f64::total_cmp);
for w in angles.windows(2) {
if let [x, y] = w
&& y > x
{
v.push(Layer::tri(Source::New, c, boundary(*x), boundary(*y), 1.0));
}
}
v
}
File diff suppressed because it is too large Load Diff
-382
View File
@@ -1,382 +0,0 @@
//! Geometry for transition effects: easing, 3-D cards, opacity fields, polygons.
use std::f64::consts::PI;
use crate::easing::{ease, smooth};
use crate::transition::{FULL, Layer, P, Q, R, Source, corners};
// ---------- easing ----------
/// Smoothstep ease in-out (PowerPoint's fades).
pub(crate) fn ss(x: f64) -> f64 {
smooth(x)
}
/// Quadratic ease in-out: velocity ramps up for the first half and down for the second
/// (PowerPoint's moves: Push, Cover, Uncover, Pan…).
pub(crate) fn q2(x: f64) -> f64 {
ease(x, 0.5, 0.5, 0.0)
}
/// Power ease in-out of degree `n` (2: quadratic, 3: cubic, 4: quartic).
pub(crate) fn pow_inout(x: f64, n: f64) -> f64 {
let x = x.clamp(0.0, 1.0);
if x < 0.5 { 0.5 * (2.0 * x).powf(n) } else { 1.0 - 0.5 * (2.0 - 2.0 * x).powf(n) }
}
/// Quadratic ease-in.
pub(crate) fn ein(x: f64) -> f64 {
let x = x.clamp(0.0, 1.0);
x * x
}
/// Quadratic ease-out.
pub(crate) fn eout(x: f64) -> f64 {
let x = 1.0 - x.clamp(0.0, 1.0);
1.0 - x * x
}
/// Progress through the window [a, b] of t, clamped to 0..1.
pub(crate) fn win(t: f64, a: f64, b: f64) -> f64 {
if b <= a {
return if t >= b { 1.0 } else { 0.0 };
}
((t - a) / (b - a)).clamp(0.0, 1.0)
}
// ---------- randomness ----------
pub(crate) fn hash64(mut x: u64) -> u64 {
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^ (x >> 31)
}
/// Deterministic pseudo-random value in [0, 1).
pub(crate) fn rnd(i: u64) -> f64 {
(hash64(i) >> 11) as f64 / (1u64 << 53) as f64
}
// ---------- 2-D ----------
pub(crate) fn offset(r: R, dx: f64, dy: f64) -> R {
[r[0] + dx, r[1] + dy, r[2] + dx, r[3] + dy]
}
pub(crate) fn center(r: R) -> P {
[(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]
}
pub(crate) fn scale_rect(r: R, s: f64) -> R {
scale_rect_about(r, s, center(r))
}
pub(crate) fn scale_rect_about(r: R, s: f64, c: P) -> R {
[c[0] + (r[0] - c[0]) * s, c[1] + (r[1] - c[1]) * s, c[0] + (r[2] - c[0]) * s, c[1] + (r[3] - c[1]) * s]
}
/// The whole source moved by (dx, dy).
pub(crate) fn moved(source: Source, dx: f64, dy: f64, alpha: f64) -> Layer {
Layer::rect(source, FULL, offset(FULL, dx, dy), alpha)
}
/// The whole source scaled by `s` about (cx, cy) and moved.
pub(crate) fn scaled(source: Source, s: f64, cx: f64, cy: f64, dx: f64, dy: f64, alpha: f64) -> Layer {
Layer::rect(source, FULL, offset(scale_rect_about(FULL, s, [cx, cy]), dx, dy), alpha)
}
/// Rotate a point about a pivot by `deg` (clockwise on screen), in a slide `a` wide per unit of
/// height, so angles and shapes stay true.
pub(crate) fn rot(p: P, c: P, deg: f64, a: f64) -> P {
let (s, co) = deg.to_radians().sin_cos();
let (x, y) = ((p[0] - c[0]) * a, p[1] - c[1]);
[c[0] + (x * co - y * s) / a, c[1] + x * s + y * co]
}
pub(crate) fn rot_quad(q: Q, c: P, deg: f64, a: f64) -> Q {
[rot(q[0], c, deg, a), rot(q[1], c, deg, a), rot(q[2], c, deg, a), rot(q[3], c, deg, a)]
}
/// Motion direction of an option: l, r, u, d and diagonals.
pub(crate) fn dir(opt: &str, default: (f64, f64)) -> (f64, f64) {
let mut d = (0.0, 0.0);
if opt.contains('l') {
d.0 = -1.0;
}
if opt.contains('r') {
d.0 = 1.0;
}
if opt.contains('u') {
d.1 = -1.0;
}
if opt.contains('d') {
d.1 = 1.0;
}
if d == (0.0, 0.0) { default } else { d }
}
/// A rectangle with a soft border `f` wide (slide units) fading out to nothing: the rectangle at
/// full opacity, four edge ramps and four corner ramps. `src` maps onto `dst`; the border samples
/// the texture's edge.
pub(crate) fn soft_rect(source: Source, src: R, dst: R, f: f64, alpha: f64) -> Vec<Layer> {
let mut v = vec![Layer::rect(source, src, dst, alpha)];
if f <= 1e-6 {
return v;
}
let (l, t, r, b) = (dst[0], dst[1], dst[2], dst[3]);
let (fx, fy) = (f, f * 16.0 / 9.0);
let uv_at = |x: f64, y: f64| -> P {
let u = if r > l { src[0] + (x.clamp(l, r) - l) / (r - l) * (src[2] - src[0]) } else { src[0] };
let w = if b > t { src[1] + (y.clamp(t, b) - t) / (b - t) * (src[3] - src[1]) } else { src[1] };
[u, w]
};
let mut q = |pts: Q, fade: [f64; 4]| {
let uv = pts.map(|p| uv_at(p[0], p[1]));
let xs = uv.map(|p| p[0]);
let ys = uv.map(|p| p[1]);
let mn = |a: [f64; 4]| a.iter().copied().fold(f64::INFINITY, f64::min);
let mx = |a: [f64; 4]| a.iter().copied().fold(f64::NEG_INFINITY, f64::max);
v.push(Layer { source, src: [mn(xs), mn(ys), mx(xs), mx(ys)], quad: pts, uv, alpha, fade });
};
q([[l, t - fy], [r, t - fy], [r, t], [l, t]], [0.0, 0.0, 1.0, 1.0]);
q([[l, b], [r, b], [r, b + fy], [l, b + fy]], [1.0, 1.0, 0.0, 0.0]);
q([[l - fx, t], [l, t], [l, b], [l - fx, b]], [0.0, 1.0, 1.0, 0.0]);
q([[r, t], [r + fx, t], [r + fx, b], [r, b]], [1.0, 0.0, 0.0, 1.0]);
q([[l - fx, t - fy], [l, t - fy], [l, t], [l - fx, t]], [0.0, 0.0, 1.0, 0.0]);
q([[r, t - fy], [r + fx, t - fy], [r + fx, t], [r, t]], [0.0, 0.0, 0.0, 1.0]);
q([[r, b], [r + fx, b], [r + fx, b + fy], [r, b + fy]], [1.0, 0.0, 0.0, 0.0]);
q([[l - fx, b], [l, b], [l, b + fy], [l - fx, b + fy]], [0.0, 1.0, 0.0, 0.0]);
v
}
// ---------- opacity fields ----------
/// The source shown in place through an opacity field `f(x, y)` (0..1) sampled on an `n` × `m`
/// grid: each cell is a quad with its corners' opacities. Cells with nothing to show are left out
/// and runs of fully opaque cells merge, so most frames stay small.
pub(crate) fn field(source: Source, n: usize, m: usize, f: &dyn Fn(f64, f64) -> f64) -> Vec<Layer> {
let (n, m) = (n.clamp(1, 256), m.clamp(1, 256));
let mut vals = vec![0.0; (n + 1) * (m + 1)];
for j in 0..=m {
for i in 0..=n {
let v = f(i as f64 / n as f64, j as f64 / m as f64);
if let Some(x) = vals.get_mut(j * (n + 1) + i) {
*x = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
}
}
}
let at = |i: usize, j: usize| vals.get(j * (n + 1) + i).copied().unwrap_or(0.0);
let mut out = Vec::new();
for j in 0..m {
let (y0, y1) = (j as f64 / m as f64, (j + 1) as f64 / m as f64);
let mut run: Option<usize> = None;
for i in 0..=n {
let full = i < n && at(i, j) >= 1.0 && at(i + 1, j) >= 1.0 && at(i, j + 1) >= 1.0 && at(i + 1, j + 1) >= 1.0;
if full {
run.get_or_insert(i);
continue;
}
if let Some(s) = run.take() {
out.push(Layer::inplace(source, [s as f64 / n as f64, y0, i as f64 / n as f64, y1], 1.0));
}
if i == n {
break;
}
let c = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
if c.iter().all(|v| *v <= 0.0) {
continue;
}
out.push(Layer::inplace(source, [i as f64 / n as f64, y0, (i + 1) as f64 / n as f64, y1], 1.0).faded(c));
}
}
out
}
/// Opacity of a soft edge at position `p` when the edge's middle is at `c` and it ramps over `w`.
pub(crate) fn edge(c: f64, p: f64, w: f64) -> f64 {
if w <= 1e-9 {
return if p <= c { 1.0 } else { 0.0 };
}
((c - p) / w + 0.5).clamp(0.0, 1.0)
}
/// Point on the unit square's boundary seen from its centre at angle `ang` (radians, clockwise
/// from 12 o'clock, measured on a slide `a` wide per unit of height).
pub(crate) fn boundary(ang: f64, a: f64) -> P {
let (dx, dy) = (ang.sin() / a, -ang.cos());
let m = (dx.abs() / 0.5).max(dy.abs() / 0.5).max(1e-9);
[0.5 + dx / m, 0.5 + dy / m]
}
/// The source shown in place through an angular opacity field `f(angle)` (radians clockwise from
/// 12 o'clock, 0..2π): a fan of thin wedges from the centre.
pub(crate) fn fan(source: Source, a: f64, steps: usize, f: &dyn Fn(f64) -> f64) -> Vec<Layer> {
let n = steps.clamp(8, 720);
let mut angles: Vec<f64> = (0..=n).map(|k| 2.0 * PI * k as f64 / n as f64).collect();
// The square's corners, so wedges reach them.
for c in [[1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]] {
let ang = ((c[0] - 0.5) * a).atan2(-(c[1] - 0.5));
angles.push(ang.rem_euclid(2.0 * PI));
}
angles.sort_by(f64::total_cmp);
angles.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
let mut out = Vec::new();
let c = [0.5, 0.5];
for w in angles.windows(2) {
let [x, y] = w else { continue };
let (fx, fy) = (f(*x).clamp(0.0, 1.0), f(*y).clamp(0.0, 1.0));
if fx <= 0.0 && fy <= 0.0 {
continue;
}
let (bx, by) = (boundary(*x, a), boundary(*y, a));
out.push(Layer::tri_uv(source, [c, bx, by], [c, bx, by], [(fx + fy) / 2.0, fx, fy], 1.0));
}
out
}
// ---------- polygons ----------
/// Keep the part of a convex polygon where `n · p <= d`.
pub(crate) fn clip(poly: &[P], n: P, d: f64) -> Vec<P> {
let mut out = Vec::with_capacity(poly.len() + 2);
let side = |p: P| n[0] * p[0] + n[1] * p[1] - d;
for (i, p) in poly.iter().enumerate() {
let q = poly.get((i + 1) % poly.len()).copied().unwrap_or(*p);
let (sp, sq) = (side(*p), side(q));
if sp <= 0.0 {
out.push(*p);
}
if (sp < 0.0 && sq > 0.0) || (sp > 0.0 && sq < 0.0) {
let k = sp / (sp - sq);
out.push([p[0] + (q[0] - p[0]) * k, p[1] + (q[1] - p[1]) * k]);
}
}
out
}
/// A convex polygon as triangles: vertices drawn at `map(p)` with texture coordinate `p`.
pub(crate) fn poly_layers(source: Source, poly: &[P], alpha: f64, map: &dyn Fn(P) -> P) -> Vec<Layer> {
let Some(first) = poly.first().copied() else { return vec![] };
poly.windows(2)
.skip(1)
.filter_map(|w| match w {
[b, c] => Some(Layer::tri_uv(source, [map(first), map(*b), map(*c)], [first, *b, *c], [1.0; 3], alpha)),
_ => None,
})
.collect()
}
pub(crate) fn rect_poly(r: R) -> Vec<P> {
corners(r).to_vec()
}
// ---------- 3-D ----------
/// A point in the 3-D scene: x right and y down in slide heights (the slide spans x ∈ [−a/2, a/2],
/// y ∈ [−½, ½] at z = 0), z away from the viewer.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct V3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
pub(crate) fn v3(x: f64, y: f64, z: f64) -> V3 {
V3 { x, y, z }
}
impl V3 {
pub fn add(self, o: V3) -> V3 {
v3(self.x + o.x, self.y + o.y, self.z + o.z)
}
pub fn sub(self, o: V3) -> V3 {
v3(self.x - o.x, self.y - o.y, self.z - o.z)
}
/// Rotate about the vertical axis through `c` (degrees; positive turns the right side away).
pub fn yaw(self, c: V3, deg: f64) -> V3 {
let (s, co) = deg.to_radians().sin_cos();
let p = self.sub(c);
v3(p.x * co - p.z * s, p.y, p.x * s + p.z * co).add(c)
}
/// Rotate about the horizontal axis through `c` (degrees; positive turns the top away).
pub fn pitch(self, c: V3, deg: f64) -> V3 {
let (s, co) = deg.to_radians().sin_cos();
let p = self.sub(c);
v3(p.x, p.y * co + p.z * s, -p.y * s + p.z * co).add(c)
}
/// Rotate in the screen plane about `c` (degrees, clockwise).
pub fn roll(self, c: V3, deg: f64) -> V3 {
let (s, co) = deg.to_radians().sin_cos();
let p = self.sub(c);
v3(p.x * co - p.y * s, p.x * s + p.y * co, p.z).add(c)
}
}
/// A perspective camera looking at the slide plane from `d` slide heights away.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Cam {
pub a: f64,
pub d: f64,
}
impl Cam {
pub fn p(&self, v: V3) -> P {
let k = self.d / (self.d + v.z).max(self.d * 0.02);
[v.x * k / self.a + 0.5, v.y * k + 0.5]
}
/// The 3-D corners (tl, tr, br, bl) of the unit-space rectangle `r` lying on the slide plane.
pub fn rect(&self, r: R) -> [V3; 4] {
corners(r).map(|p| v3((p[0] - 0.5) * self.a, p[1] - 0.5, 0.0))
}
/// The unit-space point of a 3-D point on the slide plane.
pub fn unit(&self, x: f64, y: f64) -> V3 {
v3((x - 0.5) * self.a, y - 0.5, 0.0)
}
pub fn quad(&self, c: [V3; 4]) -> Q {
c.map(|v| self.p(v))
}
}
/// Signed area of a quad (positive: front side facing the viewer).
pub(crate) fn area(q: &Q) -> f64 {
let mut s = 0.0;
for i in 0..4 {
let (a, b) = (q[i], q[(i + 1) % 4]);
s += a[0] * b[1] - b[0] * a[1];
}
s / 2.0
}
/// A card: `src` of the source mapped onto 3-D corners, if it faces the viewer; `shade` (0..1)
/// darkens it. Seen from behind it is left out unless `back` is set (then drawn mirrored).
pub(crate) fn card(cam: &Cam, source: Source, src: R, c: [V3; 4], alpha: f64, shade: f64, back: bool) -> Vec<Layer> {
let q = cam.quad(c);
if !q.iter().all(|p| p[0].is_finite() && p[1].is_finite()) {
return vec![];
}
let front = area(&q) > 0.0;
if !front && !back {
return vec![];
}
let l = Layer::quad(source, src, q, alpha);
let mut v = vec![l];
if shade > 0.001 {
v.push(l.shade(shade));
}
v
}
/// How much a card facing along `n` (unit normal toward the viewer is (0, 0, −1)) is darkened by
/// the light behind the viewer: 0 facing straight on.
pub(crate) fn facing_shade(c: [V3; 4], k: f64) -> f64 {
let u = c[1].sub(c[0]);
let w = c[3].sub(c[0]);
let n = v3(u.y * w.z - u.z * w.y, u.z * w.x - u.x * w.z, u.x * w.y - u.y * w.x);
let len = (n.x * n.x + n.y * n.y + n.z * n.z).sqrt();
if len < 1e-12 {
return 0.0;
}
let cos = (n.z / len).abs();
(k * (1.0 - cos)).clamp(0.0, 1.0)
}
-230
View File
@@ -1,230 +0,0 @@
//! Transition curves and geometry against values measured on PowerPoint's video export
//! (`plan/powerpoint/tools/synth_transitions.ps1`, 2 s transitions, 30 fps).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use deckcraft_model::anim::TRANSITIONS;
use crate::transition::{Layer, Source, transition_frame, transition_layers, uses_slide_parts};
use crate::transition_geom::{edge, pow_inout, q2, ss};
const A: f64 = 16.0 / 9.0;
fn near(a: f64, b: f64, tol: f64) -> bool {
(a - b).abs() <= tol
}
fn of(ls: &[Layer], src: Source) -> Vec<&Layer> {
ls.iter().filter(|l| l.source == src).collect()
}
fn left(l: &Layer) -> f64 {
l.quad.iter().map(|p| p[0]).fold(f64::INFINITY, f64::min)
}
fn top(l: &Layer) -> f64 {
l.quad.iter().map(|p| p[1]).fold(f64::INFINITY, f64::min)
}
#[test]
fn fade_follows_powerpoints_s_curve() {
// Measured share of the new slide in a 2 s Fade at t = 0.25, 0.5, 0.75: 0.155, 0.49, 0.82.
for (t, want) in [(0.25, 0.155), (0.5, 0.49), (0.75, 0.82)] {
let ls = transition_layers("fade", "smoothly", t);
let new = of(&ls, Source::New);
assert!(near(new[0].alpha, want, 0.04), "t={t}: {}", new[0].alpha);
}
// Through black: the old slide is gone to black at the middle, then the new one fades in.
let mid = transition_layers("fade", "throughBlack", 0.5);
assert!(mid.iter().all(|l| l.source == Source::Black));
let q = transition_layers("fade", "throughBlack", 0.25);
assert!(near(of(&q, Source::Old)[0].alpha, 0.5, 0.01));
}
#[test]
fn push_moves_both_slides_with_an_eased_curve() {
for (o, dx, dy) in [("l", -1.0, 0.0), ("r", 1.0, 0.0), ("u", 0.0, -1.0), ("d", 0.0, 1.0)] {
for t in [0.25, 0.5, 0.75] {
let ls = transition_layers("push", o, t);
let (old, new) = (of(&ls, Source::Old)[0], of(&ls, Source::New)[0]);
let s = q2(t);
assert!(near(old.quad[0][0], dx * s, 1e-9) && near(old.quad[0][1], dy * s, 1e-9), "{o} {t}");
assert!(near(new.quad[0][0], dx * (s - 1.0), 1e-9) && near(new.quad[0][1], dy * (s - 1.0), 1e-9), "{o} {t}");
}
}
// Ease in-out: slow at both ends.
assert!(q2(0.1) < 0.05 && q2(0.9) > 0.95 && near(q2(0.5), 0.5, 1e-9));
}
#[test]
fn cover_and_uncover_match_measured_positions() {
// Offset of the new slide in Cover Left (fraction of the width) at measured times.
for (t, off) in [(0.445, 0.655), (0.495, 0.512), (0.544, 0.359), (0.643, 0.134), (0.742, 0.046)] {
let ls = transition_layers("cover", "l", t);
assert!(near(left(of(&ls, Source::New)[0]), off, 0.05), "cover t={t}");
}
// Offset of the old slide in Uncover Left.
for (t, off) in [(0.244, -0.06), (0.343, -0.14), (0.442, -0.32), (0.508, -0.5), (0.558, -0.63)] {
let ls = transition_layers("uncover", "l", t);
assert!(near(left(of(&ls, Source::Old)[0]), off, 0.05), "uncover t={t}");
}
// Diagonal Cover shoots in and settles slowly.
for (t, off) in [(0.142, 0.728), (0.257, 0.49), (0.356, 0.29), (0.455, 0.146), (0.604, 0.053)] {
let ls = transition_layers("cover", "lu", t);
let n = of(&ls, Source::New)[0];
assert!(near(left(n), off, 0.06) && near(top(n), off, 0.06), "cover lu t={t}");
}
assert!(near(pow_inout(0.25, 3.0), 0.0625, 1e-9));
}
#[test]
fn wipe_has_a_wide_soft_edge() {
// Measured along a row of Wipe Right at t = 0.5: about half-way through at x = 0.6, nearly
// nothing at the right edge, fully new on the left third.
let c = -0.4 + 1.8 * 1.05 * 0.5;
assert!(near(edge(c, 0.6, 0.8), 0.49, 0.1));
assert!(edge(c, 1.0, 0.8) < 0.1);
assert!(edge(c, 0.2, 0.8) > 0.8);
// Directions: "r" starts on the left, "l" on the right, "u" at the bottom, "d" at the top,
// diagonals at the opposite corner.
let first = |o: &str| {
let ls = transition_layers("wipe", o, 0.15);
let n = of(&ls, Source::New);
assert!(!n.is_empty(), "{o}");
let cx = n.iter().map(|l| (l.quad[0][0] + l.quad[2][0]) / 2.0).sum::<f64>() / n.len() as f64;
let cy = n.iter().map(|l| (l.quad[0][1] + l.quad[2][1]) / 2.0).sum::<f64>() / n.len() as f64;
(cx, cy)
};
assert!(first("r").0 < 0.3 && first("l").0 > 0.7);
assert!(first("u").1 > 0.7 && first("d").1 < 0.3);
let ru = first("ru");
assert!(ru.0 < 0.4 && ru.1 > 0.6, "{ru:?}");
}
#[test]
fn split_and_shape_open_from_the_middle() {
for o in ["horzOut", "vertOut"] {
let ls = transition_layers("split", o, 0.2);
let n = of(&ls, Source::New);
assert!(n.iter().all(|l| {
let c = [(l.quad[0][0] + l.quad[2][0]) / 2.0, (l.quad[0][1] + l.quad[2][1]) / 2.0];
if o.starts_with("horz") { (c[1] - 0.5).abs() < 0.4 } else { (c[0] - 0.5).abs() < 0.4 }
}));
}
// Shape In is done with the old slide at half time; Shape Out starts the new one then.
assert!(of(&transition_layers("shape", "in", 0.55), Source::Old).is_empty());
assert!(of(&transition_layers("shape", "out", 0.45), Source::New).is_empty());
}
#[test]
fn dynamic_content_curves() {
// Pan: the new content's offset (fraction of the width) at measured times.
for (t, off) in [(0.6, 0.134), (0.7, 0.086), (0.8, 0.039), (0.9, 0.011)] {
let ls = transition_layers("pan", "l", t);
assert!(near(left(of(&ls, Source::NewContent)[0]), off, 0.07), "pan t={t}");
}
// The backgrounds cross-fade under the moving contents.
let ls = transition_layers("pan", "l", 0.5);
assert_eq!(ls.first().map(|l| l.source), Some(Source::OldBack));
assert!(of(&ls, Source::NewBack)[0].alpha > 0.5);
// Ferris Wheel: the old content drops (top edge, slide heights) as measured.
for (t, dy) in [(0.147, 0.06), (0.246, 0.17), (0.345, 0.36), (0.444, 0.70)] {
let ls = transition_layers("ferris", "l", t);
let q = of(&ls, Source::OldContent)[0].quad;
let cy = q.iter().map(|p| p[1]).sum::<f64>() / 4.0 - 0.5;
assert!(near(cy, dy, 0.08), "ferris t={t}: {cy}");
}
for k in ["pan", "ferris", "conveyor", "rotate", "window", "orbit", "flythrough"] {
assert!(uses_slide_parts(k, ""), "{k}");
}
assert!(uses_slide_parts("reveal", "smoothlyLeft") && !uses_slide_parts("reveal", "blackLeft"));
assert!(!uses_slide_parts("cube", "l") && !uses_slide_parts("push", "l"));
}
#[test]
fn cube_turns_toward_the_option() {
// Cube Left at the middle: the shared edge is near the middle, the old face on the left.
let ls = transition_frame("cube", "l", 0.5, A);
let (o, n) = (of(&ls, Source::Old)[0], of(&ls, Source::New)[0]);
let o_right = o.quad.iter().map(|p| p[0]).fold(f64::NEG_INFINITY, f64::max);
assert!(near(o_right, left(n), 0.02), "shared edge: {o_right} vs {}", left(n));
assert!(o_right > 0.3 && o_right < 0.7);
// Up: the new face comes from below.
let ls = transition_frame("cube", "u", 0.5, A);
assert!(top(of(&ls, Source::New)[0]) > top(of(&ls, Source::Old)[0]));
}
#[test]
fn switch_swaps_the_cards_past_halfway() {
let order = |t: f64| {
let ls = transition_frame("switch", "l", t, A);
let pos = |s: Source| ls.iter().position(|l| l.source == s);
(pos(Source::Old), pos(Source::New))
};
let (o, n) = order(0.3);
assert!(o > n, "old in front early");
let (o, n) = order(0.8);
assert!(n > o, "new in front late");
}
#[test]
fn clock_hand_sweeps_at_constant_speed() {
// The share of the slide covered grows linearly.
let area = |t: f64| {
let ls = transition_layers("clock", "clockwise", t);
of(&ls, Source::New)
.iter()
.map(|l| {
let [a, b, c, _] = l.quad;
((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])).abs() / 2.0 * (l.fade[0] + l.fade[1] + l.fade[2]) / 3.0
})
.sum::<f64>()
};
let (a1, a2, a3) = (area(0.25), area(0.5), area(0.75));
assert!(near(a2 - a1, a3 - a2, 0.08), "{a1} {a2} {a3}");
assert!(near(a2, 0.5, 0.08), "{a2}");
}
#[test]
fn options_change_the_frame() {
// Every option of a transition draws something different from its other options midway.
for (id, _, _, _, opts) in TRANSITIONS {
if matches!(*id, "morph" | "none" | "random") || opts.len() < 2 {
continue;
}
for (i, a) in opts.iter().enumerate() {
for b in opts.iter().skip(i + 1) {
let differs = [0.2, 0.35, 0.5, 0.8].iter().any(|t| transition_layers(id, a, *t) != transition_layers(id, b, *t));
assert!(differs, "{id}: {a} vs {b}");
}
}
}
}
#[test]
fn frames_stay_cheap() {
// Per frame, the show draws these meshes from cached slide textures: keep them small.
for (id, _, _, _, opts) in TRANSITIONS {
let mut options: Vec<&str> = opts.to_vec();
options.push("");
for o in options {
for t in [0.1, 0.3, 0.5, 0.7, 0.9] {
let tris: usize = transition_frame(id, o, t, A).iter().map(|l| crate::layer_mesh(l).1.len()).sum();
assert!(tris < 30_000, "{id}/{o} t={t}: {tris} triangles");
}
}
}
}
#[test]
fn hostile_aspects_are_safe() {
for a in [f64::NAN, 0.0, -3.0, 1e9, f64::INFINITY] {
for (id, ..) in TRANSITIONS {
for l in transition_frame(id, "", 0.4, a) {
assert!(l.quad.iter().all(|p| p[0].is_finite() && p[1].is_finite()));
assert!(l.fade.iter().all(|f| (0.0..=1.0).contains(f)));
}
}
}
assert!(near(ss(0.5), 0.5, 1e-12));
}
+77 -118
View File
@@ -1,7 +1,7 @@
//! CDEF (7.15).
use crate::frame::{FrameBuf, Plane};
use crate::spec_tables::{CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS, CDEF_UV_DIR, DIV_TABLE};
use crate::spec_tables::*;
use crate::state::FrameState;
/// Run CDEF on `fs.cur`; returns the CdefFrame, or None when no block is filtered (CdefFrame
@@ -45,7 +45,7 @@ fn cdef_block(fs: &FrameState, out: &mut FrameBuf, r: usize, c: usize, idx: usiz
let var_str = if (var >> 6) != 0 { (31 - ((var >> 6) as u32).leading_zeros()).min(12) as i32 } else { 0 };
pri = if var != 0 { (pri * (4 + var_str) + 8) >> 4 } else { 0 };
let damping = cp.damping as i32 + coeff_shift as i32;
filter(fs, out, 0, (r, c), (pri, sec), damping, dir);
filter(fs, out, 0, r, c, pri, sec, damping, dir);
if fs.num_planes == 1 {
return true;
}
@@ -53,8 +53,8 @@ fn cdef_block(fs: &FrameState, out: &mut FrameBuf, r: usize, c: usize, idx: usiz
let sec = (cp.uv_sec[idx] << coeff_shift) as i32;
let dir = if pri == 0 { 0 } else { CDEF_UV_DIR[fs.ssx][fs.ssy][y_dir] as usize };
let damping = cp.damping as i32 + coeff_shift as i32 - 1;
filter(fs, out, 1, (r, c), (pri, sec), damping, dir);
filter(fs, out, 2, (r, c), (pri, sec), damping, dir);
filter(fs, out, 1, r, c, pri, sec, damping, dir);
filter(fs, out, 2, r, c, pri, sec, damping, dir);
true
}
@@ -124,74 +124,33 @@ fn constrain(diff: i32, threshold: i32, adj: u32) -> i32 {
if diff < 0 { -mag } else { mag }
}
/// Tap offsets, weights and strengths of one block.
struct Taps {
pri: i32,
sec: i32,
pri_adj: u32,
sec_adj: u32,
pri_off: [isize; 2],
sec_off: [[isize; 2]; 2],
pri_taps: [i32; 2],
sec_taps: [i32; 2],
}
impl Taps {
fn new(coeff_shift: u32, (pri, sec): (i32, i32), damping: i32, dir: usize) -> Taps {
let pri_tap = ((pri >> coeff_shift) & 1) as usize;
let off = |d: usize, k: usize| CDEF_DIRECTIONS[d][k][0] as isize * PAD_STRIDE as isize + CDEF_DIRECTIONS[d][k][1] as isize;
let pri_off = [off(dir, 0), off(dir, 1)];
let d_lo = (dir + 6) & 7;
let d_hi = (dir + 2) & 7;
let sec_off = [[off(d_lo, 0), off(d_hi, 0)], [off(d_lo, 1), off(d_hi, 1)]];
let pri_taps = [CDEF_PRI_TAPS[pri_tap][0] as i32, CDEF_PRI_TAPS[pri_tap][1] as i32];
let sec_taps = [CDEF_SEC_TAPS[pri_tap][0] as i32, CDEF_SEC_TAPS[pri_tap][1] as i32];
let adj = |t: i32| if t == 0 { 0 } else { (damping - (31 - (t as u32).leading_zeros()) as i32).max(0) as u32 };
Taps { pri, sec, pri_adj: adj(pri), sec_adj: adj(sec), pri_off, sec_off, pri_taps, sec_taps }
#[allow(clippy::too_many_arguments)]
fn filter(fs: &FrameState, out: &mut FrameBuf, plane: usize, r: usize, c: usize, pri: i32, sec: i32, damping: i32, dir: usize) {
if pri == 0 && sec == 0 {
// Every tap contributes 0 and the clamp to [min, max] keeps x: CdefFrame = CurrFrame.
return;
}
/// The 12 (offset, weight, strength, adjustment) taps in filtering order.
fn tap_list(&self) -> [(isize, i32, i32, u32); 12] {
let mut taps = [(0isize, 0i32, 0i32, 0u32); 12];
let mut n = 0;
for k in 0..2 {
for sign in [-1isize, 1] {
taps[n] = (sign * self.pri_off[k], self.pri_taps[k], self.pri, self.pri_adj);
taps[n + 1] = (sign * self.sec_off[k][0], self.sec_taps[k], self.sec, self.sec_adj);
taps[n + 2] = (sign * self.sec_off[k][1], self.sec_taps[k], self.sec, self.sec_adj);
n += 3;
}
}
taps
}
}
/// Position and size of a block within its plane.
#[derive(Clone, Copy)]
struct BlockRect {
x0: usize,
y0: usize,
w: usize,
h: usize,
}
/// The block with two samples of padding on every side, plus whether every sample is available
/// (CdefAvailable: its 4x4 block is inside the frame).
fn padded_block(fs: &FrameState, plane: usize, src: &Plane, rect: BlockRect) -> ([i32; PAD_STRIDE * PAD_STRIDE], bool) {
let coeff_shift = fs.bit_depth - 8;
let (sub_x, sub_y) = if plane > 0 { (fs.ssx, fs.ssy) } else { (0, 0) };
let x0 = (c * 4) >> sub_x;
let y0 = (r * 4) >> sub_y;
let w = 8 >> sub_x;
let h = 8 >> sub_y;
let src = &fs.cur.planes[plane];
let (mi_rows, mi_cols) = (fs.fh.mi_rows as isize, fs.fh.mi_cols as isize);
// CdefAvailable per sample: its 4x4 block is inside the frame.
let mut buf = [CDEF_NA; PAD_STRIDE * PAD_STRIDE];
let mut all_avail = true;
for i in 0..rect.h + 4 {
let y = (rect.y0 + i) as isize - 2;
for i in 0..h + 4 {
let y = (y0 + i) as isize - 2;
let cand_r = (y << sub_y) >> 2;
if y < 0 || cand_r >= mi_rows {
all_avail = false;
continue;
}
let row = src.row(y as usize);
for j in 0..rect.w + 4 {
let x = (rect.x0 + j) as isize - 2;
for j in 0..w + 4 {
let x = (x0 + j) as isize - 2;
let cand_c = (x << sub_x) >> 2;
if x >= 0 && cand_c < mi_cols {
buf[i * PAD_STRIDE + j] = row[x as usize] as i32;
@@ -200,70 +159,70 @@ fn padded_block(fs: &FrameState, plane: usize, src: &Plane, rect: BlockRect) ->
}
}
}
(buf, all_avail)
}
/// Filters one sample whose taps may be unavailable (CDEF_NA).
fn filter_sample(buf: &[i32; PAD_STRIDE * PAD_STRIDE], taps: &Taps, ci: isize, x: i32) -> u16 {
let mut sum = 0i32;
let mut max = x;
let mut min = x;
for k in 0..2 {
for sign in [-1isize, 1] {
let p = buf[(ci + sign * taps.pri_off[k]) as usize];
if p != CDEF_NA {
if taps.pri != 0 {
sum += taps.pri_taps[k] * constrain(p - x, taps.pri, taps.pri_adj);
}
max = max.max(p);
min = min.min(p);
}
for s in 0..2 {
let q = buf[(ci + sign * taps.sec_off[k][s]) as usize];
if q != CDEF_NA {
if taps.sec != 0 {
sum += taps.sec_taps[k] * constrain(q - x, taps.sec, taps.sec_adj);
}
max = max.max(q);
min = min.min(q);
}
}
}
}
(x + ((8 + sum - (sum < 0) as i32) >> 4)).clamp(min, max) as u16
}
fn filter(fs: &FrameState, out: &mut FrameBuf, plane: usize, (r, c): (usize, usize), strengths: (i32, i32), damping: i32, dir: usize) {
let (pri, sec) = strengths;
if pri == 0 && sec == 0 {
// Every tap contributes 0 and the clamp to [min, max] keeps x: CdefFrame = CurrFrame.
return;
}
let coeff_shift = fs.bit_depth - 8;
let (sub_x, sub_y) = if plane > 0 { (fs.ssx, fs.ssy) } else { (0, 0) };
let rect = BlockRect { x0: (c * 4) >> sub_x, y0: (r * 4) >> sub_y, w: 8 >> sub_x, h: 8 >> sub_y };
let src = &fs.cur.planes[plane];
let (buf, all_avail) = padded_block(fs, plane, src, rect);
let taps = Taps::new(coeff_shift, strengths, damping, dir);
let pri_tap = ((pri >> coeff_shift) & 1) as usize;
let off = |d: usize, k: usize| CDEF_DIRECTIONS[d][k][0] as isize * PAD_STRIDE as isize + CDEF_DIRECTIONS[d][k][1] as isize;
let pri_off = [off(dir, 0), off(dir, 1)];
let d_lo = (dir + 6) & 7;
let d_hi = (dir + 2) & 7;
let sec_off = [[off(d_lo, 0), off(d_hi, 0)], [off(d_lo, 1), off(d_hi, 1)]];
let pri_taps = [CDEF_PRI_TAPS[pri_tap][0] as i32, CDEF_PRI_TAPS[pri_tap][1] as i32];
let sec_taps = [CDEF_SEC_TAPS[pri_tap][0] as i32, CDEF_SEC_TAPS[pri_tap][1] as i32];
let adj = |t: i32| if t == 0 { 0 } else { (damping - (31 - (t as u32).leading_zeros()) as i32).max(0) as u32 };
let (pri_adj, sec_adj) = (adj(pri), adj(sec));
let dst = &mut out.planes[plane];
if all_avail {
// Every tap is available: whole rows at a time (constrain() with threshold 0 is 0).
let list = taps.tap_list();
let rows = (rect.y0, rect.x0, rect.h);
match rect.w {
8 => filter_rows::<8>(&buf, &list, dst, rows),
_ => filter_rows::<4>(&buf, &list, dst, rows),
let mut taps = [(0isize, 0i32, 0i32, 0u32); 12];
let mut n = 0;
for k in 0..2 {
for sign in [-1isize, 1] {
taps[n] = (sign * pri_off[k], pri_taps[k], pri, pri_adj);
taps[n + 1] = (sign * sec_off[k][0], sec_taps[k], sec, sec_adj);
taps[n + 2] = (sign * sec_off[k][1], sec_taps[k], sec, sec_adj);
n += 3;
}
}
let rows = (y0, x0, h);
match w {
8 => filter_rows::<8>(&buf, &taps, dst, rows),
_ => filter_rows::<4>(&buf, &taps, dst, rows),
}
return;
}
for i in 0..rect.h {
for i in 0..h {
// The centre sample is read even where CdefAvailable is 0 (8x8 blocks straddling an odd
// MiRows / MiCols edge).
let srow = &src.row(rect.y0 + i)[rect.x0..rect.x0 + rect.w];
let drow = &mut dst.row_mut(rect.y0 + i)[rect.x0..rect.x0 + rect.w];
for j in 0..rect.w {
let srow = &src.row(y0 + i)[x0..x0 + w];
let drow = &mut dst.row_mut(y0 + i)[x0..x0 + w];
for j in 0..w {
let ci = ((i + 2) * PAD_STRIDE + j + 2) as isize;
drow[j] = filter_sample(&buf, &taps, ci, srow[j] as i32);
let x = srow[j] as i32;
let mut sum = 0i32;
let mut max = x;
let mut min = x;
for k in 0..2 {
for sign in [-1isize, 1] {
let p = buf[(ci + sign * pri_off[k]) as usize];
if p != CDEF_NA {
if pri != 0 {
sum += pri_taps[k] * constrain(p - x, pri, pri_adj);
}
max = max.max(p);
min = min.min(p);
}
for s in 0..2 {
let q = buf[(ci + sign * sec_off[k][s]) as usize];
if q != CDEF_NA {
if sec != 0 {
sum += sec_taps[k] * constrain(q - x, sec, sec_adj);
}
max = max.max(q);
min = min.min(q);
}
}
}
}
drow[j] = (x + ((8 + sum - (sum < 0) as i32) >> 4)).clamp(min, max) as u16;
}
}
}
@@ -283,14 +242,14 @@ fn filter_rows<const W: usize>(
}
for i in 0..h {
let ci = ((i + 2) * PAD_STRIDE + 2) as isize;
let Some(&x) = b16.get(ci as usize..).and_then(<[_]>::first_chunk::<W>) else {
let Some(&x) = b16.get(ci as usize..).and_then(|r| r.first_chunk::<W>()) else {
return;
};
let (mut sum, mut max, mut min) = ([0i16; W], x, x);
for &(off, weight, thr, adj) in taps {
let (weight, thr) = (weight as i16, thr as i16);
let start = (ci + off) as usize;
let Some(p) = b16.get(start..).and_then(<[_]>::first_chunk::<W>) else {
let Some(p) = b16.get(start..).and_then(|r| r.first_chunk::<W>()) else {
return;
};
for j in 0..W {
+1 -21
View File
@@ -1,26 +1,6 @@
//! The adaptive CDF arrays (spec 6.8.2 init_non_coeff_cdfs / init_coeff_cdfs, load_cdfs).
use crate::spec_tables::{
DEFAULT_ANGLE_DELTA_CDF, DEFAULT_CFL_ALPHA_CDF, DEFAULT_CFL_SIGN_CDF, DEFAULT_COEFF_BASE_CDF, DEFAULT_COEFF_BASE_EOB_CDF, DEFAULT_COEFF_BR_CDF,
DEFAULT_COMP_BWD_REF_CDF, DEFAULT_COMP_GROUP_IDX_CDF, DEFAULT_COMP_MODE_CDF, DEFAULT_COMP_REF_CDF, DEFAULT_COMP_REF_TYPE_CDF,
DEFAULT_COMPOUND_IDX_CDF, DEFAULT_COMPOUND_MODE_CDF, DEFAULT_COMPOUND_TYPE_CDF, DEFAULT_DC_SIGN_CDF, DEFAULT_DELTA_LF_CDF, DEFAULT_DELTA_Q_CDF,
DEFAULT_DRL_MODE_CDF, DEFAULT_EOB_EXTRA_CDF, DEFAULT_EOB_PT_16_CDF, DEFAULT_EOB_PT_32_CDF, DEFAULT_EOB_PT_64_CDF, DEFAULT_EOB_PT_128_CDF,
DEFAULT_EOB_PT_256_CDF, DEFAULT_EOB_PT_512_CDF, DEFAULT_EOB_PT_1024_CDF, DEFAULT_FILTER_INTRA_CDF, DEFAULT_FILTER_INTRA_MODE_CDF,
DEFAULT_INTER_INTRA_CDF, DEFAULT_INTER_INTRA_MODE_CDF, DEFAULT_INTER_TX_TYPE_SET1_CDF, DEFAULT_INTER_TX_TYPE_SET2_CDF,
DEFAULT_INTER_TX_TYPE_SET3_CDF, DEFAULT_INTERP_FILTER_CDF, DEFAULT_INTRA_TX_TYPE_SET1_CDF, DEFAULT_INTRA_TX_TYPE_SET2_CDF, DEFAULT_INTRABC_CDF,
DEFAULT_IS_INTER_CDF, DEFAULT_MOTION_MODE_CDF, DEFAULT_MV_BIT_CDF, DEFAULT_MV_CLASS_CDF, DEFAULT_MV_CLASS0_BIT_CDF, DEFAULT_MV_CLASS0_FR_CDF,
DEFAULT_MV_CLASS0_HP_CDF, DEFAULT_MV_FR_CDF, DEFAULT_MV_HP_CDF, DEFAULT_MV_JOINT_CDF, DEFAULT_MV_SIGN_CDF, DEFAULT_NEW_MV_CDF,
DEFAULT_PALETTE_SIZE_2_UV_COLOR_CDF, DEFAULT_PALETTE_SIZE_2_Y_COLOR_CDF, DEFAULT_PALETTE_SIZE_3_UV_COLOR_CDF, DEFAULT_PALETTE_SIZE_3_Y_COLOR_CDF,
DEFAULT_PALETTE_SIZE_4_UV_COLOR_CDF, DEFAULT_PALETTE_SIZE_4_Y_COLOR_CDF, DEFAULT_PALETTE_SIZE_5_UV_COLOR_CDF, DEFAULT_PALETTE_SIZE_5_Y_COLOR_CDF,
DEFAULT_PALETTE_SIZE_6_UV_COLOR_CDF, DEFAULT_PALETTE_SIZE_6_Y_COLOR_CDF, DEFAULT_PALETTE_SIZE_7_UV_COLOR_CDF, DEFAULT_PALETTE_SIZE_7_Y_COLOR_CDF,
DEFAULT_PALETTE_SIZE_8_UV_COLOR_CDF, DEFAULT_PALETTE_SIZE_8_Y_COLOR_CDF, DEFAULT_PALETTE_UV_MODE_CDF, DEFAULT_PALETTE_UV_SIZE_CDF,
DEFAULT_PALETTE_Y_MODE_CDF, DEFAULT_PALETTE_Y_SIZE_CDF, DEFAULT_PARTITION_W8_CDF, DEFAULT_PARTITION_W16_CDF, DEFAULT_PARTITION_W32_CDF,
DEFAULT_PARTITION_W64_CDF, DEFAULT_PARTITION_W128_CDF, DEFAULT_REF_MV_CDF, DEFAULT_RESTORATION_TYPE_CDF, DEFAULT_SEGMENT_ID_CDF,
DEFAULT_SEGMENT_ID_PREDICTED_CDF, DEFAULT_SINGLE_REF_CDF, DEFAULT_SKIP_CDF, DEFAULT_SKIP_MODE_CDF, DEFAULT_TX_8X8_CDF, DEFAULT_TX_16X16_CDF,
DEFAULT_TX_32X32_CDF, DEFAULT_TX_64X64_CDF, DEFAULT_TXB_SKIP_CDF, DEFAULT_TXFM_SPLIT_CDF, DEFAULT_UNI_COMP_REF_CDF, DEFAULT_USE_OBMC_CDF,
DEFAULT_USE_SGRPROJ_CDF, DEFAULT_USE_WIENER_CDF, DEFAULT_UV_MODE_CFL_ALLOWED_CDF, DEFAULT_UV_MODE_CFL_NOT_ALLOWED_CDF, DEFAULT_WEDGE_INDEX_CDF,
DEFAULT_WEDGE_INTER_INTRA_CDF, DEFAULT_Y_MODE_CDF, DEFAULT_ZERO_MV_CDF, FRAME_LF_COUNT, MV_CONTEXTS,
};
use crate::spec_tables::*;
/// Every CDF array listed by init_non_coeff_cdfs and init_coeff_cdfs. Each innermost array holds
/// N cumulative values (the last is 32768) plus the adaptation counter.
+63 -250
View File
@@ -17,11 +17,7 @@ use crate::cdf::Cdfs;
use crate::frame::FrameBuf;
use crate::header::{FilmGrainParams, FrameHeader, HeaderState, LoopFilterDeltas, RefInfo, SegmentationFeatures, SequenceHeader, default_gm_params};
use crate::par::Pool;
use crate::spec_tables::{
ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, DEFAULT_INTRA_FRAME_Y_MODE_CDF, DIV_MULT, GOLDEN_FRAME, INTRA_FRAME, INTRA_ONLY_FRAME, KEY_FRAME,
LAST_FRAME, LAST2_FRAME, MAX_FRAME_DISTANCE, MAX_OFFSET_HEIGHT, MAX_OFFSET_WIDTH, MFMV_STACK_SIZE, NUM_REF_FRAMES, PRIMARY_REF_NONE,
REFMVS_LIMIT, REFS_PER_FRAME,
};
use crate::spec_tables::*;
use crate::state::{FrameShared, FrameState, TileState};
use crate::stats::{DecodeStats, Stage, Timer};
use crate::tile::TileDecoder;
@@ -65,7 +61,7 @@ impl<T: Clone> Slot<T> {
}
fn set(&self, v: Result<T>) {
let mut g = self.value.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut g = self.value.lock().unwrap_or_else(|e| e.into_inner());
*g = Some(v);
self.cv.notify_all();
}
@@ -75,12 +71,12 @@ impl<T: Clone> Slot<T> {
}
fn wait(&self) -> Result<T> {
let mut g = self.value.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut g = self.value.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(v) = g.as_ref() {
return v.clone();
}
g = self.cv.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner);
g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner());
}
}
}
@@ -118,8 +114,6 @@ enum Output {
grain: FilmGrainParams,
apply_film_grain: bool,
pts: i64,
/// What copying the picture out costs, in the reference's own format.
bytes: u64,
},
}
@@ -134,7 +128,7 @@ impl Output {
fn take(self) -> Result<Picture> {
match self {
Output::Decoded(s) => s.wait().map(|p| Arc::try_unwrap(p).unwrap_or_else(|p| (*p).clone())),
Output::Existing { slot, seq, width, height, grain, apply_film_grain, pts, .. } => {
Output::Existing { slot, seq, width, height, grain, apply_film_grain, pts } => {
let rf = slot.wait()?;
Ok(output_picture(&seq, &rf, width, height, &grain, apply_film_grain, pts))
}
@@ -212,35 +206,12 @@ pub struct Decoder {
/// Frames submitted to the workers and not known to be finished (oldest first).
in_flight: VecDeque<Arc<FrameSlot>>,
max_in_flight: usize,
/// Bytes the picture store may take ([`deckcraft_bitstream::budget`]).
memory_budget: u64,
/// Shown pictures not yet returned, in output order.
out: VecDeque<Output>,
/// pts of the temporal unit being decoded.
pts: i64,
}
/// Whether `pictures` frames of `width` x `height`, padded as `FrameBuf::new` pads them, fit in
/// `budget` bytes.
fn store_fits(width: u32, height: u32, color: &crate::header::ColorConfig, pictures: usize, budget: u64) -> bool {
let shape = deckcraft_bitstream::budget::PictureShape {
width: u64::from(width).div_ceil(128) * 128 + 160,
height: u64::from(height).div_ceil(128) * 128 + 160,
shift_x: u32::from(color.subsampling_x),
shift_y: u32::from(color.subsampling_y),
chroma_planes: if color.mono_chrome { 0 } else { 2 },
bytes_per_sample: 2,
};
shape.fits(pictures as u64, budget)
}
impl Decoder {
/// Cap the bytes of decoded pictures (references, current, in flight) this decoder may hold.
pub fn set_memory_budget(&mut self, bytes: u64) {
self.memory_budget = bytes;
}
}
fn default_threads() -> usize {
#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
{
@@ -297,7 +268,6 @@ impl Decoder {
workers,
in_flight: VecDeque::new(),
max_in_flight: fthreads + 2,
memory_budget: deckcraft_bitstream::budget::DECODE_MEMORY_BUDGET,
out: VecDeque::new(),
pts: 0,
}
@@ -381,8 +351,8 @@ impl Decoder {
// Output policy (7.18.1 note): with scalability, show one frame per temporal unit, the
// highest spatial layer present.
let scalable = self.seq.as_ref().is_some_and(|s| s.op_idc != 0);
let kept: Vec<Output> = if !scalable {
out.into_iter().map(|(o, _, _)| o).collect()
if !scalable {
self.out.extend(out.into_iter().map(|(o, _, _)| o));
} else {
let mut last: Option<(usize, u32)> = None;
let mut sel: Vec<Output> = Vec::new();
@@ -402,61 +372,54 @@ impl Decoder {
}
}
}
sel
};
// Every repeat is copied out whole, so the repeats this call keeps (after the layer
// selection) must not queue more than half the decoder budget; the first one over it and
// everything after is dropped.
let mut r = r;
let mut repeat_bytes = 0u64;
let mut ok = Vec::with_capacity(kept.len());
for o in kept {
if let Output::Existing { bytes, .. } = &o {
repeat_bytes = repeat_bytes.saturating_add(*bytes);
if repeat_bytes > self.memory_budget / 2 {
if r.is_ok() {
r = Err(Error::Invalid("repeated frame outputs exceed the decoder memory budget"));
}
break;
}
}
ok.push(o);
self.out.extend(sel);
}
self.out.extend(ok);
r
}
/// Whether an OBU belongs to the selected operating point (spec 7.5: OBUs of other layers are dropped).
fn in_operating_point(&self, obu: &ObuUnit) -> bool {
if obu.obu_type != OBU_SEQUENCE_HEADER_T
&& obu.obu_type != OBU_TEMPORAL_DELIMITER_T
&& obu.ext
&& let Some(seq) = &self.seq
&& seq.op_idc != 0
{
let idc = seq.op_idc;
let in_t = (idc >> obu.temporal_id) & 1;
let in_s = (idc >> (obu.spatial_id + 8)) & 1;
if in_t == 0 || in_s == 0 {
return false;
}
}
true
}
fn parse_obus(&mut self, data: &[u8], out: &mut Vec<(Output, usize, u32)>) -> Result<()> {
let mut tu = 0usize;
// Repeated-frame outputs in `out`, counted as they are added rather than recounted per OBU.
let mut existing = out.iter().filter(|(o, _, _)| matches!(o, Output::Existing { .. })).count();
let mut pos = 0;
while pos < data.len() {
let obu = parse_obu_unit(data, pos)?;
pos = obu.end;
if !self.in_operating_point(&obu) {
continue;
let h = data[pos];
if h & 0x80 != 0 {
return Err(Error::Invalid("obu_forbidden_bit"));
}
let (payload, spatial_id) = (obu.payload, obu.spatial_id);
match obu.obu_type {
let obu_type = ((h >> 3) & 0xf) as u32;
let ext = h & 4 != 0;
let has_size = h & 2 != 0;
let mut p = pos + 1;
let (mut temporal_id, mut spatial_id) = (0, 0);
if ext {
let e = *data.get(p).ok_or(Error::Truncated)?;
temporal_id = (e >> 5) as u32;
spatial_id = ((e >> 3) & 3) as u32;
p += 1;
}
let size = if has_size {
let (v, n) = leb128(data.get(p..).ok_or(Error::Truncated)?)?;
p += n;
v as usize
} else {
data.len().checked_sub(p).ok_or(Error::Truncated)?
};
let end = p.checked_add(size).filter(|&e| e <= data.len()).ok_or(Error::Truncated)?;
let payload = &data[p..end];
pos = end;
if obu_type != OBU_SEQUENCE_HEADER_T
&& obu_type != OBU_TEMPORAL_DELIMITER_T
&& ext
&& let Some(seq) = &self.seq
&& seq.op_idc != 0
{
let idc = seq.op_idc;
let in_t = (idc >> temporal_id) & 1;
let in_s = (idc >> (spatial_id + 8)) & 1;
if in_t == 0 || in_s == 0 {
continue;
}
}
match obu_type {
OBU_SEQUENCE_HEADER_T => {
let s = SequenceHeader::parse(payload)?;
self.seq = Some(s);
@@ -466,12 +429,24 @@ impl Decoder {
tu += 1;
}
OBU_FRAME_HEADER_T | OBU_REDUNDANT_FRAME_HEADER_T | OBU_FRAME_T => {
if let Some(o) = self.frame_obu(&obu)? {
if existing >= 32 {
return Err(Error::Invalid("too many frame outputs in chunk"));
if self.seen_frame_header {
// frame_header_copy(): identical to the active header
if obu_type != OBU_FRAME_T {
continue;
}
existing += usize::from(matches!(o, Output::Existing { .. }));
}
let mut r = BitReader::new(payload);
let shown = self.frame_header(&mut r, temporal_id, spatial_id)?;
if let Some(o) = shown {
out.push((o, tu, spatial_id));
continue;
}
if obu_type == OBU_FRAME_T {
r.byte_align();
let rest = payload.get(r.byte_pos()..).ok_or(Error::Truncated)?;
if let Some(o) = self.tile_group(rest)? {
out.push((o, tu, spatial_id));
}
}
}
OBU_TILE_GROUP_T => {
@@ -486,22 +461,6 @@ impl Decoder {
Ok(())
}
/// A frame header or frame OBU: returns the picture it completes, if any.
fn frame_obu(&mut self, obu: &ObuUnit) -> Result<Option<Output>> {
// frame_header_copy(): identical to the active header
if self.seen_frame_header && obu.obu_type != OBU_FRAME_T {
return Ok(None);
}
let mut r = BitReader::new(obu.payload);
let shown = self.frame_header(&mut r, obu.temporal_id, obu.spatial_id)?;
if shown.is_some() || obu.obu_type != OBU_FRAME_T {
return Ok(shown);
}
r.byte_align();
let rest = obu.payload.get(r.byte_pos()..).ok_or(Error::Truncated)?;
self.tile_group(rest)
}
/// frame_header_obu( ): returns the output for show_existing_frame.
fn frame_header(&mut self, r: &mut BitReader, temporal_id: u32, spatial_id: u32) -> Result<Option<Output>> {
let seq = self.seq.clone().ok_or(Error::Invalid("frame before sequence header"))?;
@@ -524,15 +483,6 @@ impl Decoder {
let idx = fh.frame_to_show_map_idx;
let slot = self.ref_frames[idx].clone().ok_or(Error::Invalid("show_existing_frame of an empty slot"))?;
let info = self.refs[idx].clone();
// Sized in the reference's own format: a new sequence header may differ from it.
let shape = deckcraft_bitstream::budget::PictureShape {
width: u64::from(info.upscaled_width),
height: u64::from(info.frame_height),
shift_x: u32::from(info.subsampling_x),
shift_y: u32::from(info.subsampling_y),
chroma_planes: if info.mono_chrome { 0 } else { 2 },
bytes_per_sample: 2,
};
let o = Output::Existing {
slot: slot.clone(),
seq: seq.clone(),
@@ -541,7 +491,6 @@ impl Decoder {
grain: fh.film_grain.clone(),
apply_film_grain: self.apply_film_grain,
pts: self.pts,
bytes: shape.bytes().unwrap_or(u64::MAX),
};
if fh.frame_type == KEY_FRAME as u8 {
// reference frame loading process (7.21) then refresh every slot (7.20)
@@ -559,12 +508,6 @@ impl Decoder {
if fh.upscaled_width > 65536 || fh.frame_height > 65536 {
return Err(Error::Invalid("frame size"));
}
// The axis cap alone allows 8 GiB pictures: check the whole store (every reference slot,
// the new frame and those in flight, as `FrameBuf::new` pads them) before allocating.
let width = fh.upscaled_width.max(fh.frame_width);
if !store_fits(width, fh.frame_height, &seq.color, NUM_REF_FRAMES + 1 + self.max_in_flight, self.memory_budget) {
return Err(Error::Invalid("frame size exceeds the decoder memory budget"));
}
if !fh.frame_is_intra {
for i in 0..REFS_PER_FRAME {
if self.ref_frames[fh.ref_frame_idx[i]].is_none() {
@@ -612,7 +555,6 @@ impl Decoder {
if tg_end >= num_tiles || tg_start > tg_end {
return Err(Error::Invalid("tile group range"));
}
check_tile_group_start(job.tiles.len(), tg_start)?;
let mut pos = r.byte_pos();
for tile_num in tg_start..=tg_end {
let size = if tile_num == tg_end {
@@ -660,9 +602,6 @@ impl Decoder {
ri.lf_deltas = fh.lf.deltas;
ri.seg_features = fh.seg.features;
ri.grain = fh.film_grain.clone();
ri.subsampling_x = job.seq.color.subsampling_x;
ri.subsampling_y = job.seq.color.subsampling_y;
ri.mono_chrome = job.seq.color.mono_chrome;
self.ref_frames[i] = Some(job.slot.clone());
}
}
@@ -694,9 +633,7 @@ impl Decoder {
/// Decode a frame job and publish its results.
fn run_job(job: FrameJob, pool: &Pool, stats: &Mutex<DecodeStats>) {
let mut st = DecodeStats::default();
// A panic while decoding must still publish an error: the output and every frame that
// references this one wait on these slots.
match guarded(|| decode_frame(&job, pool, &mut st)) {
match decode_frame(&job, pool, &mut st) {
Ok((rf, pic)) => {
if let Some(ps) = &job.picture {
ps.set(pic.map(Arc::new).ok_or(Error::Invalid("shown frame without picture")));
@@ -715,12 +652,6 @@ fn run_job(job: FrameJob, pool: &Pool, stats: &Mutex<DecodeStats>) {
}
}
/// Run `f`, turning a panic into an error (the decoder's own code never panics on purpose; this
/// keeps a bug from stranding the job's waiters).
fn guarded<R>(f: impl FnOnce() -> Result<R>) -> Result<R> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or(Err(Error::Invalid("frame decode panicked")))
}
/// The whole decoding process of one frame: setup, tiles, post-filters, motion vector storage
/// and the output picture.
fn decode_frame(job: &FrameJob, pool: &Pool, stats: &mut DecodeStats) -> Result<(Arc<RefFrame>, Option<Picture>)> {
@@ -1016,121 +947,3 @@ fn project(fs: &mut FrameState, src: usize, dst_sign: i32) -> bool {
}
true
}
/// Tile groups must arrive in order with no gaps and no overlap: each one starts at the tile
/// after the last one received (`tg_start` semantics, 6.10.1).
fn check_tile_group_start(received: usize, tg_start: usize) -> Result<()> {
if tg_start == received { Ok(()) } else { Err(Error::Invalid("tile group out of order")) }
}
#[cfg(test)]
mod tests {
use super::check_tile_group_start;
#[test]
fn tile_groups_must_be_contiguous() {
assert!(check_tile_group_start(0, 0).is_ok());
assert!(check_tile_group_start(2, 2).is_ok());
// duplicate coverage
assert!(check_tile_group_start(2, 0).is_err());
assert!(check_tile_group_start(2, 1).is_err());
// skipped tiles
assert!(check_tile_group_start(0, 1).is_err());
assert!(check_tile_group_start(2, 3).is_err());
}
}
/// One OBU: its header fields, payload and the position just past it.
struct ObuUnit<'a> {
obu_type: u32,
ext: bool,
temporal_id: u32,
spatial_id: u32,
payload: &'a [u8],
end: usize,
}
fn parse_obu_unit(data: &[u8], pos: usize) -> Result<ObuUnit<'_>> {
let h = data[pos];
if h & 0x80 != 0 {
return Err(Error::Invalid("obu_forbidden_bit"));
}
let obu_type = ((h >> 3) & 0xf) as u32;
let ext = h & 4 != 0;
let has_size = h & 2 != 0;
let mut p = pos + 1;
let (mut temporal_id, mut spatial_id) = (0, 0);
if ext {
let e = *data.get(p).ok_or(Error::Truncated)?;
temporal_id = (e >> 5) as u32;
spatial_id = ((e >> 3) & 3) as u32;
p += 1;
}
let size = if has_size {
let (v, n) = leb128(data.get(p..).ok_or(Error::Truncated)?)?;
p += n;
v as usize
} else {
data.len().checked_sub(p).ok_or(Error::Truncated)?
};
let end = p.checked_add(size).filter(|&e| e <= data.len()).ok_or(Error::Truncated)?;
Ok(ObuUnit { obu_type, ext, temporal_id, spatial_id, payload: &data[p..end], end })
}
#[cfg(test)]
mod guard_tests {
use super::*;
#[test]
fn a_panicking_job_still_publishes_an_error_to_its_waiters() {
let slot: Arc<Slot<u32>> = Slot::new();
let picture: Arc<Slot<u32>> = Slot::new();
// Waiters: the output and a dependent frame, on their own threads.
let (tx, rx) = std::sync::mpsc::channel();
for s in [slot.clone(), picture.clone()] {
let tx = tx.clone();
std::thread::spawn(move || {
let _ = tx.send(s.wait().is_err());
});
}
let (s, p) = (slot.clone(), picture.clone());
std::thread::spawn(move || {
let r: Result<u32> = guarded(|| panic!("hostile frame"));
p.set(r.clone());
s.set(r);
});
for _ in 0..2 {
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(10)), Ok(true));
}
assert_eq!(guarded(|| Ok(5)).ok(), Some(5));
}
}
#[cfg(test)]
mod budget_tests {
use super::*;
use deckcraft_bitstream::budget::DECODE_MEMORY_BUDGET;
fn color(mono: bool) -> crate::header::ColorConfig {
crate::header::ColorConfig { mono_chrome: mono, subsampling_x: 1, subsampling_y: 1, ..Default::default() }
}
#[test]
fn the_axis_maximum_is_over_budget_and_4k_is_not() {
let refs = NUM_REF_FRAMES + 1 + 4;
assert!(!store_fits(65536, 65536, &color(false), refs, DECODE_MEMORY_BUDGET));
assert!(!store_fits(65536, 65536, &color(true), 1, DECODE_MEMORY_BUDGET));
assert!(store_fits(3840, 2160, &color(false), refs, DECODE_MEMORY_BUDGET));
assert!(store_fits(1920, 1080, &color(false), refs, DECODE_MEMORY_BUDGET));
}
#[test]
fn exact_budget_boundary_and_reference_count() {
// 8x8 pads to 288x288: luma 82944 + chroma 2 * 20736 samples, 2 bytes each.
let one = (288 * 288 + 2 * 144 * 144) * 2;
assert!(store_fits(8, 8, &color(false), 9, 9 * one));
assert!(!store_fits(8, 8, &color(false), 9, 9 * one - 1));
assert!(!store_fits(8, 8, &color(false), 10, 9 * one));
assert!(store_fits(8, 8, &color(true), 9, 9 * 288 * 288 * 2));
}
}
+3 -3
View File
@@ -16,7 +16,7 @@ const POOL_MAX_SAMPLES: usize = 96 << 20;
fn zeroed(len: usize) -> Vec<u16> {
if len >= POOL_MIN_LEN {
let found = {
let mut pool = PLANE_POOL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut pool = PLANE_POOL.lock().unwrap_or_else(|e| e.into_inner());
pool.iter().position(|v| v.capacity() >= len && v.capacity() <= 2 * len).map(|i| pool.swap_remove(i))
};
if let Some(mut v) = found {
@@ -52,8 +52,8 @@ impl Drop for Plane {
fn drop(&mut self) {
if self.data.capacity() >= POOL_MIN_LEN {
let v = std::mem::take(&mut self.data);
let mut pool = PLANE_POOL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let kept: usize = pool.iter().map(Vec::capacity).sum();
let mut pool = PLANE_POOL.lock().unwrap_or_else(|e| e.into_inner());
let kept: usize = pool.iter().map(|b| b.capacity()).sum();
if kept + v.capacity() <= POOL_MAX_SAMPLES {
pool.push(v);
}
+178 -357
View File
@@ -5,39 +5,6 @@ use crate::header::{FilmGrainParams, SequenceHeader};
use crate::spec_tables::{GAUSSIAN_SEQUENCE, MC_IDENTITY};
#[inline]
/// One plane's scaling lookup (7.18.3.4) from its `n` points. The header rejects points whose
/// values don't strictly increase; a pair that still doesn't (defence in depth) is skipped
/// instead of dividing by zero. No points: all zero.
fn scaling_lut(n: usize, xs: &[u8], ys: &[u8]) -> [i32; 256] {
let mut l = [0i32; 256];
let n = n.min(xs.len()).min(ys.len());
let (Some(&x0), Some(&y0)) = (xs.first(), ys.first()) else { return l };
if n == 0 {
return l;
}
for v in l.iter_mut().take(x0 as usize) {
*v = y0 as i32;
}
for i in 0..n - 1 {
let (xa, xb, ya, yb) = (xs[i] as i32, xs[i + 1] as i32, ys[i] as i32, ys[i + 1] as i32);
let dx = xb - xa;
if dx <= 0 {
continue;
}
let delta = (yb - ya) * ((65536 + (dx >> 1)) / dx);
for x in 0..dx {
if let Some(v) = l.get_mut((xa + x) as usize) {
*v = ya + ((x * delta + 32768) >> 16);
}
}
}
let (xl, yl) = (xs[n - 1], ys[n - 1]);
for v in l.iter_mut().skip(xl as usize) {
*v = yl as i32;
}
l
}
fn round2(x: i32, n: u32) -> i32 {
if n == 0 { x } else { (x + (1 << (n - 1))) >> n }
}
@@ -55,79 +22,21 @@ impl Rng {
}
}
/// Picture-level parameters shared by the grain synthesis stages.
struct GrainCtx<'a> {
g: &'a FilmGrainParams,
bd: u32,
mono: bool,
sub_x: usize,
sub_y: usize,
w: usize,
h: usize,
grain_min: i32,
grain_max: i32,
}
pub(crate) fn apply(pic: &mut Picture, g: &FilmGrainParams, seq: &SequenceHeader) {
let _ = seq;
let bd = pic.bit_depth as u32;
let mono = pic.mono_chrome;
let num_planes = if mono { 1 } else { 3 };
let (sub_x, sub_y) = (pic.subsampling_x as usize, pic.subsampling_y as usize);
let w = pic.width as usize;
let h = pic.height as usize;
let grain_center = 128i32 << (bd - 8);
let grain_min = -grain_center;
let grain_max = (256i32 << (bd - 8)) - 1 - grain_center;
impl GrainCtx<'_> {
fn num_planes(&self) -> usize {
if self.mono { 1 } else { 3 }
}
fn grain_shift(&self) -> u32 {
12 - self.bd + self.g.grain_scale_shift
}
fn ar_shift(&self) -> u32 {
self.g.ar_coeff_shift_minus_6 + 6
}
fn lag(&self) -> i32 {
self.g.ar_coeff_lag as i32
}
fn stripe_w(&self) -> usize {
self.w + 64
}
}
type GrainTemplate = Vec<[i32; 82]>;
/// The luma, Cb and Cr grain templates (7.18.3.3).
struct Templates {
luma: GrainTemplate,
cb: GrainTemplate,
cr: GrainTemplate,
}
impl Templates {
fn plane(&self, plane: usize) -> &GrainTemplate {
match plane {
0 => &self.luma,
1 => &self.cb,
_ => &self.cr,
}
}
}
fn luma_ar_sum(g: &FilmGrainParams, luma: &[[i32; 82]], lag: i32, y: usize, x: usize) -> i32 {
let mut s = 0;
let mut pos = 0;
'outer: for dr in -lag..=0 {
for dc in -lag..=lag {
if dr == 0 && dc == 0 {
break 'outer;
}
let c = g.ar_coeffs_y_plus_128[pos] as i32 - 128;
s += luma[(y as i32 + dr) as usize][(x as i32 + dc) as usize] * c;
pos += 1;
}
}
s
}
fn luma_grain(c: &GrainCtx, rng: &mut Rng) -> GrainTemplate {
let g = c.g;
let shift = c.grain_shift();
// Generate grain (7.18.3.3).
let mut rng = Rng(g.grain_seed);
let shift = 12 - bd + g.grain_scale_shift;
let mut luma = vec![[0i32; 82]; 73];
for row in luma.iter_mut() {
for v in row.iter_mut() {
@@ -135,89 +44,77 @@ fn luma_grain(c: &GrainCtx, rng: &mut Rng) -> GrainTemplate {
*v = round2(gv, shift);
}
}
let ar_shift = c.ar_shift();
let lag = c.lag();
let ar_shift = g.ar_coeff_shift_minus_6 + 6;
let lag = g.ar_coeff_lag as i32;
for y in 3..73 {
for x in 3..82 - 3 {
let s = luma_ar_sum(g, &luma, lag, y, x);
luma[y][x] = (luma[y][x] + round2(s, ar_shift)).clamp(c.grain_min, c.grain_max);
}
}
luma
}
/// The luma contribution to the chroma autoregressive filter at chroma position (y, x).
fn chroma_luma_term(c: &GrainCtx, luma: &[[i32; 82]], y: usize, x: usize) -> i32 {
let mut l = 0;
let lx = ((x - 3) << c.sub_x) + 3;
let ly = ((y - 3) << c.sub_y) + 3;
for i in 0..=c.sub_y {
for j in 0..=c.sub_x {
l += luma[ly + i][lx + j];
}
}
round2(l, (c.sub_x + c.sub_y) as u32)
}
fn chroma_ar_sums(c: &GrainCtx, t: &Templates, y: usize, x: usize) -> (i32, i32) {
let g = c.g;
let lag = c.lag();
let mut s0 = 0;
let mut s1 = 0;
let mut pos = 0;
'outer: for dr in -lag..=0 {
for dc in -lag..=lag {
let c0 = g.ar_coeffs_cb_plus_128[pos] as i32 - 128;
let c1 = g.ar_coeffs_cr_plus_128[pos] as i32 - 128;
if dr == 0 && dc == 0 {
if g.num_y_points > 0 {
let l = chroma_luma_term(c, &t.luma, y, x);
s0 += l * c0;
s1 += l * c1;
let mut s = 0;
let mut pos = 0;
'outer: for dr in -lag..=0 {
for dc in -lag..=lag {
if dr == 0 && dc == 0 {
break 'outer;
}
let c = g.ar_coeffs_y_plus_128[pos] as i32 - 128;
s += luma[(y as i32 + dr) as usize][(x as i32 + dc) as usize] * c;
pos += 1;
}
break 'outer;
}
let (yy, xx) = ((y as i32 + dr) as usize, (x as i32 + dc) as usize);
s0 += t.cb[yy][xx] * c0;
s1 += t.cr[yy][xx] * c1;
pos += 1;
luma[y][x] = (luma[y][x] + round2(s, ar_shift)).clamp(grain_min, grain_max);
}
}
(s0, s1)
}
/// Chroma grain templates; zero for monochrome pictures.
fn chroma_grain(c: &GrainCtx, rng: &mut Rng, luma: GrainTemplate) -> Templates {
let g = c.g;
let mut t = Templates { luma, cb: vec![[0i32; 82]; 73], cr: vec![[0i32; 82]; 73] };
if c.mono {
return t;
}
let shift = c.grain_shift();
let ar_shift = c.ar_shift();
let chroma_w = if c.sub_x != 0 { 44 } else { 82 };
let chroma_h = if c.sub_y != 0 { 38 } else { 73 };
for (arr, seed, on) in [(&mut t.cb, 0xb524u32, g.num_cb_points > 0), (&mut t.cr, 0x49d8, g.num_cr_points > 0)] {
rng.0 = g.grain_seed ^ seed;
for row in arr.iter_mut().take(chroma_h) {
for v in row.iter_mut().take(chroma_w) {
let gv = if on || g.chroma_scaling_from_luma { GAUSSIAN_SEQUENCE[rng.next(11) as usize] as i32 } else { 0 };
*v = round2(gv, shift);
let chroma_w = if sub_x != 0 { 44 } else { 82 };
let chroma_h = if sub_y != 0 { 38 } else { 73 };
let mut cb = vec![[0i32; 82]; 73];
let mut cr = vec![[0i32; 82]; 73];
if !mono {
for (arr, seed, on) in [(&mut cb, 0xb524u32, g.num_cb_points > 0), (&mut cr, 0x49d8, g.num_cr_points > 0)] {
rng.0 = g.grain_seed ^ seed;
for row in arr.iter_mut().take(chroma_h) {
for v in row.iter_mut().take(chroma_w) {
let gv = if on || g.chroma_scaling_from_luma { GAUSSIAN_SEQUENCE[rng.next(11) as usize] as i32 } else { 0 };
*v = round2(gv, shift);
}
}
}
for y in 3..chroma_h {
for x in 3..chroma_w - 3 {
let mut s0 = 0;
let mut s1 = 0;
let mut pos = 0;
'outer: for dr in -lag..=0 {
for dc in -lag..=lag {
let c0 = g.ar_coeffs_cb_plus_128[pos] as i32 - 128;
let c1 = g.ar_coeffs_cr_plus_128[pos] as i32 - 128;
if dr == 0 && dc == 0 {
if g.num_y_points > 0 {
let mut l = 0;
let lx = ((x - 3) << sub_x) + 3;
let ly = ((y - 3) << sub_y) + 3;
for i in 0..=sub_y {
for j in 0..=sub_x {
l += luma[ly + i][lx + j];
}
}
let l = round2(l, (sub_x + sub_y) as u32);
s0 += l * c0;
s1 += l * c1;
}
break 'outer;
}
let (yy, xx) = ((y as i32 + dr) as usize, (x as i32 + dc) as usize);
s0 += cb[yy][xx] * c0;
s1 += cr[yy][xx] * c1;
pos += 1;
}
}
cb[y][x] = (cb[y][x] + round2(s0, ar_shift)).clamp(grain_min, grain_max);
cr[y][x] = (cr[y][x] + round2(s1, ar_shift)).clamp(grain_min, grain_max);
}
}
}
for y in 3..chroma_h {
for x in 3..chroma_w - 3 {
let (s0, s1) = chroma_ar_sums(c, &t, y, x);
t.cb[y][x] = (t.cb[y][x] + round2(s0, ar_shift)).clamp(c.grain_min, c.grain_max);
t.cr[y][x] = (t.cr[y][x] + round2(s1, ar_shift)).clamp(c.grain_min, c.grain_max);
}
}
t
}
/// Scaling lookup tables (7.18.3.4), one per plane.
fn scaling_luts(g: &FilmGrainParams, num_planes: usize) -> [[i32; 256]; 3] {
// Scaling lookup (7.18.3.4).
let mut lut = [[0i32; 256]; 3];
for (plane, l) in lut.iter_mut().enumerate().take(num_planes) {
let (n, xs, ys) = if plane == 0 || g.chroma_scaling_from_luma {
@@ -227,143 +124,119 @@ fn scaling_luts(g: &FilmGrainParams, num_planes: usize) -> [[i32; 256]; 3] {
} else {
(g.num_cr_points, &g.point_cr_value, &g.point_cr_scaling)
};
*l = scaling_lut(n, xs, ys);
if n == 0 {
continue;
}
for v in l.iter_mut().take(xs[0] as usize) {
*v = ys[0] as i32;
}
for i in 0..n - 1 {
let dy = ys[i + 1] as i32 - ys[i] as i32;
let dx = xs[i + 1] as i32 - xs[i] as i32;
let delta = dy * ((65536 + (dx >> 1)) / dx);
for x in 0..dx {
l[xs[i] as usize + x as usize] = ys[i] as i32 + ((x * delta + 32768) >> 16);
}
}
for v in l.iter_mut().skip(xs[n - 1] as usize) {
*v = ys[n - 1] as i32;
}
}
lut
}
let scale_lut = |plane: usize, index: i32| -> i32 {
let sh = bd - 8;
let x = index >> sh;
let rem = index - (x << sh);
if bd == 8 || x == 255 {
lut[plane][x as usize]
} else {
let start = lut[plane][x as usize];
let end = lut[plane][x as usize + 1];
start + round2((end - start) * rem, sh)
}
};
fn scale_lookup(lut: &[[i32; 256]; 3], bd: u32, plane: usize, index: i32) -> i32 {
let sh = bd - 8;
let x = index >> sh;
let rem = index - (x << sh);
if bd == 8 || x == 255 {
lut[plane][x as usize]
} else {
let start = lut[plane][x as usize];
let end = lut[plane][x as usize + 1];
start + round2((end - start) * rem, sh)
}
}
/// Fills one plane of a noise stripe from the grain template at stripe column `x`.
fn fill_stripe_plane(c: &GrainCtx, src: &GrainTemplate, s: &mut [i32], plane: usize, offsets: (usize, usize), x: usize) {
let (off_x, off_y) = offsets;
let stripe_w = c.stripe_w();
let overlap = c.g.overlap_flag;
let psx = if plane > 0 { c.sub_x } else { 0 };
let psy = if plane > 0 { c.sub_y } else { 0 };
let pox = if psx != 0 { 6 + off_x } else { 9 + off_x * 2 };
let poy = if psy != 0 { 6 + off_y } else { 9 + off_y * 2 };
for i in 0..(34 >> psy) {
for j in 0..(34 >> psx) {
let mut gv = src[poy + i][pox + j];
let (idx, blend) = if psx == 0 { (i * stripe_w + x * 2 + j, j < 2) } else { (i * stripe_w + x + j, j == 0) };
if blend && overlap && x > 0 {
let old = s[idx];
gv = if psx != 0 {
old * 23 + gv * 22
} else if j == 0 {
old * 27 + gv * 17
} else {
old * 17 + gv * 27
// Noise stripes (7.18.3.5).
let stripe_w = w + 64;
let n_stripes = (h.div_ceil(2)).div_ceil(16).max(1);
let mut stripes: Vec<[Vec<i32>; 3]> = (0..n_stripes).map(|_| [vec![0; 34 * stripe_w], vec![0; 34 * stripe_w], vec![0; 34 * stripe_w]]).collect();
let overlap = g.overlap_flag;
for (luma_num, stripe) in stripes.iter_mut().enumerate() {
let mut r = g.grain_seed;
r ^= (((luma_num * 37 + 178) & 255) << 8) as u32;
r ^= ((luma_num * 173 + 105) & 255) as u32;
rng.0 = r;
let mut x = 0;
while x < w.div_ceil(2) {
let rand = rng.next(8) as usize;
let off_x = rand >> 4;
let off_y = rand & 15;
for (plane, s) in stripe.iter_mut().enumerate().take(num_planes) {
let psx = if plane > 0 { sub_x } else { 0 };
let psy = if plane > 0 { sub_y } else { 0 };
let pox = if psx != 0 { 6 + off_x } else { 9 + off_x * 2 };
let poy = if psy != 0 { 6 + off_y } else { 9 + off_y * 2 };
let src = match plane {
0 => &luma,
1 => &cb,
_ => &cr,
};
gv = round2(gv, 5).clamp(c.grain_min, c.grain_max);
}
s[idx] = gv;
}
}
}
/// Noise stripes (7.18.3.5).
struct Stripes {
data: Vec<[Vec<i32>; 3]>,
stripe_w: usize,
overlap: bool,
sub_y: usize,
grain_min: i32,
grain_max: i32,
}
impl Stripes {
fn build(c: &GrainCtx, t: &Templates, rng: &mut Rng) -> Stripes {
let g = c.g;
let stripe_w = c.stripe_w();
let n_stripes = (c.h.div_ceil(2)).div_ceil(16).max(1);
let mut data: Vec<[Vec<i32>; 3]> = (0..n_stripes).map(|_| [vec![0; 34 * stripe_w], vec![0; 34 * stripe_w], vec![0; 34 * stripe_w]]).collect();
for (luma_num, stripe) in data.iter_mut().enumerate() {
let mut r = g.grain_seed;
r ^= (((luma_num * 37 + 178) & 255) << 8) as u32;
r ^= ((luma_num * 173 + 105) & 255) as u32;
rng.0 = r;
let mut x = 0;
while x < c.w.div_ceil(2) {
let rand = rng.next(8) as usize;
let offsets = (rand >> 4, rand & 15);
for (plane, s) in stripe.iter_mut().enumerate().take(c.num_planes()) {
fill_stripe_plane(c, t.plane(plane), s, plane, offsets, x);
for i in 0..(34 >> psy) {
for j in 0..(34 >> psx) {
let mut gv = src[poy + i][pox + j];
if psx == 0 {
let idx = i * stripe_w + x * 2 + j;
if j < 2 && overlap && x > 0 {
let old = s[idx];
gv = if j == 0 { old * 27 + gv * 17 } else { old * 17 + gv * 27 };
gv = round2(gv, 5).clamp(grain_min, grain_max);
}
s[idx] = gv;
} else {
let idx = i * stripe_w + x + j;
if j == 0 && overlap && x > 0 {
let old = s[idx];
gv = round2(old * 23 + gv * 22, 5).clamp(grain_min, grain_max);
}
s[idx] = gv;
}
}
}
x += 16;
}
x += 16;
}
Stripes { data, stripe_w, overlap: g.overlap_flag, sub_y: c.sub_y, grain_min: c.grain_min, grain_max: c.grain_max }
}
fn noise_at(&self, plane: usize, y: usize, x: usize) -> i32 {
let psy = if plane > 0 { self.sub_y } else { 0 };
let noise_at = |plane: usize, y: usize, x: usize| -> i32 {
let psy = if plane > 0 { sub_y } else { 0 };
let luma_num = y >> (5 - psy);
let i = y - (luma_num << (5 - psy));
let mut gv = self.data[luma_num][plane][i * self.stripe_w + x];
let mut gv = stripes[luma_num][plane][i * stripe_w + x];
if psy == 0 {
if i < 2 && luma_num > 0 && self.overlap {
let old = self.data[luma_num - 1][plane][(i + 32) * self.stripe_w + x];
if i < 2 && luma_num > 0 && overlap {
let old = stripes[luma_num - 1][plane][(i + 32) * stripe_w + x];
gv = if i == 0 { old * 27 + gv * 17 } else { old * 17 + gv * 27 };
gv = round2(gv, 5).clamp(self.grain_min, self.grain_max);
gv = round2(gv, 5).clamp(grain_min, grain_max);
}
} else if i < 1 && luma_num > 0 && self.overlap {
let old = self.data[luma_num - 1][plane][(i + 16) * self.stripe_w + x];
gv = round2(old * 23 + gv * 22, 5).clamp(self.grain_min, self.grain_max);
} else if i < 1 && luma_num > 0 && overlap {
let old = stripes[luma_num - 1][plane][(i + 16) * stripe_w + x];
gv = round2(old * 23 + gv * 22, 5).clamp(grain_min, grain_max);
}
gv
}
}
};
/// Output clipping range and scaling shift for the blend step (7.18.3.5).
struct BlendRange {
min_value: i32,
max_luma: i32,
max_chroma: i32,
pix_max: i32,
scaling_shift: u32,
}
impl BlendRange {
fn new(c: &GrainCtx, matrix_coefficients: usize) -> BlendRange {
let bd = c.bd;
let (min_value, max_luma, max_chroma) = if c.g.clip_to_restricted_range {
let ml = 235 << (bd - 8);
(16 << (bd - 8), ml, if matrix_coefficients == MC_IDENTITY { ml } else { 240 << (bd - 8) })
} else {
let m = (256 << (bd - 8)) - 1;
(0, m, m)
};
BlendRange { min_value, max_luma, max_chroma, pix_max: (1i32 << bd) - 1, scaling_shift: c.g.grain_scaling_minus_8 + 8 }
}
}
struct BlendEnv<'a> {
c: &'a GrainCtx<'a>,
lut: &'a [[i32; 256]; 3],
stripes: &'a Stripes,
range: &'a BlendRange,
}
impl BlendEnv<'_> {
fn blend_chroma(&self, py: &[u16], pu: &mut [u16], pv: &mut [u16]) {
let c = self.c;
let g = c.g;
let (w, h, sub_x, sub_y, bd) = (c.w, c.h, c.sub_x, c.sub_y, c.bd);
// Blend (7.18.3.5).
let (min_value, max_luma, max_chroma) = if g.clip_to_restricted_range {
let ml = 235 << (bd - 8);
(16 << (bd - 8), ml, if pic.matrix_coefficients as usize == MC_IDENTITY { ml } else { 240 << (bd - 8) })
} else {
let m = (256 << (bd - 8)) - 1;
(0, m, m)
};
let pix_max = (1i32 << bd) - 1;
let scaling_shift = g.grain_scaling_minus_8 + 8;
if !mono {
let cw = (w + sub_x) >> sub_x;
let ch = (h + sub_y) >> sub_y;
let [py, pu, pv] = &mut pic.planes;
for y in 0..ch {
for x in 0..cw {
let lx = x << sub_x;
@@ -382,74 +255,22 @@ impl BlendEnv<'_> {
avg
} else {
let combined = avg * (luma_mult as i32 - 128) + orig * (mult as i32 - 128);
((combined >> 6) + ((offset as i32 - 256) << (bd - 8))).clamp(0, self.range.pix_max)
((combined >> 6) + ((offset as i32 - 256) << (bd - 8))).clamp(0, pix_max)
};
let noise = round2(scale_lookup(self.lut, bd, plane, merged) * self.stripes.noise_at(plane, y, x), self.range.scaling_shift);
out[y * cw + x] = (orig + noise).clamp(self.range.min_value, self.range.max_chroma) as u16;
let noise = round2(scale_lut(plane, merged) * noise_at(plane, y, x), scaling_shift);
out[y * cw + x] = (orig + noise).clamp(min_value, max_chroma) as u16;
}
}
}
}
fn blend_luma(&self, py: &mut [u16]) {
let (w, h) = (self.c.w, self.c.h);
if g.num_y_points > 0 {
let py = &mut pic.planes[0];
for y in 0..h {
for x in 0..w {
let orig = py[y * w + x] as i32;
let noise = round2(scale_lookup(self.lut, self.c.bd, 0, orig) * self.stripes.noise_at(0, y, x), self.range.scaling_shift);
py[y * w + x] = (orig + noise).clamp(self.range.min_value, self.range.max_luma) as u16;
let noise = round2(scale_lut(0, orig) * noise_at(0, y, x), scaling_shift);
py[y * w + x] = (orig + noise).clamp(min_value, max_luma) as u16;
}
}
}
}
pub(crate) fn apply(pic: &mut Picture, g: &FilmGrainParams, seq: &SequenceHeader) {
let _ = seq;
let bd = pic.bit_depth as u32;
let grain_center = 128i32 << (bd - 8);
let c = GrainCtx {
g,
bd,
mono: pic.mono_chrome,
sub_x: pic.subsampling_x as usize,
sub_y: pic.subsampling_y as usize,
w: pic.width as usize,
h: pic.height as usize,
grain_min: -grain_center,
grain_max: (256i32 << (bd - 8)) - 1 - grain_center,
};
// Generate grain (7.18.3.3).
let mut rng = Rng(g.grain_seed);
let luma = luma_grain(&c, &mut rng);
let templates = chroma_grain(&c, &mut rng, luma);
let lut = scaling_luts(g, c.num_planes());
let stripes = Stripes::build(&c, &templates, &mut rng);
// Blend (7.18.3.5).
let range = BlendRange::new(&c, pic.matrix_coefficients as usize);
let env = BlendEnv { c: &c, lut: &lut, stripes: &stripes, range: &range };
if !c.mono {
let [py, pu, pv] = &mut pic.planes;
env.blend_chroma(py, pu, pv);
}
if g.num_y_points > 0 {
env.blend_luma(&mut pic.planes[0]);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scaling_lut_interpolates_and_tolerates_duplicate_points() {
let l = scaling_lut(2, &[0, 255], &[0, 255]);
assert_eq!((l[0], l[128], l[255]), (0, 128, 255));
// Duplicate and descending x values don't divide by zero.
let l = scaling_lut(4, &[10, 10, 5, 200], &[20, 40, 60, 80]);
assert_eq!(l[0], 20);
assert_eq!(l[255], 80);
assert_eq!(scaling_lut(0, &[], &[]), [0; 256]);
}
}
+179 -259
View File
@@ -1,14 +1,7 @@
//! Sequence header (5.5) and uncompressed frame header (5.9) parsing.
use crate::bits::BitReader;
use crate::spec_tables::{
AFFINE, ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GM_ABS_ALPHA_BITS, GM_ABS_TRANS_BITS, GM_ABS_TRANS_ONLY_BITS, GM_ALPHA_PREC_BITS,
GM_TRANS_ONLY_PREC_BITS, GM_TRANS_PREC_BITS, GOLDEN_FRAME, IDENTITY, INTER_FRAME, INTRA_ONLY_FRAME, KEY_FRAME, LAST_FRAME, MAX_SEGMENTS,
MAX_TILE_AREA, MAX_TILE_COLS, MAX_TILE_ROWS, MAX_TILE_WIDTH, NUM_REF_FRAMES, ONLY_4X4, PRIMARY_REF_NONE, REF_FRAME_LIST, REFS_PER_FRAME,
RESTORATION_TILESIZE_MAX, RESTORE_NONE, RESTORE_SGRPROJ, RESTORE_SWITCHABLE, RESTORE_WIENER, ROTZOOM, SEG_LVL_ALT_Q, SEG_LVL_MAX,
SEG_LVL_REF_FRAME, SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SUPERRES_DENOM_BITS, SUPERRES_DENOM_MIN, SUPERRES_NUM, SWITCH_FRAME,
TOTAL_REFS_PER_FRAME, TRANSLATION, TX_MODE_LARGEST, TX_MODE_SELECT, WARPEDMODEL_PREC_BITS,
};
use crate::spec_tables::*;
use crate::{Error, Result};
pub const EIGHTTAP: u8 = 0;
@@ -360,10 +353,6 @@ pub struct RefInfo {
pub lf_deltas: LoopFilterDeltas,
pub seg_features: SegmentationFeatures,
pub grain: FilmGrainParams,
/// The colour format the frame was decoded in (a later sequence header may change it).
pub subsampling_x: u8,
pub subsampling_y: u8,
pub mono_chrome: bool,
}
/// A parsed uncompressed frame header with its derived variables.
@@ -433,38 +422,6 @@ pub struct FrameHeader {
pub spatial_id: u32,
}
/// mark_ref_frames( idLen ): invalidates reference slots whose frame id is too far from the current one.
fn mark_ref_frames(st: &mut HeaderState, cur: u32, id_len: u32) {
let diff_len = st.seq.delta_frame_id_length_minus_2 + 2;
for rs in st.refs.iter_mut() {
if cur > (1 << diff_len) {
if rs.frame_id > cur || rs.frame_id < cur - (1 << diff_len) {
rs.valid = false;
}
} else if rs.frame_id > cur && rs.frame_id < (1 << id_len) + cur - (1 << diff_len) {
rs.valid = false;
}
}
}
/// Skips buffer_removal_time for every operating point that includes this layer.
fn skip_buffer_removal_times(r: &mut BitReader, seq: &SequenceHeader, temporal_id: u32, spatial_id: u32) -> Result<()> {
if !(seq.decoder_model_info_present && r.flag()?) {
return Ok(());
}
for op in 0..=seq.operating_points_cnt_minus_1 {
if seq.decoder_model_present_for_this_op[op] {
let idc = seq.operating_point_idc[op];
let in_t = (idc >> temporal_id) & 1;
let in_s = (idc >> (spatial_id + 8)) & 1;
if idc == 0 || (in_t == 1 && in_s == 1) {
r.f(seq.buffer_removal_time_length_minus_1 + 1)?;
}
}
}
Ok(())
}
impl FrameHeader {
pub fn get_relative_dist(&self, seq: &SequenceHeader, a: u32, b: u32) -> i32 {
relative_dist(seq, a, b)
@@ -530,10 +487,35 @@ impl FrameHeader {
} else {
h.show_existing_frame = r.flag()?;
if h.show_existing_frame {
h.parse_show_existing_frame(r, st, id_len)?;
h.frame_to_show_map_idx = r.f(3)? as usize;
if seq.decoder_model_info_present && !seq.equal_picture_interval {
r.f(seq.frame_presentation_time_length_minus_1 + 1)?;
}
if seq.frame_id_numbers_present {
r.f(id_len)?;
}
let rs = &st.refs[h.frame_to_show_map_idx];
if !rs.valid {
return Err(Error::Invalid("show_existing_frame of an empty slot"));
}
h.frame_type = rs.frame_type;
if h.frame_type == KEY_FRAME as u8 {
h.refresh_frame_flags = all_frames;
}
if seq.film_grain_params_present {
h.film_grain = rs.grain.clone();
}
return Ok(h);
}
h.parse_frame_type_and_flags(r, seq)?;
h.frame_type = r.f(2)? as u8;
h.frame_is_intra = h.frame_type == INTRA_ONLY_FRAME as u8 || h.frame_type == KEY_FRAME as u8;
h.show_frame = r.flag()?;
if h.show_frame && seq.decoder_model_info_present && !seq.equal_picture_interval {
r.f(seq.frame_presentation_time_length_minus_1 + 1)?;
}
h.showable_frame = if h.show_frame { h.frame_type != KEY_FRAME as u8 } else { r.flag()? };
h.error_resilient_mode =
if h.frame_type == SWITCH_FRAME as u8 || (h.frame_type == KEY_FRAME as u8 && h.show_frame) { true } else { r.flag()? };
}
if h.frame_type == KEY_FRAME as u8 && h.show_frame {
for rs in st.refs.iter_mut() {
@@ -544,11 +526,33 @@ impl FrameHeader {
h.order_hints[LAST_FRAME + i] = 0;
}
}
h.parse_screen_content_flags(r, seq)?;
h.disable_cdf_update = r.flag()?;
h.allow_screen_content_tools = if seq.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS as u32 {
r.flag()?
} else {
seq.seq_force_screen_content_tools != 0
};
if h.allow_screen_content_tools {
h.force_integer_mv = if seq.seq_force_integer_mv == SELECT_INTEGER_MV as u32 { r.flag()? } else { seq.seq_force_integer_mv != 0 };
}
if h.frame_is_intra {
h.force_integer_mv = true;
}
if seq.frame_id_numbers_present {
h.current_frame_id = r.f(id_len)?;
mark_ref_frames(st, h.current_frame_id, id_len);
st.current_frame_id = h.current_frame_id;
// mark_ref_frames( idLen )
let diff_len = seq.delta_frame_id_length_minus_2 + 2;
let cur = h.current_frame_id;
for rs in st.refs.iter_mut() {
if cur > (1 << diff_len) {
if rs.frame_id > cur || rs.frame_id < cur - (1 << diff_len) {
rs.valid = false;
}
} else if rs.frame_id > cur && rs.frame_id < (1 << id_len) + cur - (1 << diff_len) {
rs.valid = false;
}
}
st.current_frame_id = cur;
}
h.frame_size_override_flag = if h.frame_type == SWITCH_FRAME as u8 {
true
@@ -559,7 +563,18 @@ impl FrameHeader {
};
h.order_hint = r.f(seq.order_hint_bits)?;
h.primary_ref_frame = if h.frame_is_intra || h.error_resilient_mode { PRIMARY_REF_NONE } else { r.f(3)? as usize };
skip_buffer_removal_times(r, seq, temporal_id, spatial_id)?;
if seq.decoder_model_info_present && r.flag()? {
for op in 0..=seq.operating_points_cnt_minus_1 {
if seq.decoder_model_present_for_this_op[op] {
let idc = seq.operating_point_idc[op];
let in_t = (idc >> temporal_id) & 1;
let in_s = (idc >> (spatial_id + 8)) & 1;
if idc == 0 || (in_t == 1 && in_s == 1) {
r.f(seq.buffer_removal_time_length_minus_1 + 1)?;
}
}
}
}
h.refresh_frame_flags =
if h.frame_type == SWITCH_FRAME as u8 || (h.frame_type == KEY_FRAME as u8 && h.show_frame) { all_frames } else { r.f(8)? };
if (!h.frame_is_intra || h.refresh_frame_flags != all_frames) && h.error_resilient_mode && seq.enable_order_hint {
@@ -577,16 +592,126 @@ impl FrameHeader {
h.allow_intrabc = r.flag()?;
}
} else {
h.parse_inter_frame_refs(r, st)?;
let mut short = false;
if seq.enable_order_hint {
short = r.flag()?;
if short {
let last = r.f(3)? as usize;
let gold = r.f(3)? as usize;
h.set_frame_refs(seq, st.refs, last, gold);
}
}
for i in 0..REFS_PER_FRAME {
if !short {
h.ref_frame_idx[i] = r.f(3)? as usize;
}
if seq.frame_id_numbers_present {
r.f(seq.delta_frame_id_length_minus_2 + 2)?;
}
}
for i in 0..REFS_PER_FRAME {
if !st.refs[h.ref_frame_idx[i]].valid {
return Err(Error::Invalid("reference to an empty slot"));
}
}
if h.frame_size_override_flag && !h.error_resilient_mode {
// frame_size_with_refs( )
let mut found = false;
for i in 0..REFS_PER_FRAME {
if r.flag()? {
let rs = &st.refs[h.ref_frame_idx[i]];
h.upscaled_width = rs.upscaled_width;
h.frame_width = h.upscaled_width;
h.frame_height = rs.frame_height;
h.render_width = rs.render_width;
h.render_height = rs.render_height;
found = true;
break;
}
}
if !found {
h.frame_size(r, seq)?;
h.render_size(r)?;
} else {
h.superres_params(r, seq)?;
h.compute_image_size();
}
} else {
h.frame_size(r, seq)?;
h.render_size(r)?;
}
h.allow_high_precision_mv = if h.force_integer_mv { false } else { r.flag()? };
h.interpolation_filter = if r.flag()? { SWITCHABLE } else { r.f(2)? as u8 };
h.is_motion_mode_switchable = r.flag()?;
h.use_ref_frame_mvs = if h.error_resilient_mode || !seq.enable_ref_frame_mvs { false } else { r.flag()? };
for i in 0..REFS_PER_FRAME {
let rf = LAST_FRAME + i;
let hint = st.refs[h.ref_frame_idx[i]].order_hint;
h.order_hints[rf] = hint;
h.ref_frame_sign_bias[rf] = seq.enable_order_hint && relative_dist(seq, hint, h.order_hint) > 0;
}
}
h.disable_frame_end_update_cdf = if seq.reduced_still_picture_header || h.disable_cdf_update { true } else { r.flag()? };
h.setup_or_load_previous(st);
if h.primary_ref_frame == PRIMARY_REF_NONE {
// setup_past_independence( )
st.seg_features = SegmentationFeatures::default();
st.prev_gm_params = default_gm_params();
st.lf_deltas = LoopFilterDeltas::defaults();
h.lf.delta_enabled = true;
} else {
// load_previous( )
let prev = &st.refs[h.ref_frame_idx[h.primary_ref_frame]];
st.prev_gm_params = prev.gm_params;
st.lf_deltas = prev.lf_deltas;
st.seg_features = prev.seg_features;
}
h.prev_gm_params = st.prev_gm_params;
h.tile_info(r, seq)?;
h.quantization_params(r, seq)?;
h.segmentation_params(r, st)?;
h.delta_q_lf_params(r)?;
h.compute_lossless();
// delta_q_params( )
if h.quant.base_q_idx > 0 {
h.delta_q_present = r.flag()?;
}
if h.delta_q_present {
h.delta_q_res = r.f(2)?;
}
// delta_lf_params( )
if h.delta_q_present {
if !h.allow_intrabc {
h.delta_lf_present = r.flag()?;
}
if h.delta_lf_present {
h.delta_lf_res = r.f(2)?;
h.delta_lf_multi = r.flag()?;
}
}
h.coded_lossless = true;
for seg_id in 0..MAX_SEGMENTS {
let q = h.get_qindex(true, seg_id, 0);
let ll = q == 0
&& h.quant.delta_q_y_dc == 0
&& h.quant.delta_q_u_ac == 0
&& h.quant.delta_q_u_dc == 0
&& h.quant.delta_q_v_ac == 0
&& h.quant.delta_q_v_dc == 0;
h.lossless_array[seg_id] = ll;
if !ll {
h.coded_lossless = false;
}
if h.quant.using_qmatrix {
if ll {
h.seg_qm_level[0][seg_id] = 15;
h.seg_qm_level[1][seg_id] = 15;
h.seg_qm_level[2][seg_id] = 15;
} else {
h.seg_qm_level[0][seg_id] = h.quant.qm_y;
h.seg_qm_level[1][seg_id] = h.quant.qm_u;
h.seg_qm_level[2][seg_id] = h.quant.qm_v;
}
}
}
h.all_lossless = h.coded_lossless && h.frame_width == h.upscaled_width;
h.loop_filter_params(r, seq, st)?;
h.cdef_params(r, seq)?;
h.lr_params(r, seq)?;
@@ -607,182 +732,6 @@ impl FrameHeader {
Ok(h)
}
/// The show_existing_frame branch: picks the slot to show and inherits its frame type and grain.
fn parse_show_existing_frame(&mut self, r: &mut BitReader, st: &HeaderState, id_len: u32) -> Result<()> {
let seq = st.seq;
self.frame_to_show_map_idx = r.f(3)? as usize;
if seq.decoder_model_info_present && !seq.equal_picture_interval {
r.f(seq.frame_presentation_time_length_minus_1 + 1)?;
}
if seq.frame_id_numbers_present {
r.f(id_len)?;
}
let rs = &st.refs[self.frame_to_show_map_idx];
if !rs.valid {
return Err(Error::Invalid("show_existing_frame of an empty slot"));
}
self.frame_type = rs.frame_type;
if self.frame_type == KEY_FRAME as u8 {
self.refresh_frame_flags = (1u32 << NUM_REF_FRAMES) - 1;
}
if seq.film_grain_params_present {
self.film_grain = rs.grain.clone();
}
Ok(())
}
/// frame_type, show_frame, showable_frame and error_resilient_mode.
fn parse_frame_type_and_flags(&mut self, r: &mut BitReader, seq: &SequenceHeader) -> Result<()> {
self.frame_type = r.f(2)? as u8;
self.frame_is_intra = self.frame_type == INTRA_ONLY_FRAME as u8 || self.frame_type == KEY_FRAME as u8;
self.show_frame = r.flag()?;
if self.show_frame && seq.decoder_model_info_present && !seq.equal_picture_interval {
r.f(seq.frame_presentation_time_length_minus_1 + 1)?;
}
self.showable_frame = if self.show_frame { self.frame_type != KEY_FRAME as u8 } else { r.flag()? };
self.error_resilient_mode =
if self.frame_type == SWITCH_FRAME as u8 || (self.frame_type == KEY_FRAME as u8 && self.show_frame) { true } else { r.flag()? };
Ok(())
}
/// disable_cdf_update, allow_screen_content_tools and force_integer_mv.
fn parse_screen_content_flags(&mut self, r: &mut BitReader, seq: &SequenceHeader) -> Result<()> {
self.disable_cdf_update = r.flag()?;
self.allow_screen_content_tools = if seq.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS as u32 {
r.flag()?
} else {
seq.seq_force_screen_content_tools != 0
};
if self.allow_screen_content_tools {
self.force_integer_mv = if seq.seq_force_integer_mv == SELECT_INTEGER_MV as u32 { r.flag()? } else { seq.seq_force_integer_mv != 0 };
}
if self.frame_is_intra {
self.force_integer_mv = true;
}
Ok(())
}
/// Reference selection, frame size, motion vector precision and filter flags of an inter frame.
fn parse_inter_frame_refs(&mut self, r: &mut BitReader, st: &HeaderState) -> Result<()> {
let seq = st.seq;
let mut short = false;
if seq.enable_order_hint {
short = r.flag()?;
if short {
let last = r.f(3)? as usize;
let gold = r.f(3)? as usize;
self.set_frame_refs(seq, st.refs, last, gold);
}
}
for i in 0..REFS_PER_FRAME {
if !short {
self.ref_frame_idx[i] = r.f(3)? as usize;
}
if seq.frame_id_numbers_present {
r.f(seq.delta_frame_id_length_minus_2 + 2)?;
}
}
for i in 0..REFS_PER_FRAME {
if !st.refs[self.ref_frame_idx[i]].valid {
return Err(Error::Invalid("reference to an empty slot"));
}
}
if self.frame_size_override_flag && !self.error_resilient_mode {
self.frame_size_with_refs(r, seq, st.refs)?;
} else {
self.frame_size(r, seq)?;
self.render_size(r)?;
}
self.allow_high_precision_mv = if self.force_integer_mv { false } else { r.flag()? };
self.interpolation_filter = if r.flag()? { SWITCHABLE } else { r.f(2)? as u8 };
self.is_motion_mode_switchable = r.flag()?;
self.use_ref_frame_mvs = if self.error_resilient_mode || !seq.enable_ref_frame_mvs { false } else { r.flag()? };
for i in 0..REFS_PER_FRAME {
let rf = LAST_FRAME + i;
let hint = st.refs[self.ref_frame_idx[i]].order_hint;
self.order_hints[rf] = hint;
self.ref_frame_sign_bias[rf] = seq.enable_order_hint && relative_dist(seq, hint, self.order_hint) > 0;
}
Ok(())
}
/// frame_size_with_refs( ).
fn frame_size_with_refs(&mut self, r: &mut BitReader, seq: &SequenceHeader, refs: &[RefInfo; NUM_REF_FRAMES]) -> Result<()> {
for i in 0..REFS_PER_FRAME {
if r.flag()? {
let rs = &refs[self.ref_frame_idx[i]];
self.upscaled_width = rs.upscaled_width;
self.frame_width = self.upscaled_width;
self.frame_height = rs.frame_height;
self.render_width = rs.render_width;
self.render_height = rs.render_height;
self.superres_params(r, seq)?;
self.compute_image_size();
return Ok(());
}
}
self.frame_size(r, seq)?;
self.render_size(r)
}
/// setup_past_independence( ) or load_previous( ), depending on primary_ref_frame.
fn setup_or_load_previous(&mut self, st: &mut HeaderState) {
if self.primary_ref_frame == PRIMARY_REF_NONE {
st.seg_features = SegmentationFeatures::default();
st.prev_gm_params = default_gm_params();
st.lf_deltas = LoopFilterDeltas::defaults();
self.lf.delta_enabled = true;
} else {
let prev = &st.refs[self.ref_frame_idx[self.primary_ref_frame]];
st.prev_gm_params = prev.gm_params;
st.lf_deltas = prev.lf_deltas;
st.seg_features = prev.seg_features;
}
}
/// delta_q_params( ) and delta_lf_params( ).
fn delta_q_lf_params(&mut self, r: &mut BitReader) -> Result<()> {
if self.quant.base_q_idx > 0 {
self.delta_q_present = r.flag()?;
}
if self.delta_q_present {
self.delta_q_res = r.f(2)?;
if !self.allow_intrabc {
self.delta_lf_present = r.flag()?;
}
if self.delta_lf_present {
self.delta_lf_res = r.f(2)?;
self.delta_lf_multi = r.flag()?;
}
}
Ok(())
}
/// Per-segment lossless flags, quantizer matrix levels and the frame-wide lossless flags.
fn compute_lossless(&mut self) {
self.coded_lossless = true;
for seg_id in 0..MAX_SEGMENTS {
let q = self.get_qindex(true, seg_id, 0);
let ll = q == 0
&& self.quant.delta_q_y_dc == 0
&& self.quant.delta_q_u_ac == 0
&& self.quant.delta_q_u_dc == 0
&& self.quant.delta_q_v_ac == 0
&& self.quant.delta_q_v_dc == 0;
self.lossless_array[seg_id] = ll;
if !ll {
self.coded_lossless = false;
}
if self.quant.using_qmatrix {
let levels = if ll { [15; 3] } else { [self.quant.qm_y, self.quant.qm_u, self.quant.qm_v] };
for (plane, level) in levels.into_iter().enumerate() {
self.seg_qm_level[plane][seg_id] = level;
}
}
}
self.all_lossless = self.coded_lossless && self.frame_width == self.upscaled_width;
}
fn superres_params(&mut self, r: &mut BitReader, seq: &SequenceHeader) -> Result<()> {
self.use_superres = if seq.enable_superres { r.flag()? } else { false };
self.superres_denom = if self.use_superres { r.f(SUPERRES_DENOM_BITS as u32)? + SUPERRES_DENOM_MIN as u32 } else { SUPERRES_NUM as u32 };
@@ -950,9 +899,6 @@ impl FrameHeader {
let mut widest = 0;
let mut start = 0;
while start < sb_cols {
if t.mi_col_starts.len() >= MAX_TILE_COLS {
return Err(Error::Invalid("tile_cols exceeds MAX_TILE_COLS"));
}
t.mi_col_starts.push(start << sb_shift);
let max_width = (sb_cols - start).min(max_tile_width_sb);
let size = r.ns(max_width)? + 1;
@@ -970,9 +916,6 @@ impl FrameHeader {
let max_tile_height_sb = (max_tile_area_sb / widest.max(1)).max(1);
let mut start = 0;
while start < sb_rows {
if t.mi_row_starts.len() >= MAX_TILE_ROWS {
return Err(Error::Invalid("tile_rows exceeds MAX_TILE_ROWS"));
}
t.mi_row_starts.push(start << sb_shift);
let max_height = (sb_rows - start).min(max_tile_height_sb);
let size = r.ns(max_height)? + 1;
@@ -1313,7 +1256,6 @@ impl FrameHeader {
g.point_y_value[i] = r.f(8)? as u8;
g.point_y_scaling[i] = r.f(8)? as u8;
}
check_increasing(&g.point_y_value[..g.num_y_points], "point_y_value")?;
g.chroma_scaling_from_luma = if seq.color.mono_chrome { false } else { r.flag()? };
if seq.color.mono_chrome
|| g.chroma_scaling_from_luma
@@ -1330,7 +1272,6 @@ impl FrameHeader {
g.point_cb_value[i] = r.f(8)? as u8;
g.point_cb_scaling[i] = r.f(8)? as u8;
}
check_increasing(&g.point_cb_value[..g.num_cb_points], "point_cb_value")?;
g.num_cr_points = r.f(4)? as usize;
if g.num_cr_points > 10 {
return Err(Error::Invalid("num_cr_points"));
@@ -1339,7 +1280,6 @@ impl FrameHeader {
g.point_cr_value[i] = r.f(8)? as u8;
g.point_cr_scaling[i] = r.f(8)? as u8;
}
check_increasing(&g.point_cr_value[..g.num_cr_points], "point_cr_value")?;
}
g.grain_scaling_minus_8 = r.f(2)?;
g.ar_coeff_lag = r.f(2)?;
@@ -1427,23 +1367,3 @@ fn decode_subexp(r: &mut BitReader, num_syms: i32) -> Result<i32> {
}
}
}
/// Film-grain scaling point values must strictly increase (AV1 spec 6.8.20); a duplicate would
/// divide by zero when the scaling lookup is built.
fn check_increasing(values: &[u8], what: &'static str) -> Result<()> {
if values.windows(2).all(|w| w[0] < w[1]) { Ok(()) } else { Err(Error::Invalid(what)) }
}
#[cfg(test)]
mod grain_point_tests {
use super::*;
#[test]
fn scaling_points_must_strictly_increase() {
assert!(check_increasing(&[], "p").is_ok());
assert!(check_increasing(&[7], "p").is_ok());
assert!(check_increasing(&[0, 10, 255], "p").is_ok());
assert!(matches!(check_increasing(&[0, 10, 10], "point_y_value"), Err(Error::Invalid("point_y_value"))));
assert!(check_increasing(&[20, 10], "p").is_err());
}
}
+50 -72
View File
@@ -5,16 +5,7 @@ use std::sync::OnceLock;
use crate::frame::Plane;
use crate::mvpred::round2_signed64;
use crate::spec_tables::{
BLOCK_8X8, BLOCK_SIZES, COMPOUND_AVERAGE, COMPOUND_DIFFWTD, COMPOUND_DISTANCE, COMPOUND_INTRA, COMPOUND_WEDGE, DIV_LUT, DIV_LUT_BITS,
DIV_LUT_PREC_BITS, EIGHTTAP, EIGHTTAP_SHARP, EIGHTTAP_SMOOTH, FILTER_BITS, GLOBAL_GLOBALMV, GLOBALMV, II_H_PRED, II_SMOOTH_PRED, II_V_PRED,
II_WEIGHTS_1D, INTRA_FRAME, LAST_FRAME, LOCALWARP, LS_MV_MAX, MASK_MASTER_SIZE, MAX_FRAME_DISTANCE, MAX_SB_SIZE, MI_HEIGHT_LOG2, MI_WIDTH_LOG2,
NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, OBMC, OBMC_MASK_2, OBMC_MASK_4, OBMC_MASK_8, OBMC_MASK_16, OBMC_MASK_32, QUANT_DIST_LOOKUP,
QUANT_DIST_WEIGHT, REF_SCALE_SHIFT, SCALE_SUBPEL_BITS, SUBPEL_BITS, SUBPEL_FILTERS, SUBPEL_MASK, TRANSLATION, WARP_PARAM_REDUCE_BITS,
WARPED_FILTERS, WARPEDDIFF_PREC_BITS, WARPEDMODEL_NONDIAGAFFINE_CLAMP, WARPEDMODEL_PREC_BITS, WARPEDMODEL_TRANS_CLAMP, WARPEDPIXEL_PREC_SHIFTS,
WEDGE_BITS, WEDGE_CODEBOOK, WEDGE_HORIZONTAL, WEDGE_MASTER_OBLIQUE_EVEN, WEDGE_MASTER_OBLIQUE_ODD, WEDGE_MASTER_VERTICAL, WEDGE_OBLIQUE27,
WEDGE_OBLIQUE63, WEDGE_OBLIQUE117, WEDGE_OBLIQUE153, WEDGE_TYPES, WEDGE_VERTICAL,
};
use crate::spec_tables::*;
use crate::tile::TileDecoder;
const PRED_STRIDE: usize = 128;
@@ -420,8 +411,20 @@ impl TileDecoder<'_, '_> {
let fh = &self.fs.fh;
for ref_list in 0..1 + is_compound as usize {
let ref_frame = cand_refs[ref_list];
let ym = self.b.y_mode;
let global =
(ym == GLOBALMV || ym == GLOBAL_GLOBALMV) && ref_frame > INTRA_FRAME as i8 && fh.gm_type[ref_frame as usize] as usize > TRANSLATION;
let global_valid = global && setup_shear(&fh.gm_params[ref_frame as usize]).0;
let ref_idx: i32 = if self.b.use_intrabc { -1 } else { fh.ref_frame_idx[ref_frame as usize - LAST_FRAME] as i32 };
let use_warp = self.warp_mode(ref_frame, ref_idx, w, h);
let use_warp = if w < 8 || h < 8 || fh.force_integer_mv {
0
} else if self.b.motion_mode as usize == LOCALWARP && self.b.local_valid {
1
} else if global && !self.is_scaled_ref(ref_idx) && global_valid {
2
} else {
0
};
let mv = [cand_mvs[ref_list].row as i32, cand_mvs[ref_list].col as i32];
if use_warp != 0 {
let params = if use_warp == 1 { self.b.local_warp_params } else { fh.gm_params[ref_frame as usize] };
@@ -436,7 +439,40 @@ impl TileDecoder<'_, '_> {
}
}
let ct = self.b.compound_type;
self.fill_blend_mask(plane, w, h, &preds, rnd.2);
if ct == COMPOUND_WEDGE && plane == 0 {
let m = &wedge_masks()[self.b.mi_size][self.b.wedge_index][self.b.wedge_sign];
for i in 0..h {
for j in 0..w {
self.mask[i * PRED_STRIDE + j] = m[i * w + j] as i32;
}
}
} else if ct == COMPOUND_INTRA {
let size_scale = MAX_SB_SIZE / h.max(w);
let im = self.b.interintra_mode;
for i in 0..h {
for j in 0..w {
self.mask[i * PRED_STRIDE + j] = if im == II_V_PRED {
II_WEIGHTS_1D[i * size_scale] as i32
} else if im == II_H_PRED {
II_WEIGHTS_1D[j * size_scale] as i32
} else if im == II_SMOOTH_PRED {
II_WEIGHTS_1D[i.min(j) * size_scale] as i32
} else {
32
};
}
}
} else if ct == COMPOUND_DIFFWTD && plane == 0 {
for i in 0..h {
for j in 0..w {
let k = i * PRED_STRIDE + j;
let diff = (preds[0][k] - preds[1][k]).abs();
let diff = round2(diff, (bd - 8) + rnd.2);
let m = (38 + diff / 16).clamp(0, 64);
self.mask[k] = if self.b.mask_type == 1 { 64 - m } else { m };
}
}
}
let (fwd, bck) = if ct == COMPOUND_DISTANCE { self.distance_weights(cand_refs) } else { (0, 0) };
let max = (1i32 << bd) - 1;
let is_inter_intra = self.b.is_inter && self.b.ref_frame[1] == INTRA_FRAME as i8;
@@ -476,64 +512,6 @@ impl TileDecoder<'_, '_> {
}
}
/// Warp selection for one reference: 0 none, 1 local warp, 2 global warp.
fn warp_mode(&self, ref_frame: i8, ref_idx: i32, w: usize, h: usize) -> u8 {
let fh = &self.fs.fh;
let ym = self.b.y_mode;
let global =
(ym == GLOBALMV || ym == GLOBAL_GLOBALMV) && ref_frame > INTRA_FRAME as i8 && fh.gm_type[ref_frame as usize] as usize > TRANSLATION;
let global_valid = global && setup_shear(&fh.gm_params[ref_frame as usize]).0;
if w < 8 || h < 8 || fh.force_integer_mv {
0
} else if self.b.motion_mode as usize == LOCALWARP && self.b.local_valid {
1
} else if global && !self.is_scaled_ref(ref_idx) && global_valid {
2
} else {
0
}
}
/// Builds the blend mask (wedge, inter-intra or difference-weighted) for the current compound type.
fn fill_blend_mask(&mut self, plane: usize, w: usize, h: usize, preds: &[Vec<i32>; 2], round_post: u32) {
let bd = self.fs.bit_depth;
let ct = self.b.compound_type;
if ct == COMPOUND_WEDGE && plane == 0 {
let m = &wedge_masks()[self.b.mi_size][self.b.wedge_index][self.b.wedge_sign];
for i in 0..h {
for j in 0..w {
self.mask[i * PRED_STRIDE + j] = m[i * w + j] as i32;
}
}
} else if ct == COMPOUND_INTRA {
let size_scale = MAX_SB_SIZE / h.max(w);
let im = self.b.interintra_mode;
for i in 0..h {
for j in 0..w {
self.mask[i * PRED_STRIDE + j] = if im == II_V_PRED {
II_WEIGHTS_1D[i * size_scale] as i32
} else if im == II_H_PRED {
II_WEIGHTS_1D[j * size_scale] as i32
} else if im == II_SMOOTH_PRED {
II_WEIGHTS_1D[i.min(j) * size_scale] as i32
} else {
32
};
}
}
} else if ct == COMPOUND_DIFFWTD && plane == 0 {
for i in 0..h {
for j in 0..w {
let k = i * PRED_STRIDE + j;
let diff = (preds[0][k] - preds[1][k]).abs();
let diff = round2(diff, (bd - 8) + round_post);
let m = (38 + diff / 16).clamp(0, 64);
self.mask[k] = if self.b.mask_type == 1 { 64 - m } else { m };
}
}
}
}
fn is_scaled_ref(&self, ref_idx: i32) -> bool {
if ref_idx < 0 {
return false;
@@ -700,7 +678,7 @@ fn hpass<const W: usize>(src: &[u16], hf: &[i16; 8], out: &mut [i32], half: i32,
let mut acc = [half; W];
for t in 0..8 {
let f = hf[t] as i32;
let Some(p) = src.get(t..).and_then(<[_]>::first_chunk::<W>) else {
let Some(p) = src.get(t..).and_then(|s| s.first_chunk::<W>()) else {
return;
};
for j in 0..W {
@@ -721,7 +699,7 @@ fn vpass<const W: usize>(rows: &[i32], vf: &[i16; 8], out: &mut [i32], half: i32
let mut acc = [half; W];
for t in 0..8 {
let f = vf[t] as i32;
let Some(p) = rows.get(t * W..).and_then(<[_]>::first_chunk::<W>) else {
let Some(p) = rows.get(t * W..).and_then(|s| s.first_chunk::<W>()) else {
return;
};
for j in 0..W {
+1 -8
View File
@@ -3,14 +3,7 @@
use crate::Result;
use crate::header::{EIGHTTAP, SWITCHABLE};
use crate::mvpred::MvP;
use crate::spec_tables::{
ALTREF_FRAME, ALTREF2_FRAME, BLOCK_8X8, BLOCK_32X32, BLOCK_64X64, BLOCK_128X128, BWDREF_FRAME, CLASS0_SIZE, COMP_NEWMV_CTXS, COMPOUND_AVERAGE,
COMPOUND_DIFFWTD, COMPOUND_DISTANCE, COMPOUND_INTRA, COMPOUND_MODE_CTX_MAP, COMPOUND_REFERENCE, COMPOUND_WEDGE, GLOBAL_GLOBALMV, GLOBALMV,
GOLDEN_FRAME, INTRA_FRAME, INTRABC_DELAY_PIXELS, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, LOCALWARP, MV_CLASS_0, MV_INTRABC_CONTEXT,
MV_JOINT_HNZVNZ, MV_JOINT_HNZVZ, MV_JOINT_HZVNZ, NEAR_NEARMV, NEAR_NEWMV, NEAREST_NEARESTMV, NEAREST_NEWMV, NEARESTMV, NEARMV, NEW_NEARESTMV,
NEW_NEARMV, NEW_NEWMV, NEWMV, NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, OBMC, REF_SCALE_SHIFT, SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP,
SIMPLE, SINGLE_REFERENCE, SIZE_GROUP, TRANSLATION, UNIDIR_COMP_REFERENCE, UV_CFL_PRED, WEDGE_BITS,
};
use crate::spec_tables::*;
use crate::tile::TileDecoder;
fn block_width(bs: usize) -> usize {
+1 -5
View File
@@ -1,11 +1,7 @@
//! Intra prediction (spec 7.11.2), palette prediction (7.11.4) and chroma from luma (7.11.5).
use crate::frame::Plane;
use crate::spec_tables::{
ANGLE_STEP, D67_PRED, DC_PRED, DR_INTRA_DERIVATIVE, INTRA_EDGE_KERNEL, INTRA_EDGE_TAPS, INTRA_FILTER_SCALE_BITS, INTRA_FILTER_TAPS,
MODE_TO_ANGLE, SM_WEIGHTS_TX_4X4, SM_WEIGHTS_TX_8X8, SM_WEIGHTS_TX_16X16, SM_WEIGHTS_TX_32X32, SM_WEIGHTS_TX_64X64, SMOOTH_H_PRED, SMOOTH_PRED,
SMOOTH_V_PRED, V_PRED,
};
use crate::spec_tables::*;
use crate::transform::round2;
/// Inputs of the intra prediction process that come from the block.
+1 -4
View File
@@ -1,10 +1,7 @@
//! Motion vector prediction processes (spec 7.10): find_mv_stack, has_overlappable_candidates
//! and find_warp_samples.
use crate::spec_tables::{
GLOBAL_GLOBALMV, GLOBALMV, IDENTITY, INTRA_FRAME, LEAST_SQUARES_SAMPLES_MAX, MAX_REF_MV_STACK_SIZE, MV_BORDER, NEAR_NEWMV, NEAREST_NEWMV,
NEW_NEARESTMV, NEW_NEARMV, NEW_NEWMV, NEWMV, NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, REF_CAT_LEVEL, TRANSLATION, WARPEDMODEL_PREC_BITS,
};
use crate::spec_tables::*;
use crate::tile::TileDecoder;
pub(crate) type MvP = [i32; 2];
+1 -4
View File
@@ -1,10 +1,7 @@
//! In-loop post filters run by decode_frame_wrapup: loop filter (7.14), CDEF (7.15),
//! super-resolution upscaling (7.16) and loop restoration (7.17).
use crate::spec_tables::{
GLOBAL_GLOBALMV, GLOBALMV, INTRA_FRAME, MAX_LOOP_FILTER, NEARESTMV, NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, SEG_LVL_ALT_LF_Y_V, TX_HEIGHT,
TX_WIDTH,
};
use crate::spec_tables::*;
use crate::state::FrameState;
use crate::stats::{DecodeStats, Stage, Timer};
+79 -118
View File
@@ -1,11 +1,7 @@
//! Super-resolution upscaling (7.16) and loop restoration (7.17).
use crate::frame::{FrameBuf, Plane};
use crate::spec_tables::{
FILTER_BITS, RESTORE_NONE, RESTORE_SGRPROJ, RESTORE_WIENER, SGR_PARAMS, SGRPROJ_MTABLE_BITS, SGRPROJ_PRJ_BITS, SGRPROJ_RECIP_BITS,
SGRPROJ_RST_BITS, SGRPROJ_SGR_BITS, SUPERRES_EXTRA_BITS, SUPERRES_FILTER_OFFSET, SUPERRES_FILTER_TAPS, SUPERRES_SCALE_BITS, SUPERRES_SCALE_MASK,
UPSCALE_FILTER,
};
use crate::spec_tables::*;
use crate::state::FrameState;
/// Upscale a frame horizontally from FrameWidth to UpscaledWidth (7.16).
@@ -73,70 +69,57 @@ impl LrCtx<'_> {
}
}
/// Position and size of a (at most 4x4) restoration block within its plane.
#[derive(Clone, Copy)]
struct LrBlock {
x: i32,
y: i32,
w: i32,
h: i32,
}
/// Loop restoration (7.17): returns LrFrame given UpscaledCurrFrame and UpscaledCdefFrame.
pub(crate) fn loop_restoration(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf) -> FrameBuf {
let fh = &fs.fh;
let mut lr = cdef.clone();
let up_w = fh.upscaled_width as i32;
let fr_h = fh.frame_height as i32;
let bd = fs.bit_depth;
for plane in 0..fs.num_planes {
if fs.fh.lr.frame_restoration_type[plane] == RESTORE_NONE as u8 {
let rtype_frame = fh.lr.frame_restoration_type[plane];
if rtype_frame == RESTORE_NONE as u8 {
continue;
}
restore_plane(fs, cur, cdef, &mut lr.planes[plane], plane);
let (sub_x, sub_y) = if plane > 0 { (fs.ssx as i32, fs.ssy as i32) } else { (0, 0) };
let unit_size = fh.lr.loop_restoration_size[plane] as i32;
let unit_rows = fs.lr_unit_rows[plane] as i32;
let unit_cols = fs.lr_unit_cols[plane] as i32;
let plane_end_x = ((up_w + sub_x) >> sub_x) - 1;
let plane_end_y = ((fr_h + sub_y) >> sub_y) - 1;
let mut row = 0;
while row * 4 < fr_h {
let luma_y = row * 4;
let stripe_num = (luma_y + 8) / 64;
let stripe_start_y = (-8 + stripe_num * 64) >> sub_y;
let stripe_end_y = stripe_start_y + (64 >> sub_y) - 1;
let ctx = LrCtx { cur: &cur.planes[plane], cdef: &cdef.planes[plane], plane_end_x, plane_end_y, stripe_start_y, stripe_end_y };
let unit_row = (unit_rows - 1).min(((row * 4 + 8) >> sub_y) / unit_size);
let mut col = 0;
while col * 4 < up_w {
let unit_col = (unit_cols - 1).min(((col * 4) >> sub_x) / unit_size);
let x = (col * 4) >> sub_x;
let y = (row * 4) >> sub_y;
let w = (4 >> sub_x).min(plane_end_x - x + 1);
let h = (4 >> sub_y).min(plane_end_y - y + 1);
if w > 0 && h > 0 {
let ui = (unit_row * unit_cols + unit_col) as usize;
match fs.lr.lr_type[plane][ui] {
t if t == RESTORE_WIENER as u8 => wiener(fs, &ctx, &mut lr.planes[plane], plane, ui, x, y, w, h, bd),
t if t == RESTORE_SGRPROJ as u8 => self_guided(fs, &ctx, &mut lr.planes[plane], plane, ui, x, y, w, h, bd),
_ => {}
}
}
col += 1;
}
row += 1;
}
}
lr
}
fn restore_plane(fs: &FrameState, cur: &FrameBuf, cdef: &FrameBuf, out: &mut Plane, plane: usize) {
let fh = &fs.fh;
let up_w = fh.upscaled_width as i32;
let fr_h = fh.frame_height as i32;
let bd = fs.bit_depth;
let (sub_x, sub_y) = if plane > 0 { (fs.ssx as i32, fs.ssy as i32) } else { (0, 0) };
let unit_size = fh.lr.loop_restoration_size[plane] as i32;
let unit_rows = fs.lr_unit_rows[plane] as i32;
let unit_cols = fs.lr_unit_cols[plane] as i32;
let plane_end_x = ((up_w + sub_x) >> sub_x) - 1;
let plane_end_y = ((fr_h + sub_y) >> sub_y) - 1;
let mut row = 0;
while row * 4 < fr_h {
let luma_y = row * 4;
let stripe_num = (luma_y + 8) / 64;
let stripe_start_y = (-8 + stripe_num * 64) >> sub_y;
let stripe_end_y = stripe_start_y + (64 >> sub_y) - 1;
let ctx = LrCtx { cur: &cur.planes[plane], cdef: &cdef.planes[plane], plane_end_x, plane_end_y, stripe_start_y, stripe_end_y };
let unit_row = (unit_rows - 1).min(((row * 4 + 8) >> sub_y) / unit_size);
let mut col = 0;
while col * 4 < up_w {
let unit_col = (unit_cols - 1).min(((col * 4) >> sub_x) / unit_size);
let x = (col * 4) >> sub_x;
let y = (row * 4) >> sub_y;
let w = (4 >> sub_x).min(plane_end_x - x + 1);
let h = (4 >> sub_y).min(plane_end_y - y + 1);
if w > 0 && h > 0 {
let ui = (unit_row * unit_cols + unit_col) as usize;
let blk = LrBlock { x, y, w, h };
match fs.lr.lr_type[plane][ui] {
t if t == RESTORE_WIENER as u8 => wiener(fs, &ctx, out, (plane, ui), blk, bd),
t if t == RESTORE_SGRPROJ as u8 => self_guided(fs, &ctx, out, (plane, ui), blk, bd),
_ => {}
}
}
col += 1;
}
row += 1;
}
}
fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, (plane, ui): (usize, usize), blk: LrBlock, bd: u32) {
let LrBlock { x, y, w, h } = blk;
#[allow(clippy::too_many_arguments)]
fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {
let round0: u32 = if bd == 12 { 5 } else { 3 };
let round1: u32 = if bd == 12 { 9 } else { 11 };
let coef = &fs.lr.lr_wiener[plane][ui];
@@ -179,13 +162,13 @@ fn wiener(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, (plane, ui): (usize, us
}
}
fn self_guided(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, (plane, ui): (usize, usize), blk: LrBlock, bd: u32) {
let LrBlock { x, y, w, h } = blk;
#[allow(clippy::too_many_arguments)]
fn self_guided(fs: &FrameState, ctx: &LrCtx, out: &mut Plane, plane: usize, ui: usize, x: i32, y: i32, w: i32, h: i32, bd: u32) {
let set = fs.lr.lr_sgr_set[plane][ui] as usize;
let mut flt0 = [[0i32; 4]; 4];
let mut flt1 = [[0i32; 4]; 4];
box_filter(ctx, blk, (set, 0), bd, &mut flt0);
box_filter(ctx, blk, (set, 1), bd, &mut flt1);
box_filter(ctx, x, y, w, h, set, 0, bd, &mut flt0);
box_filter(ctx, x, y, w, h, set, 1, bd, &mut flt1);
let xqd = fs.lr.lr_sgr_xqd[plane][ui];
let w0 = xqd[0] as i32;
let w1 = xqd[1] as i32;
@@ -211,56 +194,8 @@ fn round2_64(x: i64, n: u32) -> i64 {
if n == 0 { x } else { (x + (1i64 << (n - 1))) >> n }
}
/// Box sums of the samples within `r` of (x, y): (sum of squares, sum).
fn box_sums(ctx: &LrCtx, x: i32, y: i32, r: i32) -> (i64, i64) {
let mut a = 0i64;
let mut b = 0i64;
for dy in -r..=r {
for dx in -r..=r {
let c = ctx.sample(x + dx, y + dy) as i64;
a += c * c;
b += c;
}
}
(a, b)
}
/// Self-guided filter constants of one pass.
struct SgrConsts {
n: i64,
s: i64,
one_over_n: i64,
}
/// (A, B) coefficients of one sample from its box sums.
fn sgr_coefficients(a: i64, b: i64, k: &SgrConsts, bd: u32) -> (i64, i64) {
let a = round2_64(a, 2 * (bd - 8));
let d = round2_64(b, bd - 8);
let p = (a * k.n - d * d).max(0);
let z = round2_64(p * k.s, SGRPROJ_MTABLE_BITS as u32);
let a2 = if z >= 255 {
256
} else if z == 0 {
1
} else {
((z << SGRPROJ_SGR_BITS) + z / 2) / (z + 1)
};
let b2 = ((1i64 << SGRPROJ_SGR_BITS) - a2) * b * k.one_over_n;
(a2, round2_64(b2, SGRPROJ_RECIP_BITS as u32))
}
fn box_weight(pass: usize, i: i32, dx: i32, dy: i32) -> i64 {
if pass == 0 {
if ((i + dy) & 1) != 0 { if dx == 0 { 6 } else { 5 } } else { 0 }
} else if dx == 0 || dy == 0 {
4
} else {
3
}
}
fn box_filter(ctx: &LrCtx, blk: LrBlock, (set, pass): (usize, usize), bd: u32, f: &mut [[i32; 4]; 4]) {
let LrBlock { x, y, w, h } = blk;
#[allow(clippy::too_many_arguments)]
fn box_filter(ctx: &LrCtx, x: i32, y: i32, w: i32, h: i32, set: usize, pass: usize, bd: u32, f: &mut [[i32; 4]; 4]) {
let r = SGR_PARAMS[set][pass * 2] as i32;
if r == 0 {
return;
@@ -268,15 +203,35 @@ fn box_filter(ctx: &LrCtx, blk: LrBlock, (set, pass): (usize, usize), bd: u32, f
let eps = SGR_PARAMS[set][pass * 2 + 1] as i64;
let n = ((2 * r + 1) * (2 * r + 1)) as i64;
let n2e = n * n * eps;
let k = SgrConsts { n, s: ((1i64 << SGRPROJ_MTABLE_BITS) + n2e / 2) / n2e, one_over_n: ((1i64 << SGRPROJ_RECIP_BITS) + n / 2) / n };
let s = ((1i64 << SGRPROJ_MTABLE_BITS) + n2e / 2) / n2e;
let one_over_n = ((1i64 << SGRPROJ_RECIP_BITS) + n / 2) / n;
let mut a_arr = [[0i64; 6]; 6];
let mut b_arr = [[0i64; 6]; 6];
for i in -1..h + 1 {
for j in -1..w + 1 {
let (a, b) = box_sums(ctx, x + j, y + i, r);
let (a2, b2) = sgr_coefficients(a, b, &k, bd);
let mut a = 0i64;
let mut b = 0i64;
for dy in -r..=r {
for dx in -r..=r {
let c = ctx.sample(x + j + dx, y + i + dy) as i64;
a += c * c;
b += c;
}
}
let a = round2_64(a, 2 * (bd - 8));
let d = round2_64(b, bd - 8);
let p = (a * n - d * d).max(0);
let z = round2_64(p * s, SGRPROJ_MTABLE_BITS as u32);
let a2 = if z >= 255 {
256
} else if z == 0 {
1
} else {
((z << SGRPROJ_SGR_BITS) + z / 2) / (z + 1)
};
let b2 = ((1i64 << SGRPROJ_SGR_BITS) - a2) * b * one_over_n;
a_arr[(i + 1) as usize][(j + 1) as usize] = a2;
b_arr[(i + 1) as usize][(j + 1) as usize] = b2;
b_arr[(i + 1) as usize][(j + 1) as usize] = round2_64(b2, SGRPROJ_RECIP_BITS as u32);
}
}
for i in 0..h {
@@ -286,7 +241,13 @@ fn box_filter(ctx: &LrCtx, blk: LrBlock, (set, pass): (usize, usize), bd: u32, f
let mut b = 0i64;
for dy in -1..=1i32 {
for dx in -1..=1i32 {
let weight = box_weight(pass, i, dx, dy);
let weight = if pass == 0 {
if ((i + dy) & 1) != 0 { if dx == 0 { 6 } else { 5 } } else { 0 }
} else if dx == 0 || dy == 0 {
4
} else {
3
};
a += weight * a_arr[(i + dy + 1) as usize][(j + dx + 1) as usize];
b += weight * b_arr[(i + dy + 1) as usize][(j + dx + 1) as usize];
}
+1 -1
View File
@@ -9,7 +9,7 @@
use crate::decoder::RefFrame;
use crate::frame::{FrameBuf, MiInfo};
use crate::header::{FrameHeader, RefInfo, SequenceHeader};
use crate::spec_tables::{DEFAULT_INTRA_FRAME_Y_MODE_CDF, NUM_REF_FRAMES, RESTORE_NONE, SUBSAMPLED_SIZE};
use crate::spec_tables::*;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
+69 -106
View File
@@ -6,27 +6,7 @@ use crate::cdf::Cdfs;
use crate::frame::{MiInfo, Mv};
use crate::header::{FrameHeader, NONE, SequenceHeader};
use crate::intra::{IntraParams, is_directional_mode, predict_intra, round2_signed};
use crate::spec_tables::{
AC_QLOOKUP, ADJUSTED_TX_SIZE, ADST_FLIPADST, BLOCK_4X4, BLOCK_8X8, BLOCK_64X64, BLOCK_128X128, BR_CDF_SIZE, CFL_SIGN_NEG, CFL_SIGN_ZERO,
COEFF_BASE_CTX_OFFSET, COEFF_BASE_POS_CTX_OFFSET, COEFF_BASE_RANGE, COMPOUND_AVERAGE, DC_PRED, DC_QLOOKUP, DCT_DCT, DCT_FLIPADST,
DEFAULT_SCAN_4X4, DEFAULT_SCAN_4X8, DEFAULT_SCAN_4X16, DEFAULT_SCAN_8X4, DEFAULT_SCAN_8X8, DEFAULT_SCAN_8X16, DEFAULT_SCAN_8X32,
DEFAULT_SCAN_16X4, DEFAULT_SCAN_16X8, DEFAULT_SCAN_16X16, DEFAULT_SCAN_16X32, DEFAULT_SCAN_32X8, DEFAULT_SCAN_32X16, DEFAULT_SCAN_32X32,
DELTA_LF_SMALL, DELTA_Q_SMALL, FILTER_INTRA_MODE_TO_INTRA_DIR, FLIPADST_ADST, FLIPADST_DCT, FLIPADST_FLIPADST, FRAME_LF_COUNT, H_ADST, H_DCT,
H_FLIPADST, H_PRED, IDTX, II_DC_PRED, II_H_PRED, II_V_PRED, INTRA_FRAME, INTRA_MODE_CONTEXT, MAG_REF_OFFSET_WITH_TX_CLASS, MAX_ANGLE_DELTA,
MAX_LOOP_FILTER, MAX_TX_DEPTH_TABLE, MAX_TX_SIZE_RECT, MAX_VARTX_DEPTH, MCOL_SCAN_4X4, MCOL_SCAN_4X8, MCOL_SCAN_4X16, MCOL_SCAN_8X4,
MCOL_SCAN_8X8, MCOL_SCAN_8X16, MCOL_SCAN_16X4, MCOL_SCAN_16X8, MCOL_SCAN_16X16, MI_HEIGHT_LOG2, MI_WIDTH_LOG2, MODE_TO_TXFM, MROW_SCAN_4X4,
MROW_SCAN_4X8, MROW_SCAN_4X16, MROW_SCAN_8X4, MROW_SCAN_8X8, MROW_SCAN_8X16, MROW_SCAN_16X4, MROW_SCAN_16X8, MROW_SCAN_16X16,
NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, NUM_BASE_LEVELS, PALETTE_COLOR_CONTEXT, PALETTE_COLOR_HASH_MULTIPLIERS, PALETTE_COLORS,
PALETTE_NUM_NEIGHBORS, PARTITION_HORZ, PARTITION_HORZ_4, PARTITION_HORZ_A, PARTITION_HORZ_B, PARTITION_NONE, PARTITION_SPLIT, PARTITION_SUBSIZE,
PARTITION_VERT, PARTITION_VERT_4, PARTITION_VERT_A, PARTITION_VERT_B, QM_OFFSET, QUANTIZER_MATRIX, RESTORE_NONE, RESTORE_SGRPROJ, RESTORE_WIENER,
SEG_LVL_SKIP, SGR_PARAMS, SGRPROJ_PARAMS_BITS, SGRPROJ_PRJ_BITS, SGRPROJ_PRJ_SUBEXP_K, SIG_REF_DIFF_OFFSET, SIG_REF_DIFF_OFFSET_NUM, SIMPLE,
SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, SPLIT_TX_SIZE, SUPERRES_NUM, TX_4X4, TX_4X8, TX_4X16, TX_8X4, TX_8X8, TX_8X16, TX_8X32, TX_16X4,
TX_16X8, TX_16X16, TX_16X32, TX_16X64, TX_32X8, TX_32X16, TX_32X32, TX_32X64, TX_64X16, TX_64X32, TX_64X64, TX_CLASS_2D, TX_CLASS_HORIZ,
TX_CLASS_VERT, TX_HEIGHT, TX_HEIGHT_LOG2, TX_MODE_SELECT, TX_SET_DCTONLY, TX_SET_INTER_1, TX_SET_INTER_2, TX_SET_INTER_3, TX_SET_INTRA_1,
TX_SET_INTRA_2, TX_SIZE_SQR, TX_SIZE_SQR_UP, TX_SIZES, TX_SIZES_ALL, TX_TYPE_IN_SET_INTER, TX_TYPE_IN_SET_INTRA, TX_TYPE_INTER_INV_SET1,
TX_TYPE_INTER_INV_SET2, TX_TYPE_INTER_INV_SET3, TX_TYPE_INTRA_INV_SET1, TX_TYPE_INTRA_INV_SET2, TX_WIDTH, TX_WIDTH_LOG2, UV_CFL_PRED, V_ADST,
V_DCT, V_FLIPADST, V_PRED,
};
use crate::spec_tables::*;
use crate::state::{FrameShared, TileState};
use crate::symbol::SymbolDecoder;
use crate::transform::inverse_transform_2d;
@@ -1682,87 +1662,6 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
}
/// eob_pt, eob_extra and the remaining eob bits.
fn read_eob(&mut self, tx_sz: usize, tx_sz_ctx: usize, ptype: usize, tx_class: usize) -> usize {
let eob_multisize = (TX_WIDTH_LOG2[tx_sz] as usize).min(5) + (TX_HEIGHT_LOG2[tx_sz] as usize).min(5) - 4;
let ectx = (tx_class != TX_CLASS_2D) as usize;
let eob_pt = 1 + match eob_multisize {
0 => self.sd.read_symbol(&mut self.cdf.eob_pt_16[ptype][ectx]),
1 => self.sd.read_symbol(&mut self.cdf.eob_pt_32[ptype][ectx]),
2 => self.sd.read_symbol(&mut self.cdf.eob_pt_64[ptype][ectx]),
3 => self.sd.read_symbol(&mut self.cdf.eob_pt_128[ptype][ectx]),
4 => self.sd.read_symbol(&mut self.cdf.eob_pt_256[ptype][ectx]),
5 => self.sd.read_symbol(&mut self.cdf.eob_pt_512[ptype]),
_ => self.sd.read_symbol(&mut self.cdf.eob_pt_1024[ptype]),
};
let mut eob = if eob_pt < 2 { eob_pt } else { (1 << (eob_pt - 2)) + 1 };
let eob_shift = eob_pt as i32 - 3;
if eob_shift >= 0 {
let extra = self.sd.read_symbol(&mut self.cdf.eob_extra[tx_sz_ctx][ptype][eob_pt - 3]);
if extra == 1 {
eob += 1 << eob_shift;
}
for i in 1..(eob_pt as i32 - 2).max(0) {
let sh = (eob_pt as i32 - 2).max(0) - 1 - i;
if self.sd.read_literal(1) == 1 {
eob += 1 << sh;
}
}
}
eob
}
/// Exp-Golomb coded remainder of a coefficient above the base range (read_golomb).
fn read_golomb(&mut self) -> u32 {
let mut length = 0;
loop {
length += 1;
if self.sd.read_literal(1) == 1 || length > 32 {
break;
}
}
let mut x: u32 = 1;
for _ in (0..length - 1).rev() {
x = (x << 1) | self.sd.read_literal(1);
}
x
}
/// Reads the signs and Golomb remainders of the first `scan.len()` (= eob) coefficients, applies
/// them to `self.quant`, and returns the culLevel and dcCategory contexts. `blk4` is (x4, y4, w4, h4).
fn read_signs_and_golomb(&mut self, plane: usize, blk4: (usize, usize, usize, usize), scan: &[u16]) -> (u32, u8) {
let (x4, y4, w4, h4) = blk4;
let ptype = (plane > 0) as usize;
let mut cul_level = 0u32;
let mut dc_category = 0u8;
for (c, &p) in scan.iter().enumerate() {
let pos = p as usize;
let sign = if self.quant[pos] != 0 {
if c == 0 {
let ctx = self.dc_sign_ctx(plane, x4, y4, w4, h4);
self.sd.read_symbol(&mut self.cdf.dc_sign[ptype][ctx]) == 1
} else {
self.sd.read_literal(1) == 1
}
} else {
false
};
if self.quant[pos] > (NUM_BASE_LEVELS + COEFF_BASE_RANGE) as i32 {
let x = self.read_golomb();
self.quant[pos] = (x as i64 + COEFF_BASE_RANGE as i64 + NUM_BASE_LEVELS as i64).min(i32::MAX as i64) as i32;
}
if pos == 0 && self.quant[pos] > 0 {
dc_category = if sign { 1 } else { 2 };
}
self.quant[pos] &= 0xFFFFF;
cul_level += self.quant[pos] as u32;
if sign {
self.quant[pos] = -self.quant[pos];
}
}
(cul_level.min(63), dc_category)
}
/// coeffs( ): returns eob.
fn coeffs(&mut self, plane: usize, start_x: usize, start_y: usize, tx_sz: usize) -> usize {
let x4 = start_x >> 2;
@@ -1788,8 +1687,32 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
}
self.plane_tx_type = self.compute_tx_type(plane, tx_sz, x4, y4);
let scan = self.get_scan(tx_sz);
let eob_multisize = (TX_WIDTH_LOG2[tx_sz] as usize).min(5) + (TX_HEIGHT_LOG2[tx_sz] as usize).min(5) - 4;
let tx_class = get_tx_class(self.plane_tx_type);
eob = self.read_eob(tx_sz, tx_sz_ctx, ptype, tx_class);
let ectx = (tx_class != TX_CLASS_2D) as usize;
let eob_pt = 1 + match eob_multisize {
0 => self.sd.read_symbol(&mut self.cdf.eob_pt_16[ptype][ectx]),
1 => self.sd.read_symbol(&mut self.cdf.eob_pt_32[ptype][ectx]),
2 => self.sd.read_symbol(&mut self.cdf.eob_pt_64[ptype][ectx]),
3 => self.sd.read_symbol(&mut self.cdf.eob_pt_128[ptype][ectx]),
4 => self.sd.read_symbol(&mut self.cdf.eob_pt_256[ptype][ectx]),
5 => self.sd.read_symbol(&mut self.cdf.eob_pt_512[ptype]),
_ => self.sd.read_symbol(&mut self.cdf.eob_pt_1024[ptype]),
};
eob = if eob_pt < 2 { eob_pt } else { (1 << (eob_pt - 2)) + 1 };
let eob_shift = eob_pt as i32 - 3;
if eob_shift >= 0 {
let extra = self.sd.read_symbol(&mut self.cdf.eob_extra[tx_sz_ctx][ptype][eob_pt - 3]);
if extra == 1 {
eob += 1 << eob_shift;
}
for i in 1..(eob_pt as i32 - 2).max(0) {
let sh = (eob_pt as i32 - 2).max(0) - 1 - i;
if self.sd.read_literal(1) == 1 {
eob += 1 << sh;
}
}
}
let adj = ADJUSTED_TX_SIZE[tx_sz] as usize;
let bwl = TX_WIDTH_LOG2[adj] as usize;
let height = TX_HEIGHT[adj] as usize;
@@ -1837,7 +1760,45 @@ impl<'a, 'f> TileDecoder<'a, 'f> {
lev[li] = level as u8;
}
self.levels = lev;
(cul_level, dc_category) = self.read_signs_and_golomb(plane, (x4, y4, w4, h4), &scan[..eob]);
for c in 0..eob {
let pos = scan[c] as usize;
let sign = if self.quant[pos] != 0 {
if c == 0 {
let ctx = self.dc_sign_ctx(plane, x4, y4, w4, h4);
self.sd.read_symbol(&mut self.cdf.dc_sign[ptype][ctx]) == 1
} else {
self.sd.read_literal(1) == 1
}
} else {
false
};
if self.quant[pos] > (NUM_BASE_LEVELS + COEFF_BASE_RANGE) as i32 {
let mut length = 0;
loop {
length += 1;
if self.sd.read_literal(1) == 1 {
break;
}
if length > 32 {
break;
}
}
let mut x: u32 = 1;
for _ in (0..length - 1).rev() {
x = (x << 1) | self.sd.read_literal(1);
}
self.quant[pos] = (x as i64 + COEFF_BASE_RANGE as i64 + NUM_BASE_LEVELS as i64).min(i32::MAX as i64) as i32;
}
if pos == 0 && self.quant[pos] > 0 {
dc_category = if sign { 1 } else { 2 };
}
self.quant[pos] &= 0xFFFFF;
cul_level += self.quant[pos] as u32;
if sign {
self.quant[pos] = -self.quant[pos];
}
}
cul_level = cul_level.min(63);
}
for i in 0..w4 {
if x4 + i < self.t.above_level[plane].len() {
@@ -2261,16 +2222,18 @@ fn neg_deinterleave(diff: i32, r: i32, max: i32) -> i32 {
if diff <= 2 * r {
if diff & 1 == 1 {
return r + ((diff + 1) >> 1);
} else {
return r - (diff >> 1);
}
return r - (diff >> 1);
}
diff
} else {
if diff <= 2 * (max - r - 1) {
if diff & 1 == 1 {
return r + ((diff + 1) >> 1);
} else {
return r - (diff >> 1);
}
return r - (diff >> 1);
}
max - (diff + 1)
}
+5 -52
View File
@@ -1,9 +1,6 @@
//! Inverse transforms (spec 7.13), implemented step by step as specified.
use crate::spec_tables::{
ADST_ADST, ADST_DCT, ADST_FLIPADST, COS128_LOOKUP, DCT_ADST, DCT_DCT, DCT_FLIPADST, FLIPADST_ADST, FLIPADST_DCT, FLIPADST_FLIPADST, H_ADST,
H_DCT, H_FLIPADST, TRANSFORM_ROW_SHIFT, TX_HEIGHT_LOG2, TX_WIDTH_LOG2, V_ADST, V_DCT, V_FLIPADST,
};
use crate::spec_tables::*;
#[inline(always)]
fn round2_64(x: i64, n: u32) -> i32 {
@@ -104,7 +101,7 @@ impl<const L: usize> Lane for [i32; L] {
}
#[inline(always)]
fn neg(self) -> Self {
self.map(i32::wrapping_neg)
self.map(|v| v.wrapping_neg())
}
#[inline(always)]
fn mul_round12(self, m: i32) -> Self {
@@ -165,15 +162,6 @@ pub(crate) fn inverse_dct<T: Lane>(t: &mut [T], n: u32, r: u32) {
for i in 0..len {
t[i] = copy[brev(n, i)];
}
inverse_dct_stage1(t, n, r);
inverse_dct_stage2(t, n, r);
inverse_dct_stage3(t, n, r);
inverse_dct_stage4(t, n, r);
inverse_dct_stage5(t, n, r);
inverse_dct_stage6(t, n, r);
}
fn inverse_dct_stage1<T: Lane>(t: &mut [T], n: u32, r: u32) {
if n == 6 {
for i in 0..16 {
bf(t, 32 + i, 63 - i, 63 - 4 * brev(4, i) as i32, false);
@@ -199,9 +187,6 @@ fn inverse_dct_stage1<T: Lane>(t: &mut [T], n: u32, r: u32) {
hd(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r);
}
}
}
fn inverse_dct_stage2<T: Lane>(t: &mut [T], n: u32, r: u32) {
if n == 6 {
for i in 0..4 {
for j in 0..2 {
@@ -233,9 +218,6 @@ fn inverse_dct_stage2<T: Lane>(t: &mut [T], n: u32, r: u32) {
}
}
}
}
fn inverse_dct_stage3<T: Lane>(t: &mut [T], n: u32, r: u32) {
for i in 0..2 {
bf(t, 2 * i, 2 * i + 1, 32 + 16 * i as i32, i == 0);
}
@@ -263,9 +245,6 @@ fn inverse_dct_stage3<T: Lane>(t: &mut [T], n: u32, r: u32) {
}
}
}
}
fn inverse_dct_stage4<T: Lane>(t: &mut [T], n: u32, r: u32) {
for i in 0..2 {
hd(t, i, 3 - i, false, r);
}
@@ -291,9 +270,6 @@ fn inverse_dct_stage4<T: Lane>(t: &mut [T], n: u32, r: u32) {
}
}
}
}
fn inverse_dct_stage5<T: Lane>(t: &mut [T], n: u32, r: u32) {
if n >= 3 {
for i in 0..4 {
hd(t, i, 7 - i, false, r);
@@ -321,9 +297,6 @@ fn inverse_dct_stage5<T: Lane>(t: &mut [T], n: u32, r: u32) {
hd(t, i, 15 - i, false, r);
}
}
}
fn inverse_dct_stage6<T: Lane>(t: &mut [T], n: u32, r: u32) {
if n >= 5 {
for i in 0..4 {
bf(t, 27 - i, 20 + i, 32, true);
@@ -555,9 +528,10 @@ pub(crate) fn inverse_transform_2d(dequant: &[i32], residual: &mut [i32], tx_sz:
let col_clamp = (bit_depth + 6).max(16);
let rk = row_kind(tx_type);
let ck = col_kind(tx_type);
let mut t = [0i32; 64];
let rect2 = log2w.abs_diff(log2h) == 1;
let p = Tx2d { w, h, log2w, log2h, row_shift, col_shift, row_clamp, col_clamp, rk, ck, rect2 };
if !lossless && bit_depth <= 10 {
let p = Tx2d { w, h, log2w, log2h, row_shift, col_shift, row_clamp, col_clamp, rk, ck, rect2 };
if w >= 8 && h >= 8 {
transform_lanes::<8>(dequant, residual, &p);
} else {
@@ -565,13 +539,6 @@ pub(crate) fn inverse_transform_2d(dequant: &[i32], residual: &mut [i32], tx_sz:
}
return;
}
scalar_row_pass(dequant, residual, &p, lossless);
scalar_col_pass(residual, &p, lossless);
}
fn scalar_row_pass(dequant: &[i32], residual: &mut [i32], p: &Tx2d, lossless: bool) {
let (w, h, log2w, row_shift, row_clamp, col_clamp, rk, rect2) = (p.w, p.h, p.log2w, p.row_shift, p.row_clamp, p.col_clamp, p.rk, p.rect2);
let mut t = [0i32; 64];
let in_w = w.min(32);
for i in 0..h {
// Every 1D transform maps an all-zero row to zeros (each step is linear with
@@ -602,11 +569,6 @@ fn scalar_row_pass(dequant: &[i32], residual: &mut [i32], p: &Tx2d, lossless: bo
residual[i * w + j] = round2(t[j], row_shift).clamp(lo, hi);
}
}
}
fn scalar_col_pass(residual: &mut [i32], p: &Tx2d, lossless: bool) {
let (w, h, log2h, col_shift, col_clamp, ck) = (p.w, p.h, p.log2h, p.col_shift, p.col_clamp, p.ck);
let mut t = [0i32; 64];
for j in 0..w {
for i in 0..h {
t[i] = residual[i * w + j];
@@ -652,16 +614,11 @@ fn transform_1d<T: Lane>(t: &mut [T], kind: Kind1d, n: u32, r: u32) {
/// The 2D inverse transform with `L` rows (row pass) or columns (column pass) at a time;
/// bit-identical to the one-at-a-time process for bit depths up to 10.
fn transform_lanes<const L: usize>(dequant: &[i32], residual: &mut [i32], p: &Tx2d) {
let mut t = [[0i32; L]; 64];
lanes_row_pass(dequant, residual, p, &mut t);
lanes_col_pass(residual, p, &mut t);
}
fn lanes_row_pass<const L: usize>(dequant: &[i32], residual: &mut [i32], p: &Tx2d, t: &mut [[i32; L]; 64]) {
let (w, h) = (p.w, p.h);
let in_w = w.min(32);
let lo = -(1i32 << (p.col_clamp - 1));
let hi = (1i32 << (p.col_clamp - 1)) - 1;
let mut t = [[0i32; L]; 64];
let mut i0 = 0;
while i0 < h {
// Rows without coefficients (and rows 32..63) transform to zeros.
@@ -689,10 +646,6 @@ fn lanes_row_pass<const L: usize>(dequant: &[i32], residual: &mut [i32], p: &Tx2
}
i0 += L;
}
}
fn lanes_col_pass<const L: usize>(residual: &mut [i32], p: &Tx2d, t: &mut [[i32; L]; 64]) {
let (w, h) = (p.w, p.h);
let mut j0 = 0;
while j0 < w {
for i in 0..h {
+3 -1
View File
@@ -9,4 +9,6 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-media = { workspace = true, features = ["bitstream"] }
[dev-dependencies]
proptest = { workspace = true }
-82
View File
@@ -1,82 +0,0 @@
//! Memory budget for decoded pictures, shared by the video decoders.
//!
//! A per-axis size cap does not bound memory: a decoder holds the current picture, every
//! reference picture and the pictures still being decoded on worker threads. Each decoder checks
//! the whole picture store against [`DECODE_MEMORY_BUDGET`] with checked arithmetic before it
//! allocates for a new picture size, so a hostile header is an error, not an out-of-memory abort.
/// Bytes the decoded pictures of one decoder may take: 4 GiB on 64-bit targets, 1 GiB on 32-bit
/// ones (wasm32 has a 4 GiB address space in all).
pub const DECODE_MEMORY_BUDGET: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 };
/// The shape of one decoded picture as a decoder allocates it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PictureShape {
/// Allocated luma samples per row and rows (padding included).
pub width: u64,
pub height: u64,
/// Chroma subsampling shifts (0 or 1); ignored when `chroma_planes` is 0.
pub shift_x: u32,
pub shift_y: u32,
/// Chroma planes (0 for monochrome, 2 otherwise).
pub chroma_planes: u64,
/// Bytes per sample (1 for 8-bit buffers, 2 for 16-bit ones).
pub bytes_per_sample: u64,
}
impl PictureShape {
/// Bytes of one picture, `None` if it does not fit in a `u64`.
pub fn bytes(&self) -> Option<u64> {
let luma = self.width.checked_mul(self.height)?;
let cw = self.width.div_ceil(1 << self.shift_x.min(1));
let ch = self.height.div_ceil(1 << self.shift_y.min(1));
let chroma = cw.checked_mul(ch)?.checked_mul(self.chroma_planes)?;
luma.checked_add(chroma)?.checked_mul(self.bytes_per_sample)
}
/// Bytes of `pictures` such pictures, `None` on overflow.
pub fn store_bytes(&self, pictures: u64) -> Option<u64> {
self.bytes()?.checked_mul(pictures)
}
/// Whether `pictures` such pictures fit in `budget` bytes.
pub fn fits(&self, pictures: u64, budget: u64) -> bool {
self.store_bytes(pictures).is_some_and(|b| b <= budget)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn shape(w: u64, h: u64) -> PictureShape {
PictureShape { width: w, height: h, shift_x: 1, shift_y: 1, chroma_planes: 2, bytes_per_sample: 2 }
}
#[test]
fn bytes_count_luma_and_subsampled_chroma() {
assert_eq!(shape(4, 4).bytes(), Some((16 + 2 * 4) * 2));
// Odd sizes round chroma up.
assert_eq!(shape(3, 3).bytes(), Some((9 + 2 * 4) * 2));
let mono = PictureShape { chroma_planes: 0, bytes_per_sample: 1, ..shape(10, 10) };
assert_eq!(mono.bytes(), Some(100));
let full = PictureShape { shift_x: 0, shift_y: 0, ..shape(10, 10) };
assert_eq!(full.bytes(), Some(600));
}
#[test]
fn exact_budget_boundary() {
let s = shape(4, 4); // 48 bytes
assert!(s.fits(10, 480));
assert!(!s.fits(10, 479));
assert!(!s.fits(11, 480));
}
#[test]
fn overflow_is_never_within_budget() {
let huge = shape(u64::MAX / 2, 3);
assert_eq!(huge.bytes(), None);
assert!(!huge.fits(1, u64::MAX));
assert!(!shape(1 << 31, 1 << 31).fits(u64::MAX, u64::MAX));
}
}
+442 -5
View File
@@ -1,14 +1,451 @@
//! Bit-level reading and writing for DeckCraft's codec crates: a re-export of
//! [`craft_media::bitstream`] from craft-libs, plus [`budget`].
//! Bit-level reading and writing shared by DeckCraft's codec crates (ported from FilmCraft).
//!
//! - [`BitReader`]: MSB-first reader with Exp-Golomb (`ue(v)`, `se(v)`), as used by H.264/HEVC/AV1 headers.
//! - [`BitWriter`]: the matching writer (for encoders and header rewriting).
//! - [`unescape_rbsp`] / [`escape_rbsp`]: remove/insert H.264/HEVC emulation-prevention bytes.
//! - [`annexb_nals`] / [`length_prefixed_nals`]: split Annex-B byte streams and AVCC/HVCC samples into NAL units.
//! - [`budget`]: the memory budget video decoders check their picture store against.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
pub use craft_media::bitstream::*;
use std::fmt;
pub mod budget;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitError {
/// Tried to read past the end of the buffer.
Eof,
/// An Exp-Golomb code longer than 32 leading zeros.
InvalidExpGolomb,
}
impl fmt::Display for BitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BitError::Eof => f.write_str("unexpected end of bitstream"),
BitError::InvalidExpGolomb => f.write_str("invalid Exp-Golomb code"),
}
}
}
impl std::error::Error for BitError {}
pub type Result<T> = std::result::Result<T, BitError>;
/// MSB-first bit reader over a byte slice.
#[derive(Clone)]
pub struct BitReader<'a> {
data: &'a [u8],
/// Position in bits.
pos: usize,
}
impl<'a> BitReader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
pub fn data(&self) -> &'a [u8] {
self.data
}
/// Bit position from the start.
pub fn position(&self) -> usize {
self.pos
}
pub fn bits_left(&self) -> usize {
(self.data.len() * 8).saturating_sub(self.pos)
}
pub fn is_byte_aligned(&self) -> bool {
self.pos.is_multiple_of(8)
}
pub fn byte_align(&mut self) {
self.pos = self.pos.div_ceil(8) * 8;
}
/// Byte offset of the current position (rounded down).
pub fn byte_pos(&self) -> usize {
self.pos / 8
}
pub fn seek_bits(&mut self, pos: usize) {
self.pos = pos;
}
/// Peek up to 32 bits without consuming (zero-padded past the end).
#[inline]
pub fn peek(&self, n: u32) -> u32 {
debug_assert!(n <= 32);
if n == 0 {
return 0;
}
let byte = self.pos / 8;
let shift = self.pos % 8;
let mut v: u64 = 0;
for i in 0..5 {
v = (v << 8) | *self.data.get(byte + i).unwrap_or(&0) as u64;
}
// v holds 40 bits starting at `byte`
((v << (24 + shift)) >> (64 - n)) as u32
}
#[inline]
pub fn read_bits(&mut self, n: u32) -> Result<u32> {
if n as usize > self.bits_left() {
return Err(BitError::Eof);
}
let v = self.peek(n);
self.pos += n as usize;
Ok(v)
}
pub fn read_bits_u64(&mut self, n: u32) -> Result<u64> {
if n <= 32 {
return self.read_bits(n).map(u64::from);
}
let hi = self.read_bits(n - 32)? as u64;
let lo = self.read_bits(32)? as u64;
Ok((hi << 32) | lo)
}
#[inline]
pub fn read_bit(&mut self) -> Result<bool> {
self.read_bits(1).map(|b| b == 1)
}
pub fn read_flag(&mut self) -> Result<bool> {
self.read_bit()
}
pub fn skip(&mut self, n: usize) -> Result<()> {
if n > self.bits_left() {
return Err(BitError::Eof);
}
self.pos += n;
Ok(())
}
/// Unsigned Exp-Golomb `ue(v)`.
pub fn read_ue(&mut self) -> Result<u32> {
let mut zeros = 0u32;
while !self.read_bit()? {
zeros += 1;
if zeros > 32 {
return Err(BitError::InvalidExpGolomb);
}
}
if zeros == 0 {
return Ok(0);
}
let v = self.read_bits_u64(zeros)?;
let r = (1u64 << zeros) - 1 + v;
u32::try_from(r).map_err(|_| BitError::InvalidExpGolomb)
}
/// `ue(v) + add` (the `..._minus1` / `..._minus8` fields), failing instead of overflowing on a
/// hostile value near `u32::MAX`.
pub fn read_ue_plus(&mut self, add: u32) -> Result<u32> {
self.read_ue()?.checked_add(add).ok_or(BitError::InvalidExpGolomb)
}
/// Signed Exp-Golomb `se(v)`.
pub fn read_se(&mut self) -> Result<i32> {
let k = self.read_ue()? as i64;
Ok(if k & 1 == 1 { ((k + 1) / 2) as i32 } else { -((k / 2) as i32) })
}
/// Truncated Exp-Golomb `te(v)` with range `max`.
pub fn read_te(&mut self, max: u32) -> Result<u32> {
if max > 1 { self.read_ue() } else { Ok(!self.read_bit()? as u32) }
}
/// H.264/HEVC `more_rbsp_data()`: true if there is data before the rbsp trailing bits.
pub fn more_rbsp_data(&self) -> bool {
let total = self.data.len() * 8;
if self.pos >= total {
return false;
}
// find last set bit (the rbsp_stop_one_bit)
let mut last = None;
for (i, &b) in self.data.iter().enumerate().rev() {
if b != 0 {
last = Some(i * 8 + 7 - b.trailing_zeros() as usize);
break;
}
}
match last {
Some(stop) => self.pos < stop,
None => false,
}
}
}
/// MSB-first bit writer.
#[derive(Default, Clone)]
pub struct BitWriter {
buf: Vec<u8>,
acc: u64,
nbits: u32,
}
impl BitWriter {
pub fn new() -> Self {
Self::default()
}
pub fn write_bits(&mut self, value: u32, n: u32) {
debug_assert!(n <= 32);
if n == 0 {
return;
}
let v = (value as u64) & ((1u64 << n) - 1);
self.acc = (self.acc << n) | v;
self.nbits += n;
while self.nbits >= 8 {
self.nbits -= 8;
self.buf.push((self.acc >> self.nbits) as u8);
}
self.acc &= (1u64 << self.nbits) - 1;
}
pub fn write_bit(&mut self, b: bool) {
self.write_bits(b as u32, 1);
}
pub fn write_ue(&mut self, v: u32) {
let x = v as u64 + 1;
let len = 64 - x.leading_zeros();
let zeros = len - 1;
for _ in 0..zeros {
self.write_bit(false);
}
if len > 32 {
self.write_bits((x >> 32) as u32, len - 32);
self.write_bits(x as u32, 32);
} else {
self.write_bits(x as u32, len);
}
}
pub fn write_se(&mut self, v: i32) {
let k = if v > 0 { (v as u32) * 2 - 1 } else { (-(v as i64) as u32) * 2 };
self.write_ue(k);
}
pub fn bit_len(&self) -> usize {
self.buf.len() * 8 + self.nbits as usize
}
pub fn is_byte_aligned(&self) -> bool {
self.nbits == 0
}
/// Pad with zero bits to a byte boundary.
pub fn align_zero(&mut self) {
if self.nbits > 0 {
self.write_bits(0, 8 - self.nbits);
}
}
/// `rbsp_trailing_bits()`: a one bit then zeros to alignment.
pub fn rbsp_trailing(&mut self) {
self.write_bit(true);
self.align_zero();
}
pub fn write_bytes(&mut self, bytes: &[u8]) {
if self.nbits == 0 {
self.buf.extend_from_slice(bytes);
} else {
for &b in bytes {
self.write_bits(b as u32, 8);
}
}
}
pub fn finish(mut self) -> Vec<u8> {
self.align_zero();
self.buf
}
pub fn bytes(&self) -> &[u8] {
&self.buf
}
}
/// Remove emulation-prevention bytes (`00 00 03` → `00 00`) from a NAL payload.
pub fn unescape_rbsp(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len());
let mut zeros = 0;
for &b in data {
if zeros >= 2 && b == 3 {
zeros = 0;
continue;
}
out.push(b);
zeros = if b == 0 { zeros + 1 } else { 0 };
}
out
}
/// Insert emulation-prevention bytes so no `00 00 0x` (x ≤ 3) sequence appears.
pub fn escape_rbsp(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + data.len() / 64);
let mut zeros = 0;
for &b in data {
if zeros >= 2 && b <= 3 {
out.push(3);
zeros = 0;
}
out.push(b);
zeros = if b == 0 { zeros + 1 } else { 0 };
}
out
}
/// Split an Annex-B byte stream (start codes `00 00 01` / `00 00 00 01`) into NAL units (escaped payloads).
pub fn annexb_nals(data: &[u8]) -> Vec<&[u8]> {
let mut starts = Vec::new();
let mut i = 0;
while i + 3 <= data.len() {
if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
starts.push(i + 3);
i += 3;
} else {
i += 1;
}
}
let mut out = Vec::with_capacity(starts.len());
for (k, &s) in starts.iter().enumerate() {
let mut e = if k + 1 < starts.len() { starts[k + 1] - 3 } else { data.len() };
// trim trailing zero bytes (part of a 4-byte start code or trailing_zero_8bits)
while e > s && data[e - 1] == 0 {
e -= 1;
}
if e > s {
out.push(&data[s..e]);
}
}
out
}
/// Split a length-prefixed sample (AVCC/HVCC, `length_size` 1/2/4 bytes) into NAL units.
pub fn length_prefixed_nals(data: &[u8], length_size: usize) -> Result<Vec<&[u8]>> {
let mut out = Vec::new();
let mut i = 0;
while i < data.len() {
if i + length_size > data.len() {
return Err(BitError::Eof);
}
let mut len = 0usize;
for k in 0..length_size {
len = (len << 8) | data[i + k] as usize;
}
i += length_size;
if i + len > data.len() {
return Err(BitError::Eof);
}
out.push(&data[i..i + len]);
i += len;
}
Ok(out)
}
/// CRC-32 (IEEE, reflected) — used by containers (e.g. Matroska CRC-32 elements, PNG).
pub fn crc32(data: &[u8]) -> u32 {
let mut crc = 0xFFFF_FFFFu32;
for &b in data {
crc ^= b as u32;
for _ in 0..8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
}
}
!crc
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn read_ue_plus_rejects_overflow() {
let mut w = BitWriter::new();
w.write_ue(7);
w.write_ue(u32::MAX);
w.rbsp_trailing();
let b = w.finish();
let mut r = BitReader::new(&b);
assert_eq!(r.read_ue_plus(1).unwrap(), 8);
assert!(r.read_ue_plus(1).is_err());
}
#[test]
fn reads_bits() {
let d = [0b1010_1100, 0b0101_0011];
let mut r = BitReader::new(&d);
assert_eq!(r.read_bits(1).unwrap(), 1);
assert_eq!(r.read_bits(3).unwrap(), 0b010);
assert_eq!(r.read_bits(8).unwrap(), 0b1100_0101);
assert_eq!(r.bits_left(), 4);
assert_eq!(r.read_bits(5), Err(BitError::Eof));
}
#[test]
fn exp_golomb_known() {
// 1 | 010 | 011 | 00100 | 00101 -> 0,1,2,3,4
let mut w = BitWriter::new();
for v in 0..5 {
w.write_ue(v);
}
let b = w.finish();
let mut r = BitReader::new(&b);
for v in 0..5 {
assert_eq!(r.read_ue().unwrap(), v);
}
let mut w = BitWriter::new();
for v in [0, 1, -1, 2, -2, 1000, -1000] {
w.write_se(v);
}
let b = w.finish();
let mut r = BitReader::new(&b);
for v in [0, 1, -1, 2, -2, 1000, -1000] {
assert_eq!(r.read_se().unwrap(), v);
}
}
#[test]
fn emulation_prevention() {
let raw = [0, 0, 1, 0, 0, 0, 5, 0, 0, 3];
let esc = escape_rbsp(&raw);
assert_eq!(esc, vec![0, 0, 3, 1, 0, 0, 3, 0, 5, 0, 0, 3, 3]);
assert_eq!(unescape_rbsp(&esc), raw);
}
#[test]
fn annexb_split() {
let s = [0, 0, 0, 1, 0x67, 1, 2, 0, 0, 1, 0x68, 3, 0, 0, 0, 1, 0x65, 9, 9];
let n = annexb_nals(&s);
assert_eq!(n, vec![&[0x67, 1, 2][..], &[0x68, 3][..], &[0x65, 9, 9][..]]);
let l = [0, 0, 0, 2, 0x67, 1, 0, 0, 0, 1, 0x68];
assert_eq!(length_prefixed_nals(&l, 4).unwrap(), vec![&[0x67, 1][..], &[0x68][..]]);
}
#[test]
fn more_rbsp() {
let d = [0b1100_0000];
let mut r = BitReader::new(&d);
assert!(r.more_rbsp_data());
r.read_bit().unwrap();
assert!(!r.more_rbsp_data());
}
#[test]
fn crc() {
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
}
proptest! {
#[test]
fn roundtrip(vals in proptest::collection::vec((0u32..u32::MAX, 1u32..=32), 0..200), ues in proptest::collection::vec(0u32..u32::MAX - 1, 0..50)) {
let mut w = BitWriter::new();
for &(v, n) in &vals { w.write_bits(v, n); }
for &u in &ues { w.write_ue(u); }
let b = w.finish();
let mut r = BitReader::new(&b);
for &(v, n) in &vals {
let mask = if n == 32 { u32::MAX } else { (1 << n) - 1 };
prop_assert_eq!(r.read_bits(n).unwrap(), v & mask);
}
for &u in &ues { prop_assert_eq!(r.read_ue().unwrap(), u); }
}
#[test]
fn escape_roundtrip(data in proptest::collection::vec(0u8..4, 0..300)) {
let e = escape_rbsp(&data);
prop_assert_eq!(unescape_rbsp(&e), data);
for w in e.windows(3) { prop_assert!(!(w[0] == 0 && w[1] == 0 && w[2] < 3)); }
}
}
}
+2 -258
View File
@@ -34,9 +34,8 @@ impl Rgba {
}
/// `RRGGBB` or `#RRGGBB` (also `RRGGBBAA`).
pub fn from_hex(s: &str) -> Option<Self> {
let s = s.trim();
let s = s.strip_prefix('#').unwrap_or(s);
if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
let s = s.trim().trim_start_matches('#');
if !s.is_ascii() {
return None;
}
let byte = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok());
@@ -516,265 +515,10 @@ pub fn preset(name: &str) -> Option<Rgba> {
Some(Rgba::rgb(c.0, c.1, c.2))
}
/// Every preset colour name a file may write (`ST_PresetColorVal`, with the later editions' aliases).
pub const PRESET_NAMES: [&str; 190] = [
"aliceBlue",
"antiqueWhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedAlmond",
"blue",
"blueViolet",
"brown",
"burlyWood",
"cadetBlue",
"chartreuse",
"chocolate",
"coral",
"cornflowerBlue",
"cornsilk",
"crimson",
"cyan",
"darkBlue",
"darkCyan",
"darkGoldenrod",
"darkGray",
"darkGrey",
"darkGreen",
"darkKhaki",
"darkMagenta",
"darkOliveGreen",
"darkOrange",
"darkOrchid",
"darkRed",
"darkSalmon",
"darkSeaGreen",
"darkSlateBlue",
"darkSlateGray",
"darkSlateGrey",
"darkTurquoise",
"darkViolet",
"dkBlue",
"dkCyan",
"dkGoldenrod",
"dkGray",
"dkGrey",
"dkGreen",
"dkKhaki",
"dkMagenta",
"dkOliveGreen",
"dkOrange",
"dkOrchid",
"dkRed",
"dkSalmon",
"dkSeaGreen",
"dkSlateBlue",
"dkSlateGray",
"dkSlateGrey",
"dkTurquoise",
"dkViolet",
"deepPink",
"deepSkyBlue",
"dimGray",
"dimGrey",
"dodgerBlue",
"firebrick",
"floralWhite",
"forestGreen",
"fuchsia",
"gainsboro",
"ghostWhite",
"gold",
"goldenrod",
"gray",
"grey",
"green",
"greenYellow",
"honeydew",
"hotPink",
"indianRed",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderBlush",
"lawnGreen",
"lemonChiffon",
"lightBlue",
"lightCoral",
"lightCyan",
"lightGoldenrodYellow",
"lightGray",
"lightGrey",
"lightGreen",
"lightPink",
"lightSalmon",
"lightSeaGreen",
"lightSkyBlue",
"lightSlateGray",
"lightSlateGrey",
"lightSteelBlue",
"lightYellow",
"ltBlue",
"ltCoral",
"ltCyan",
"ltGoldenrodYellow",
"ltGray",
"ltGrey",
"ltGreen",
"ltPink",
"ltSalmon",
"ltSeaGreen",
"ltSkyBlue",
"ltSlateGray",
"ltSlateGrey",
"ltSteelBlue",
"ltYellow",
"lime",
"limeGreen",
"linen",
"magenta",
"maroon",
"medAquamarine",
"medBlue",
"medOrchid",
"medPurple",
"medSeaGreen",
"medSlateBlue",
"medSpringGreen",
"medTurquoise",
"medVioletRed",
"mediumAquamarine",
"mediumBlue",
"mediumOrchid",
"mediumPurple",
"mediumSeaGreen",
"mediumSlateBlue",
"mediumSpringGreen",
"mediumTurquoise",
"mediumVioletRed",
"midnightBlue",
"mintCream",
"mistyRose",
"moccasin",
"navajoWhite",
"navy",
"oldLace",
"olive",
"oliveDrab",
"orange",
"orangeRed",
"orchid",
"paleGoldenrod",
"paleGreen",
"paleTurquoise",
"paleVioletRed",
"papayaWhip",
"peachPuff",
"peru",
"pink",
"plum",
"powderBlue",
"purple",
"red",
"rosyBrown",
"royalBlue",
"saddleBrown",
"salmon",
"sandyBrown",
"seaGreen",
"seaShell",
"sienna",
"silver",
"skyBlue",
"slateBlue",
"slateGray",
"slateGrey",
"snow",
"springGreen",
"steelBlue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whiteSmoke",
"yellow",
"yellowGreen",
];
/// Every system colour name a file may write (`ST_SystemColorVal`).
pub const SYSTEM_NAMES: [&str; 30] = [
"scrollBar",
"background",
"activeCaption",
"inactiveCaption",
"menu",
"window",
"windowFrame",
"menuText",
"windowText",
"captionText",
"activeBorder",
"inactiveBorder",
"appWorkspace",
"highlight",
"highlightText",
"btnFace",
"btnShadow",
"grayText",
"btnText",
"inactiveCaptionText",
"btnHighlight",
"3dDkShadow",
"3dLight",
"infoText",
"infoBk",
"hotLight",
"gradientActiveCaption",
"gradientInactiveCaption",
"menuHighlight",
"menuBar",
];
/// Whether `name` is a preset colour name a file may write.
pub fn is_preset_name(name: &str) -> bool {
PRESET_NAMES.contains(&name)
}
/// Whether `name` is a system colour name a file may write.
pub fn is_system_name(name: &str) -> bool {
SYSTEM_NAMES.contains(&name)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_hex_rejects_multiple_hashes() {
assert_eq!(Rgba::from_hex("##FF0000"), None);
assert_eq!(Rgba::from_hex("####FF0000"), None);
assert_eq!(Rgba::from_hex("#FF0000"), Some(Rgba::rgb(255, 0, 0)));
assert_eq!(Rgba::from_hex("FF0000"), Some(Rgba::rgb(255, 0, 0)));
assert_eq!(Rgba::from_hex("#FF000080"), Some(Rgba::rgba(255, 0, 0, 128)));
}
#[test]
fn from_hex_rejects_signs() {
assert_eq!(Rgba::from_hex("+12345"), None);
assert_eq!(Rgba::from_hex("#+1+2+3"), None);
assert_eq!(Rgba::from_hex("+1+2+3+4"), None);
assert_eq!(Rgba::from_hex("+12"), None);
}
#[test]
fn hex_roundtrip() {
assert_eq!(Rgba::from_hex("#156082"), Some(Rgba::rgb(0x15, 0x60, 0x82)));
-10
View File
@@ -25,13 +25,3 @@ i_overlay = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
image = { workspace = true }
chrono = { workspace = true }
[dev-dependencies]
deckcraft-anim = { workspace = true }
zip = { workspace = true }
# The browser clock for comment timestamps (wasm has no std::time::SystemTime).
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3"
-264
View File
@@ -1,264 +0,0 @@
# DeckCraft's built-in thesaurus: headword|synonym, synonym, ...
# Written for DeckCraft (no third-party word list). Lowercase; one meaning group per line;
# a headword may appear on several lines (one per sense).
ability|capability, capacity, skill, competence, talent
able|capable, competent, qualified, skilled
accept|agree to, approve, adopt, embrace
accurate|precise, exact, correct, right
achieve|accomplish, attain, reach, realize, deliver
achievement|accomplishment, success, attainment, milestone
add|include, append, attach, insert
advantage|benefit, edge, strength, asset, upside
affect|influence, impact, change, alter
aim|goal, objective, target, purpose, intent
allow|permit, enable, let, authorize
analyze|examine, study, assess, evaluate, review
answer|reply, response, solution
approach|method, strategy, way, technique, plan
area|region, field, domain, zone, sector
arrange|organize, order, sort, plan
ask|request, inquire, query, question
assess|evaluate, gauge, judge, review, appraise
assist|help, aid, support, back
attempt|try, effort, endeavor, bid
bad|poor, weak, inferior, unfavorable, negative
basic|fundamental, essential, core, elementary, simple
begin|start, commence, launch, initiate, open
benefit|advantage, gain, value, payoff, upside
best|finest, top, leading, optimal, premier
big|large, major, substantial, significant, sizable
boost|increase, raise, lift, improve, strengthen
brief|short, concise, succinct, quick
bright|vivid, brilliant, luminous, clever
build|construct, create, develop, assemble, establish
business|company, firm, enterprise, organization, venture
buy|purchase, acquire, obtain
careful|cautious, thorough, meticulous, attentive
cause|reason, source, origin, driver
change|alter, modify, adjust, revise, transform
change|shift, transition, adjustment, revision
cheap|inexpensive, affordable, low-cost, economical
check|verify, confirm, examine, inspect, review
choice|option, alternative, selection, pick
choose|select, pick, opt for, decide on
clear|plain, obvious, evident, transparent, lucid
client|customer, buyer, account, patron
close|near, nearby, adjacent
close|end, finish, conclude, shut
common|frequent, usual, typical, widespread, shared
company|business, firm, organization, enterprise, corporation
complete|finish, conclude, finalize, accomplish
complete|whole, full, entire, total
complex|complicated, intricate, involved, elaborate
concern|worry, issue, problem, risk
consider|weigh, contemplate, evaluate, think about
continue|proceed, carry on, keep going, persist, maintain
cost|price, expense, charge, outlay
create|make, build, produce, design, generate
critical|crucial, vital, essential, key, decisive
current|present, existing, ongoing, latest, up-to-date
customer|client, buyer, consumer, user
data|information, figures, facts, statistics
decide|determine, choose, resolve, settle
decrease|reduce, lower, cut, decline, drop
define|specify, describe, explain, outline
deliver|provide, supply, bring, hand over, ship
demonstrate|show, prove, illustrate, display
describe|explain, outline, portray, depict
design|plan, layout, blueprint, pattern
design|create, plan, devise, draft
develop|build, create, grow, expand, evolve
difference|distinction, contrast, gap, variation
different|distinct, various, diverse, unlike
difficult|hard, challenging, tough, demanding
discuss|talk about, debate, examine, review
easy|simple, straightforward, effortless, painless
effect|result, impact, outcome, consequence
effective|successful, efficient, productive, powerful
effort|work, attempt, endeavor, exertion
end|finish, conclusion, close, completion
enough|sufficient, adequate, ample
ensure|guarantee, make sure, secure, confirm
error|mistake, fault, flaw, bug, slip
essential|vital, crucial, key, necessary, fundamental
establish|set up, found, create, institute
estimate|forecast, projection, approximation, guess
evaluate|assess, appraise, judge, rate, review
event|occasion, function, happening, incident
example|instance, case, illustration, sample
excellent|outstanding, superb, exceptional, first-rate
expand|grow, extend, enlarge, broaden, scale
expect|anticipate, foresee, predict, await
explain|clarify, describe, illustrate, account for
fail|fall short, miss, flop, break down
fast|quick, rapid, swift, speedy
feature|characteristic, attribute, capability, function
final|last, closing, concluding, ultimate
find|discover, locate, identify, uncover
finish|complete, end, conclude, wrap up
focus|concentrate, center, target, emphasize
focus|emphasis, priority, attention, core
future|upcoming, coming, forthcoming, prospective
gain|increase, rise, improvement, profit
get|obtain, acquire, receive, gain
give|provide, offer, supply, grant
goal|aim, objective, target, purpose, ambition
good|fine, great, strong, solid, positive
great|excellent, outstanding, terrific, remarkable
grow|increase, expand, rise, develop, scale
growth|expansion, increase, development, rise
help|assist, aid, support, enable
help|assistance, aid, support, guidance
high|elevated, tall, top, strong
idea|concept, notion, thought, proposal
identify|recognize, pinpoint, detect, determine
impact|effect, influence, consequence, result
important|significant, key, major, crucial, vital
improve|enhance, upgrade, refine, strengthen, boost
include|contain, cover, incorporate, comprise
increase|raise, boost, grow, expand, lift
increase|rise, growth, gain, jump
information|data, details, facts, knowledge
innovative|inventive, creative, original, novel, pioneering
issue|problem, concern, matter, question
job|task, assignment, role, position
keep|retain, maintain, preserve, hold
key|main, central, critical, essential, principal
large|big, sizable, substantial, major, extensive
last|final, latest, previous, closing
launch|start, introduce, roll out, release, unveil
lead|guide, direct, head, steer, run
learn|discover, find out, master, study
less|fewer, smaller, reduced, lower
little|small, minor, slight, modest
look|appear, seem
look|view, glance, examine, inspect
low|minimal, modest, small, reduced
main|primary, chief, principal, central, key
maintain|keep, preserve, sustain, uphold
major|significant, important, key, principal, big
make|create, build, produce, generate
manage|run, handle, oversee, direct, lead
market|industry, sector, segment, marketplace
measure|gauge, assess, quantify, track
meet|satisfy, fulfil, reach, achieve
meeting|session, conference, discussion, review
method|approach, technique, process, procedure, way
model|framework, template, pattern, design
more|additional, extra, further, added
move|shift, transfer, relocate, transition
need|requirement, demand, necessity
need|require, call for, demand, want
new|fresh, recent, novel, modern, latest
next|following, upcoming, subsequent
number|figure, count, total, quantity, amount
objective|goal, aim, target, purpose
offer|provide, propose, extend, present
old|previous, former, legacy, outdated, existing
open|start, launch, begin, unveil
opportunity|opening, chance, prospect, possibility
option|choice, alternative, possibility, route
organize|arrange, structure, coordinate, order
outcome|result, consequence, effect, end result
overview|summary, outline, synopsis, recap
part|portion, piece, segment, section, component
partner|ally, collaborator, associate, affiliate
people|staff, team, individuals, personnel
plan|strategy, scheme, roadmap, proposal, program
plan|organize, arrange, schedule, prepare
point|aspect, detail, issue, argument
popular|well-liked, widespread, in demand, favored
possible|feasible, achievable, viable, potential
present|show, display, introduce, demonstrate
present|current, existing, ongoing
price|cost, rate, charge, fee
priority|focus, concern, precedence, goal
problem|issue, challenge, difficulty, obstacle
process|procedure, method, workflow, system
produce|make, create, generate, manufacture, yield
product|offering, item, solution, good
profit|earnings, return, gain, margin
progress|advance, headway, development, improvement
project|initiative, program, undertaking, venture
propose|suggest, recommend, put forward, offer
provide|give, supply, deliver, offer
purpose|aim, goal, objective, intent, reason
quality|standard, caliber, excellence, grade
question|query, issue, inquiry
quick|fast, rapid, speedy, swift, prompt
rapid|fast, quick, swift, speedy
reach|achieve, attain, hit, arrive at
reason|cause, rationale, motive, basis
recent|latest, new, current, fresh
recommend|suggest, advise, propose, advocate
reduce|cut, lower, decrease, lessen, trim
region|area, territory, zone, market
relevant|pertinent, applicable, related, appropriate
remove|delete, eliminate, take out, drop
replace|substitute, swap, supersede, change
report|account, summary, review, statement
require|need, demand, call for, necessitate
research|study, investigation, analysis, inquiry
resource|asset, supply, means, capacity
result|outcome, effect, consequence, finding
review|assessment, evaluation, examination, analysis
review|examine, assess, evaluate, check, revisit
revenue|income, sales, earnings, turnover
risk|danger, threat, exposure, hazard
role|part, function, position, responsibility
run|operate, manage, conduct, execute
safe|secure, protected, reliable
same|identical, equal, matching, equivalent
save|keep, store, preserve, conserve
see|view, observe, notice, spot
sell|market, offer, trade, retail
service|support, assistance, offering
share|portion, part, stake, percentage
share|distribute, spread, communicate, pass on
show|demonstrate, display, present, reveal, illustrate
significant|important, notable, considerable, major, meaningful
similar|alike, comparable, related, equivalent
simple|easy, straightforward, plain, basic
size|scale, extent, magnitude, dimensions
small|little, minor, compact, modest
solution|answer, fix, remedy, resolution
solve|resolve, fix, settle, work out
specific|particular, precise, exact, distinct
start|begin, launch, commence, kick off, initiate
step|stage, phase, measure, action
strategy|plan, approach, policy, roadmap, tactic
strong|robust, solid, powerful, sturdy
structure|framework, organization, layout, arrangement
success|achievement, accomplishment, win, triumph
successful|effective, thriving, prosperous, winning
suggest|propose, recommend, advise, imply
summary|overview, recap, synopsis, digest
support|help, back, assist, sustain
support|help, assistance, backing, aid
sure|certain, confident, positive, definite
target|goal, objective, aim
task|job, assignment, duty, activity
team|group, crew, staff, squad, unit
test|trial, check, experiment, evaluation
test|try, check, evaluate, verify
think|believe, consider, reckon, suppose
time|period, duration, while, moment
tool|instrument, utility, device, aid
total|sum, whole, aggregate, overall
trend|pattern, tendency, movement, direction
understand|grasp, comprehend, follow, realize
unique|distinctive, singular, one-of-a-kind, unmatched
update|revise, refresh, upgrade, modernize
update|revision, change, upgrade, news
use|employ, apply, utilize, leverage
useful|helpful, practical, handy, valuable
value|worth, benefit, merit, importance
various|diverse, assorted, different, several
view|opinion, perspective, outlook, position
vision|outlook, aspiration, goal, dream
way|method, approach, manner, means
weak|feeble, fragile, poor, limited
well|effectively, successfully, nicely, properly
work|labor, effort, activity, job
work|function, operate, run, succeed
year|annum, twelve months
-696
View File
@@ -1,696 +0,0 @@
//! The command registry. Ids follow PowerPoint's ribbon and menu structure.
pub mod animation;
pub mod arrange;
pub mod artistic;
pub mod background;
pub mod compress;
pub mod design;
pub mod edit;
pub mod file;
pub mod find;
pub mod format;
pub mod ideas;
pub mod insert;
pub mod inspect;
pub mod media;
pub mod merge;
pub mod picture_style;
pub mod points;
pub mod recolor;
pub mod reuse;
pub mod review;
mod richclip;
pub mod selection;
pub mod shape;
pub mod slide;
pub mod smartart;
pub mod table;
pub mod text;
pub mod three_d;
pub mod transition;
pub mod zoom;
use deckcraft_geom::Xfrm;
use deckcraft_model::ShapeId;
use serde::Serialize;
use serde_json::Value;
use crate::{EngineError, Result, Session};
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Where it lives: `["Home", "Font"]` (ribbon tab and group) or `["Arrange"]` (menu).
pub menu: &'static [&'static str],
pub shortcut: Option<&'static str>,
/// The parameters as `describe` and `commands` show them, read by [`parse_params`]: `?` marks
/// an optional key, a spaced ` | ` separates alternative sets of keys (so alternative values
/// are written unspaced, `ms|null`), `(…)` is a remark and `→` starts the answer.
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
pub journal: bool,
pub undoable: bool,
}
#[derive(Clone, Debug, Serialize)]
pub struct CommandInfo {
pub id: &'static str,
pub label: &'static str,
pub menu: Vec<&'static str>,
pub shortcut: Option<&'static str>,
pub params: &'static str,
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled_reason: Option<String>,
}
impl CommandSpec {
/// Holds because `Session::execute` skips the selection check when `id` or `ids` is given.
pub fn acts_on(&self) -> Option<String> {
let keys = param_keys(self.params).unwrap_or_default();
let named = if keys.contains(&"ids") {
Some("the shapes in `ids`")
} else if keys.contains(&"id") {
Some("the shape in `id`")
} else {
None
};
let reason = (self.enabled)(&Session::with_new()).err()?;
Some(match (reason.as_str(), named) {
(SELECT_TEXT_OR_SHAPE, _) => "Acts on the selected text or shapes.".into(),
(NOTHING_SELECTED, Some(n)) => format!("Acts on {n}, else on the selected shapes."),
(NOTHING_SELECTED, None) => "Acts on the selected shapes.".into(),
(SELECT_TWO, Some(n)) => format!("Acts on two or more shapes: {n}, else the selected ones."),
(SELECT_TWO, None) => "Acts on two or more selected shapes.".into(),
(NO_TEXT_POINT, _) => "Acts on the text being edited; text.edit starts editing a shape's text.".into(),
_ => return None,
})
}
pub fn info(&self, s: &Session) -> CommandInfo {
let e = (self.enabled)(s);
CommandInfo {
id: self.id,
label: self.label,
menu: self.menu.to_vec(),
shortcut: self.shortcut,
params: self.params,
enabled: e.is_ok(),
disabled_reason: e.err(),
}
}
}
pub fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
pub fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no presentation open".into())
}
pub fn has_slide(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.active().is_some_and(|d| !d.doc.slides.is_empty() || d.selection.target != crate::Target::Slides) { Ok(()) } else { Err("no slides".into()) }
}
pub const NOTHING_SELECTED: &str = "nothing selected";
pub const SELECT_TWO: &str = "select two or more objects";
pub const NO_TEXT_POINT: &str = "no text insertion point";
pub const SELECT_TEXT_OR_SHAPE: &str = "select text or a shape";
pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.active().is_some_and(|d| !d.selection.shapes.is_empty()) { Ok(()) } else { Err(NOTHING_SELECTED.into()) }
}
pub fn has_two(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.active().is_some_and(|d| d.selection.shapes.len() >= 2) { Ok(()) } else { Err(SELECT_TWO.into()) }
}
pub fn has_text(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.active().is_some_and(|d| d.selection.text.is_some()) { Ok(()) } else { Err(NO_TEXT_POINT.into()) }
}
/// Text editing or selected shapes (formatting commands apply to either).
pub fn has_text_or_shapes(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.active().is_some_and(|d| d.selection.text.is_some() || !d.selection.shapes.is_empty()) { Ok(()) } else { Err(SELECT_TEXT_OR_SHAPE.into()) }
}
pub fn can_undo(s: &Session) -> std::result::Result<(), String> {
if s.active().is_some_and(|d| !d.history.undo.is_empty()) { Ok(()) } else { Err("nothing to undo".into()) }
}
pub fn can_redo(s: &Session) -> std::result::Result<(), String> {
if s.active().is_some_and(|d| !d.history.redo.is_empty()) { Ok(()) } else { Err("nothing to redo".into()) }
}
macro_rules! cmd {
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: true }
};
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, undoable: false }
};
(noundo $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: false }
};
}
pub(crate) use cmd;
pub fn command_specs() -> &'static [CommandSpec] {
static SPECS: std::sync::OnceLock<Vec<CommandSpec>> = std::sync::OnceLock::new();
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(file::specs());
v.extend(edit::specs());
v.extend(slide::specs());
v.extend(reuse::specs());
v.extend(insert::specs());
v.extend(smartart::specs());
v.extend(shape::specs());
v.extend(background::specs());
v.extend(picture_style::specs());
v.extend(recolor::specs());
v.extend(arrange::specs());
v.extend(selection::specs());
v.extend(merge::specs());
v.extend(points::specs());
v.extend(text::specs());
v.extend(format::specs());
v.extend(design::specs());
v.extend(ideas::specs());
v.extend(transition::specs());
v.extend(animation::specs());
v.extend(table::specs());
v.extend(find::specs());
v.extend(review::specs());
v.extend(inspect::specs());
v.extend(media::specs());
v.extend(artistic::specs());
v.extend(zoom::specs());
v.extend(compress::specs());
v
})
}
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
pub(crate) fn param_keys(doc: &str) -> std::result::Result<Vec<&str>, String> {
let mut keys = vec![];
for p in parse_params(doc)? {
if !keys.contains(&p.name) {
keys.push(p.name);
}
}
Ok(keys)
}
#[derive(Debug, PartialEq)]
pub struct Param<'a> {
pub name: &'a str,
pub optional: bool,
/// What the doc says of it: its values, unit or remark (`rect|roundRect|…`, `[x,y,w,h] pt`).
pub about: &'a str,
/// An alternative to the parameter before it in the same object (`color? | none?`).
pub or: bool,
/// Which of the doc's alternative objects it belongs to: `{index} | {id}` puts id in object 1.
pub object: usize,
}
/// The top-level parameters of a params doc: `{preset, rect?: [x,y,w,h] pt} | {id}` gives preset,
/// rect (optional, `[x,y,w,h] pt`) and id (in the second object). Text after `→` is the result
/// and is skipped. Errs where the doc strays from that grammar.
pub fn parse_params(doc: &str) -> std::result::Result<Vec<Param<'_>>, String> {
let doc = doc.split('→').next().unwrap_or_default();
let mut params: Vec<Param> = vec![];
let mut open: Vec<char> = vec![];
let mut expect_key = false;
let mut or = false;
let mut objects: usize = 0;
let mut about_from: Option<usize> = None;
let mut chars = doc.char_indices().peekable();
let mut prev = ' ';
fn end_about<'a>(doc: &'a str, params: &mut [Param<'a>], from: &mut Option<usize>, to: usize) {
if let (Some(f), Some(p)) = (from.take(), params.last_mut()) {
p.about = doc.get(f..to).unwrap_or_default().trim();
}
}
while let Some((i, c)) = chars.next() {
let in_object = open == ['{'];
match c {
'{' | '[' | '(' => {
open.push(c);
if open == ['{'] {
expect_key = true;
objects += 1;
or = false;
}
}
'}' | ']' | ')' => {
if in_object {
end_about(doc, &mut params, &mut about_from, i);
}
open.pop();
}
',' if in_object => {
end_about(doc, &mut params, &mut about_from, i);
expect_key = true;
}
'|' if in_object && prev == ' ' && chars.peek().is_some_and(|(_, n)| *n == ' ') => {
end_about(doc, &mut params, &mut about_from, i);
expect_key = true;
or = true;
}
c if in_object && expect_key && (c.is_ascii_alphabetic() || c == '_') => {
let mut end = i + c.len_utf8();
while let Some((j, n)) = chars.peek().copied().filter(|(_, n)| n.is_ascii_alphanumeric() || *n == '_') {
end = j + n.len_utf8();
chars.next();
}
let after = doc.get(end..).unwrap_or_default();
let rest = after.trim_start_matches('?').trim_start();
let at = doc.len() - rest.len();
about_from = match rest.chars().next() {
Some(':') => Some(at + 1),
Some('(') => Some(at),
Some(',' | '}' | '|') => None,
_ => return Err(format!("`{}` is followed by `{}`", &doc[i..end], rest.chars().take(12).collect::<String>())),
};
params.push(Param { name: &doc[i..end], optional: after.starts_with('?'), about: "", or, object: objects.saturating_sub(1) });
or = false;
expect_key = false;
}
c if in_object && expect_key && !c.is_whitespace() => return Err(format!("expected a key at `{}`", &doc[i..])),
_ => {}
}
prev = c;
}
Ok(params)
}
// ---------- param helpers ----------
/// The deck has used every object id (a hostile file can arrive that way): it cannot grow, and
/// growing would duplicate ids (#407).
pub(crate) const NO_ID_SPACE: &str = "the presentation has used every object id and can hold no more";
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
pub(crate) fn f64_param(p: &Value, key: &str) -> Option<f64> {
p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite())
}
pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
f64_param(p, key).unwrap_or(default)
}
pub(crate) fn bool_param(p: &Value, key: &str) -> Option<bool> {
p.get(key).and_then(Value::as_bool)
}
pub(crate) fn bool_or(p: &Value, key: &str, default: bool) -> bool {
bool_param(p, key).unwrap_or(default)
}
pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> {
p.get(key).and_then(Value::as_str)
}
pub(crate) fn usize_param(p: &Value, key: &str) -> Option<usize> {
p.get(key).and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok())
}
/// An index param: `Ok(None)` when absent (callers may fall back to the selection), `Err` when
/// present but not a valid index (negative, non-integer), so a bad index never acts on the selection.
pub(crate) fn opt_usize_param(p: &Value, key: &str, cmd: &str) -> Result<Option<usize>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().and_then(|v| usize::try_from(v).ok()).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` is not a valid index: {v}"))),
}
}
/// A shape id param: `Ok(None)` when absent (callers may fall back to the selection), `Err` when
/// present but not a valid id (negative, non-integer, beyond `u32`), so a bad id never edits the selection.
pub(crate) fn id_param(p: &Value, key: &str, cmd: &str) -> Result<Option<ShapeId>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_u64()
.and_then(|v| u32::try_from(v).ok())
.map(|v| Some(ShapeId(v)))
.ok_or_else(|| bad(cmd, format!("`{key}` is not a valid shape id: {v}"))),
}
}
pub(crate) fn ids_param(p: &Value, key: &str) -> Option<Vec<ShapeId>> {
p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).filter_map(|v| u32::try_from(v).ok()).map(ShapeId).collect())
}
/// `[x, y, w, h]` in points.
pub(crate) fn rect_param(p: &Value, key: &str) -> Option<Xfrm> {
let a = p.get(key)?.as_array()?;
let f = |i: usize| a.get(i).and_then(Value::as_f64).filter(|v| v.is_finite());
Some(Xfrm::new(f(0)?, f(1)?, f(2)?.abs(), f(3)?.abs()))
}
pub(crate) fn with_param(p: &Value, key: &str, v: Value) -> Value {
let mut m = p.as_object().cloned().unwrap_or_default();
m.insert(key.to_string(), v);
Value::Object(m)
}
/// Targets: `ids` / `id` params, else the selection.
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<ShapeId>> {
if let Some(a) = p.get("ids").and_then(Value::as_array)
&& let Some(v) = a.iter().find(|v| v.as_u64().and_then(|v| u32::try_from(v).ok()).is_none())
{
return Err(bad("shape", format!("`ids` has an invalid shape id: {v}")));
}
if let Some(ids) = ids_param(p, "ids")
&& !ids.is_empty()
{
return Ok(ids);
}
if let Some(id) = id_param(p, "id", "shape")? {
return Ok(vec![id]);
}
Ok(s.doc()?.selection.shapes.clone())
}
pub(crate) fn ok() -> Result<Value> {
Ok(Value::Null)
}
/// Parse a colour param: `"#RRGGBB"`, `"accent1"`…, or `{"scheme":"accent2","lumMod":75000}`.
/// A preset or system colour keeps its base: `{"preset":"red"}`,
/// `{"system":"windowText","last":"#000000"}`.
pub(crate) fn color_param(p: &Value, key: &str) -> Option<deckcraft_model::ColorRef> {
let v = p.get(key)?;
color_value(v)
}
pub(crate) fn color_value(v: &Value) -> Option<deckcraft_model::ColorRef> {
use deckcraft_model::ColorRef;
match v {
Value::String(s) => {
if let Some(slot) = deckcraft_color::SchemeSlot::from_xml(s) {
return Some(ColorRef::scheme(slot));
}
if let Some(c) = deckcraft_color::Rgba::from_hex(s) {
return Some(ColorRef::rgb(c));
}
deckcraft_color::preset(s).map(ColorRef::rgb)
}
Value::Object(o) => {
let mut c = if let Some(s) = o.get("scheme").and_then(Value::as_str) {
ColorRef::scheme(deckcraft_color::SchemeSlot::from_xml(s)?)
} else if let Some(name) = o.get("preset").and_then(Value::as_str) {
if !deckcraft_color::is_preset_name(name) {
return None;
}
ColorRef { base: deckcraft_model::ColorBase::Preset { name: name.to_string() }, mods: vec![] }
} else if let Some(name) = o.get("system").and_then(Value::as_str) {
if !deckcraft_color::is_system_name(name) {
return None;
}
let last = deckcraft_color::Rgba::from_hex(o.get("last").and_then(Value::as_str)?)?;
ColorRef { base: deckcraft_model::ColorBase::System { name: name.to_string(), last }, mods: vec![] }
} else {
ColorRef::rgb(deckcraft_color::Rgba::from_hex(o.get("rgb").and_then(Value::as_str)?)?)
};
for (k, val) in o {
if let Some(t) = deckcraft_color::ColorTransform::from_xml(k, val.as_i64().and_then(|x| i32::try_from(x).ok())) {
c.mods.push(t);
}
}
Some(c)
}
_ => None,
}
}
/// Look a shape up by id in the edited tree.
pub(crate) fn shape_of(s: &Session, id: ShapeId) -> Result<deckcraft_model::Shape> {
s.doc()?.shape(id).cloned().ok_or_else(|| EngineError::Other(format!("no shape {id}")))
}
/// Effective box of a shape (placeholders inherit theirs). A table's box is at least as tall as its
/// rows are drawn (rows grow to fit their text), so handles and hit tests match what is shown.
pub fn xfrm_of(doc: &deckcraft_model::Presentation, sel: &crate::Selection, shape: &deckcraft_model::Shape) -> Xfrm {
let mut x = shape.xfrm.unwrap_or_else(|| ctx_xfrm(doc, sel, shape));
if let deckcraft_model::ShapeKind::Table(t) = &shape.kind {
let drawn: f64 = table_drawn_heights(doc, sel, t).iter().sum();
if drawn.is_finite() && drawn > x.h {
x.h = drawn;
}
}
x
}
/// Row heights of table `t` as drawn: a stored height is a minimum, rows grow to fit their text.
pub fn table_drawn_heights(doc: &deckcraft_model::Presentation, sel: &crate::Selection, t: &deckcraft_model::Table) -> Vec<f64> {
match text::ctx_for(doc, sel) {
Some(ctx) => deckcraft_render::table_row_heights(&ctx, t, &deckcraft_text::NoFields),
None => t.rows.iter().map(|r| r.height).collect(),
}
}
fn ctx_xfrm(doc: &deckcraft_model::Presentation, sel: &crate::Selection, shape: &deckcraft_model::Shape) -> Xfrm {
use deckcraft_model::resolve::{self, Ctx};
match sel.target {
crate::Target::Slides => doc.slides.get(sel.slide).and_then(|s| Ctx::for_slide(doc, s)).map(|c| resolve::xfrm(&c, shape)),
crate::Target::Master { master } => doc.masters.get(master).map(|m| resolve::xfrm(&Ctx::for_master(doc, m), shape)),
t @ (crate::Target::Handout | crate::Target::NotesMaster) => {
crate::page_master(doc, t).map(|m| resolve::xfrm(&Ctx::for_master(doc, m), shape))
}
crate::Target::Layout { master, layout } => {
doc.masters.get(master).and_then(|m| m.layouts.get(layout).map(|l| resolve::xfrm(&Ctx::for_layout(doc, m, l), shape)))
}
}
.unwrap_or_default()
}
/// Run `f` on each target shape (copy-on-write), materialising inherited boxes first.
pub(crate) fn edit_shapes(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut deckcraft_model::Shape) -> Result<()>) -> Result<Value> {
let mut ids = targets(s, p)?;
if ids.is_empty() {
return Err(bad(cmd, "no shapes selected"));
}
// A shape named twice is edited once.
let mut seen = std::collections::HashSet::new();
ids.retain(|id| seen.insert(*id));
s.edit(|doc, sel| {
// The boxes are read from the shapes in place: no copy of a shape (and its text) per id.
let boxes: std::collections::HashMap<ShapeId, Xfrm> = ids
.iter()
.filter_map(|id| current_shapes(doc, sel).and_then(|v| deckcraft_model::find_shape(v, *id)))
.map(|sh| (sh.id, xfrm_of(doc, sel, sh)))
.collect();
let shapes = crate::shapes_mut(doc, sel).ok_or_else(|| bad(cmd, "no slide"))?;
let mut n = 0;
for id in &ids {
if let Some(sh) = deckcraft_model::find_shape_mut(shapes, *id) {
if sh.xfrm.is_none() {
sh.xfrm = boxes.get(id).copied();
}
f(sh)?;
n += 1;
}
}
if n == 0 {
return Err(bad(cmd, "no such shape"));
}
Ok(Value::from(n))
})
}
/// [`edit_shapes`] for edits a locked object refuses (move, size, rotate, flip, reshape, crop):
/// locked targets are left out, and when every target is locked nothing changes.
pub(crate) fn edit_geometry(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut deckcraft_model::Shape) -> Result<()>) -> Result<Value> {
let ids = targets(s, p)?;
let st = s.doc()?;
let free: Vec<u32> = ids.iter().filter(|id| !st.shape(**id).is_some_and(|x| x.locked)).map(|id| id.0).collect();
if !ids.is_empty() && free.is_empty() {
return Err(bad(cmd, "the object is locked"));
}
edit_shapes(s, &with_param(p, "ids", Value::from(free)), cmd, f)
}
pub(crate) fn current_shapes<'a>(doc: &'a deckcraft_model::Presentation, sel: &crate::Selection) -> Option<&'a Vec<deckcraft_model::Shape>> {
match sel.target {
crate::Target::Slides => doc.slides.get(sel.slide).map(|s| &s.shapes),
crate::Target::Master { master } => doc.masters.get(master).map(|m| &m.shapes),
t @ (crate::Target::Handout | crate::Target::NotesMaster) => crate::page_master(doc, t).map(|m| &m.shapes),
crate::Target::Layout { master, layout } => doc.masters.get(master).and_then(|m| m.layouts.get(layout)).map(|l| &l.shapes),
}
}
/// Every name on the slide, group members included, and the number of shapes (which exceeds the
/// number of names when two shapes share one).
pub(crate) fn current_names(doc: &deckcraft_model::Presentation, sel: &crate::Selection) -> (std::collections::HashSet<String>, usize) {
let mut names = std::collections::HashSet::new();
let mut count = 0;
if let Some(v) = current_shapes(doc, sel) {
deckcraft_model::walk(v, &mut |sh, _| {
names.insert(sh.name.clone());
count += 1;
});
}
(names, count)
}
/// The command palette runs a command with `{}`. True when the params doc names a value that
/// call would have to supply (`path`, `rows`, `path? | data`), so the palette must not offer it.
/// A name ending in `?` is optional. Text after `→` is the result, not an input.
pub fn needs_arguments(params: &str) -> bool {
let input = params.split('→').next().unwrap_or(params);
let Some(start) = input.find('{') else { return false };
let inside = input.get(start + 1..).unwrap_or("");
let inside = inside.split('}').next().unwrap_or(inside);
split_fields(inside).iter().any(|f| field_requires(f.trim()))
}
fn split_fields(s: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut start = 0;
let mut depth = 0i32;
let mut quote = false;
for (i, c) in s.char_indices() {
if quote {
if c == '"' {
quote = false;
}
continue;
}
match c {
'"' => quote = true,
'[' | '(' => depth += 1,
']' | ')' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
out.push(s.get(start..i).unwrap_or(""));
start = i + c.len_utf8();
}
_ => {}
}
}
out.push(s.get(start..).unwrap_or(""));
out
}
/// A field needs a value unless every alternative (`path? | data`) is an optional parameter.
fn field_requires(field: &str) -> bool {
if field.is_empty() {
return false;
}
let alts: Vec<&str> = if field.contains(" | ") { field.split(" | ").map(str::trim).filter(|s| !s.is_empty()).collect() } else { vec![field] };
let mut saw = false;
let mut all_optional = true;
for alt in alts {
let Some(optional) = param_optional(alt) else { continue };
saw = true;
all_optional &= optional;
}
saw && !all_optional
}
/// `Some(true)` when `alt` starts with an optional parameter name, `Some(false)` when required.
fn param_optional(alt: &str) -> Option<bool> {
let alt = alt.trim();
let name_end = alt.find(|c: char| !c.is_ascii_alphanumeric()).unwrap_or(alt.len());
let name = alt.get(..name_end).unwrap_or("");
if name.is_empty() || !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
return None;
}
let rest = alt.get(name_end..).unwrap_or("").trim_start();
if rest.starts_with('?') {
Some(true)
} else if rest.is_empty() || rest.starts_with(':') {
Some(false)
} else {
None
}
}
/// Base64 (standard alphabet) for binary payloads in JSON params and results.
pub fn base64_encode(data: &[u8]) -> String {
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
for (i, shift) in [18, 12, 6, 0].iter().enumerate() {
if i <= chunk.len() {
out.push(A.get(((n >> shift) & 63) as usize).copied().unwrap_or(b'A') as char);
} else {
out.push('=');
}
}
}
out
}
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
let s = s.split_once("base64,").map(|(_, b)| b).unwrap_or(s);
let mut out = Vec::with_capacity(s.len() / 4 * 3);
let mut acc = 0u32;
let mut bits = 0;
for c in s.bytes() {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' | b'-' => 62,
b'/' | b'_' => 63,
b'=' | b'\n' | b'\r' | b' ' => continue,
_ => return None,
} as u32;
acc = (acc << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push(((acc >> bits) & 0xff) as u8);
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_palette_skips_a_command_that_needs_a_value() {
assert!(needs_arguments("{path}"));
assert!(needs_arguments("{path, format: png|jpeg|pptx, slide?: index}"));
assert!(needs_arguments("{path? | data: base64, name?, rect?}"));
assert!(needs_arguments("{rows, cols, rect?}"));
assert!(needs_arguments("{axis: horizontal|vertical, ids?}"));
assert!(needs_arguments("{percent}"));
assert!(!needs_arguments("{}"));
assert!(!needs_arguments("{on?: bool}"));
assert!(!needs_arguments("{theme?: name, size?: [w,h] pt, blank?: bool}"));
assert!(!needs_arguments("{uid?: one entry, else all}"));
assert!(!needs_arguments("{locked?: bool (default: toggle), ids?}"));
assert!(!needs_arguments("{} → [{name, label, category}]"));
assert!(!needs_arguments("{title?, subject?} → properties"));
assert!(!needs_arguments("{slides?: [index] | \"1-3,5\", includeHidden?}"));
let export = command_specs().iter().find(|c| c.id == "file.export").expect("export");
let save = command_specs().iter().find(|c| c.id == "file.save").expect("save");
let audio = command_specs().iter().find(|c| c.id == "insert.audio").expect("audio");
assert!(needs_arguments(export.params));
assert!(!needs_arguments(save.params));
assert!(needs_arguments(audio.params));
}
#[test]
fn preset_and_system_colors_keep_their_base() {
use deckcraft_color::{ColorTransform, Rgba};
use deckcraft_model::{ColorBase, ColorRef};
use serde_json::json;
let preset = color_value(&json!({"preset": "red", "lumMod": 50_000}));
assert_eq!(preset, Some(ColorRef { base: ColorBase::Preset { name: "red".into() }, mods: vec![ColorTransform::LumMod(50_000)] }));
let system = color_value(&json!({"system": "windowText", "last": "#123456"}));
assert_eq!(system, Some(ColorRef { base: ColorBase::System { name: "windowText".into(), last: Rgba::rgb(0x12, 0x34, 0x56) }, mods: vec![] }));
assert_eq!(color_value(&json!({"system": "windowText"})), None, "a system color needs its last value");
assert_eq!(color_value(&json!({"preset": "notAColor"})), None);
assert_eq!(color_value(&json!({"system": "notAColor", "last": "#000000"})), None);
for name in ["aliceBlue", "darkBlue", "ltSlateGrey"] {
assert!(color_value(&json!({"preset": name})).is_some(), "{name}");
}
assert!(color_value(&json!({"system": "3dDkShadow", "last": "#000000"})).is_some());
}
}
+20 -355
View File
@@ -5,9 +5,7 @@ use std::sync::Arc;
use deckcraft_model::anim::{ANIMATIONS, AnimClass, AnimStart, Animation, TextBuild, animation_info};
use serde_json::{Value, json};
use super::{
CommandSpec, always, bad, bool_or, bool_param, cmd, has_selection, has_slide, id_param, ok, opt_usize_param, str_param, targets, usize_param,
};
use super::*;
use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
@@ -17,7 +15,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Animation Styles",
["Animations", "Animation"],
None,
"{effect: fade|fly|zoom|wipe|appear|spin|pulse|fadeOut|lines|… (animation.list), class?: entrance|emphasis|exit|path, option?, path?: [[x,y],…] or OOXML string, closed?: bool, ids?} — replaces the shapes' animations. path (motion paths): points in slide points, as offsets from where the shape sits, or the OOXML path string (slide fractions) animation.get answers",
"{effect: fade|fly|zoom|wipe|appear|spin|pulse|fadeOut|lines|… (animation.list), class?: entrance|emphasis|exit|path, option?, ids?} — replaces the shapes' animations",
has_selection,
set
),
@@ -26,11 +24,11 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Animation",
["Animations", "Advanced Animation"],
None,
"{effect, class?, option?, path?: [[x,y],…] or OOXML string, closed?: bool, start?: onClick|withPrevious|afterPrevious, duration?: ms, delay?: ms, ids?} → {count, path?}",
"{effect, class?, option?, start?: onClick|withPrevious|afterPrevious, duration?: ms, delay?: ms, ids?}",
has_selection,
add
),
cmd!("animation.remove", "Remove Animation", ["Animation Pane"], None, "{index} | {ids? (all of the shapes' animations)}", has_slide, remove),
cmd!("animation.remove", "Remove Animation", ["Animation Pane"], None, "{index} | {ids?} (all of the shapes' animations)", has_slide, remove),
cmd!("animation.move", "Reorder Animation", ["Animations", "Timing"], None, "{index, to}", has_slide, move_anim),
cmd!(
"animation.timing",
@@ -46,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Effect Options",
["Animations", "Animation"],
None,
"{option?, textBuild?: asOne|byParagraph|byWord|byLetter, path?: [[x,y],…] or OOXML string, closed?: bool, index?}",
"{option?, textBuild?: asOne|byParagraph|byWord|byLetter, index?}",
has_slide,
options
),
@@ -84,52 +82,7 @@ fn start_of(s: &str) -> AnimStart {
}
}
/// The effect option `given` as one of `allowed`. Besides the stored codes ("b", "lt", "u", …)
/// it takes the direction words people type: "fromBottom", "bottom", "fromTopLeft",
/// "upRight". `None` when it matches none of them: the renderer reads direction codes letter
/// by letter, so an unchecked "fromBottom" would fly in from the right and the bottom.
fn resolve_option(allowed: &[&str], given: &str) -> Option<String> {
if allowed.is_empty() || allowed.contains(&given) {
return Some(given.to_string());
}
let low = given.to_ascii_lowercase();
if let Some(o) = allowed.iter().find(|o| o.to_ascii_lowercase() == low) {
return Some(o.to_string());
}
let mut rest = low.strip_prefix("from").unwrap_or(&low).trim_start_matches(['-', '_', ' ']);
// Direction words in order, each as both its edge letter and its arrow letter.
let mut dirs: Vec<(char, char)> = Vec::new();
while !rest.is_empty() {
let words: [(&str, (char, char)); 8] = [
("bottom", ('b', 'd')),
("down", ('b', 'd')),
("top", ('t', 'u')),
("up", ('t', 'u')),
("left", ('l', 'l')),
("right", ('r', 'r')),
("-", ('-', '-')),
("_", ('-', '-')),
];
let (w, d) = words.iter().find(|(w, _)| rest.starts_with(w))?;
if d.0 != '-' {
dirs.push(*d);
}
rest = &rest[w.len()..];
}
if dirs.is_empty() || dirs.len() > 2 {
return None;
}
let mut cands: Vec<String> = Vec::new();
for pick in [|d: &(char, char)| d.0, |d: &(char, char)| d.1] {
let code: String = dirs.iter().map(pick).collect();
let rev: String = code.chars().rev().collect();
cands.push(code);
cands.push(rev);
}
cands.into_iter().find(|c| allowed.contains(&c.as_str()))
}
fn build(p: &Value, slide: (f64, f64)) -> Result<Animation> {
fn build(p: &Value) -> Result<Animation> {
let effect = str_param(p, "effect").ok_or_else(|| bad("animation", "missing `effect`"))?;
let class = class_of(str_param(p, "class"));
let info = match class {
@@ -140,12 +93,7 @@ fn build(p: &Value, slide: (f64, f64)) -> Result<Animation> {
let mut a = Animation {
class: info.2,
effect: info.0.to_string(),
option: match str_param(p, "option") {
Some(o) => {
resolve_option(info.5, o).ok_or_else(|| bad("animation", format!("option `{o}` is not one of {:?} for `{}`", info.5, info.0)))?
}
None => info.5.first().map(|o| o.to_string()).unwrap_or_default(),
},
option: str_param(p, "option").map(String::from).or_else(|| info.5.first().map(|o| o.to_string())).unwrap_or_default(),
duration_ms: p.get("duration").and_then(Value::as_u64).map(|v| v.min(600_000) as u32).unwrap_or(info.4),
delay_ms: p.get("delay").and_then(Value::as_u64).map(|v| v.min(600_000) as u32).unwrap_or(0),
preset_id: Some(info.3),
@@ -155,9 +103,7 @@ fn build(p: &Value, slide: (f64, f64)) -> Result<Animation> {
a.start = start_of(st);
}
if a.class == AnimClass::Path {
a.path = Some(path_param(p, slide)?.unwrap_or_else(|| default_path(&a.effect, &a.option)));
} else if p.get("path").is_some() {
return Err(bad("animation", "`path` only fits a motion path (class `path`)"));
a.path = Some(default_path(&a.effect, &a.option));
}
if a.effect == "spin" {
a.amount = Some(360.0);
@@ -168,97 +114,6 @@ fn build(p: &Value, slide: (f64, f64)) -> Result<Animation> {
Ok(a)
}
/// Most points of a motion path given as an array, and longest path string given as text.
const MAX_PATH_POINTS: usize = 1_000;
const MAX_PATH_TEXT: usize = 16 * 1024;
/// Largest offset of a point, in slide points; anything beyond is not a place on any slide.
const MAX_PATH_OFFSET: f64 = 1.0e6;
/// A number of a path string: slide fractions, rounded to 6 places.
fn path_num(v: f64) -> String {
let t = format!("{:.6}", v);
let t = t.trim_end_matches('0').trim_end_matches('.');
if t == "-0" || t.is_empty() { "0".into() } else { t.into() }
}
/// Does a raw motion path string draw: only commands and numbers, every number finite, and at
/// least two points? (A lone `e`, or `1e999`, would play as an empty or partial path.)
fn raw_path_draws(text: &str) -> bool {
let cs: Vec<char> = text.chars().collect();
let (mut i, mut nums) = (0, 0usize);
while let Some(&c) = cs.get(i) {
if c.is_ascii_digit() || c == '.' || ((c == '-' || c == '+') && cs.get(i + 1).is_some_and(|d| d.is_ascii_digit() || *d == '.')) {
let start = i;
i += 1;
while cs.get(i).is_some_and(|d| d.is_ascii_digit() || *d == '.') {
i += 1;
}
if cs.get(i).is_some_and(|d| *d == 'e' || *d == 'E') {
let n1 = cs.get(i + 1).copied().unwrap_or(' ');
let n2 = cs.get(i + 2).copied().unwrap_or(' ');
if n1.is_ascii_digit() || ((n1 == '-' || n1 == '+') && n2.is_ascii_digit()) {
i += 2;
while cs.get(i).is_some_and(char::is_ascii_digit) {
i += 1;
}
}
}
let tok: String = cs.get(start..i).map(|t| t.iter().collect()).unwrap_or_default();
match tok.parse::<f64>() {
Ok(v) if v.is_finite() => nums += 1,
_ => return false,
}
} else if " ,MmLlCcQqHhVvZzE".contains(c) {
i += 1;
} else {
return false;
}
}
nums >= 4
}
/// The motion path `path` asks for, as the OOXML path string animations store: either points
/// (`[[x, y], …]`, slide points as offsets from where the shape sits, joined by lines, `closed?`
/// to return to the first) or that string itself.
fn path_param(p: &Value, slide: (f64, f64)) -> Result<Option<String>> {
let Some(v) = p.get("path") else { return Ok(None) };
let refuse = |why: &str| bad("animation", format!("`path` {why}"));
match v {
Value::String(text) => {
let ok = text.len() <= MAX_PATH_TEXT
&& text.contains(|c: char| c.is_ascii_digit())
&& text.chars().all(|c| c.is_ascii_digit() || " .+-eE,MmLlCcQqHhVvZz".contains(c))
&& raw_path_draws(text);
if !ok {
return Err(refuse("string must be an OOXML motion path such as `M 0 0 L 0.25 0 E` (at most 16 KiB)"));
}
Ok(Some(text.clone()))
}
Value::Array(points) => {
if !(2..=MAX_PATH_POINTS).contains(&points.len()) {
return Err(refuse(&format!("needs 2 to {MAX_PATH_POINTS} points")));
}
if !(slide.0.is_finite() && slide.1.is_finite() && slide.0 > 0.0 && slide.1 > 0.0) {
return Err(refuse("can't be placed: the slide has no size"));
}
let mut out = String::new();
for (k, pt) in points.iter().enumerate() {
let xy = pt.as_array().filter(|a| a.len() == 2).and_then(|a| Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?)));
let Some((x, y)) = xy.filter(|(x, y)| x.abs() <= MAX_PATH_OFFSET && y.abs() <= MAX_PATH_OFFSET) else {
return Err(refuse(&format!("point {k} must be [x, y], two finite numbers within ±{MAX_PATH_OFFSET} points")));
};
out.push_str(&format!("{} {} {} ", if k == 0 { "M" } else { "L" }, path_num(x / slide.0), path_num(y / slide.1)));
}
if p.get("closed").and_then(Value::as_bool) == Some(true) {
out.push_str("Z ");
}
out.push('E');
Ok(Some(out))
}
_ => Err(refuse("must be [[x, y], …] or an OOXML path string")),
}
}
/// Default motion paths, in slide-fraction units relative to the shape's position.
pub fn default_path(effect: &str, option: &str) -> String {
let (dx, dy) = match option {
@@ -272,13 +127,13 @@ pub fn default_path(effect: &str, option: &str) -> String {
"turns" => format!("M 0 0 L {} {} C {} {} {dx} {} {dx} {dy} E", dx * 0.5, dy * 0.5, dx, dy * 0.5, dy * 0.75),
"shapes" => "M 0 0 C 0.1 0 0.1 0.15 0 0.15 C -0.1 0.15 -0.1 0 0 0 Z E".into(),
"loops" => "M 0 0 C 0.1 -0.1 0.2 0.1 0.1 0.1 C 0 0.1 0.1 -0.1 0.25 0 E".into(),
other => deckcraft_model::anim::preset_path(other).unwrap_or_else(|| format!("M 0 0 L {dx} {dy} E")),
_ => format!("M 0 0 L {dx} {dy} E"),
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let ids = targets(s, p)?;
let a = build(p, slide_extent(s)?)?;
let a = build(p)?;
s.edit(|doc, sel| {
let sl = doc.slides.get_mut(sel.slide).ok_or_else(|| bad("animation.set", "no slide"))?;
let sl = Arc::make_mut(sl);
@@ -308,16 +163,9 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// The slide's width and height in points.
fn slide_extent(s: &mut Session) -> Result<(f64, f64)> {
let size = &s.doc()?.doc.slide_size;
Ok((size.width, size.height))
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let ids = targets(s, p)?;
let a = build(p, slide_extent(s)?)?;
let path = a.path.clone();
let a = build(p)?;
s.edit(|doc, sel| {
let sl = Arc::make_mut(doc.slides.get_mut(sel.slide).ok_or_else(|| bad("animation.add", "no slide"))?);
for (k, id) in ids.iter().enumerate() {
@@ -327,15 +175,12 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
sl.animations.push(x);
}
Ok(match &path {
Some(path) => json!({"count": sl.animations.len(), "path": path}),
None => json!({"count": sl.animations.len()}),
})
Ok(json!({"count": sl.animations.len()}))
})
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let index = opt_usize_param(p, "index", "animation.remove")?;
let index = usize_param(p, "index");
let ids = if index.is_none() { targets(s, p)? } else { vec![] };
s.edit(|doc, sel| {
let sl = Arc::make_mut(doc.slides.get_mut(sel.slide).ok_or_else(|| bad("animation.remove", "no slide"))?);
@@ -352,7 +197,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
}
fn move_anim(s: &mut Session, p: &Value) -> Result<Value> {
let i = opt_usize_param(p, "index", "animation.move")?.ok_or_else(|| bad("animation.move", "missing `index`"))?;
let i = usize_param(p, "index").ok_or_else(|| bad("animation.move", "missing `index`"))?;
let to = usize_param(p, "to").ok_or_else(|| bad("animation.move", "missing `to`"))?;
s.edit(|doc, sel| {
let sl = Arc::make_mut(doc.slides.get_mut(sel.slide).ok_or_else(|| bad("animation.move", "no slide"))?);
@@ -368,7 +213,7 @@ fn move_anim(s: &mut Session, p: &Value) -> Result<Value> {
}
fn each_target(s: &mut Session, p: &Value, f: impl Fn(&mut Animation)) -> Result<Value> {
let index = opt_usize_param(p, "index", "animation")?;
let index = usize_param(p, "index");
let ids = if index.is_none() { targets(s, p)? } else { vec![] };
s.edit(|doc, sel| {
let sl = Arc::make_mut(doc.slides.get_mut(sel.slide).ok_or_else(|| bad("animation", "no slide"))?);
@@ -423,20 +268,11 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
"byLetter" => TextBuild::ByLetter,
_ => TextBuild::AsOne,
});
let path = path_param(p, slide_extent(s)?)?;
each_target(s, p, |a| {
if let (Some(path), AnimClass::Path) = (&path, a.class) {
a.path = Some(path.clone());
}
if let Some(o) = &option {
// Each target takes the option in its own effect's terms; one it has no such
// option for keeps its own.
let allowed = animation_info(&a.effect, a.class).map(|i| i.5).unwrap_or(&[]);
if let Some(o) = resolve_option(allowed, o) {
if a.class == AnimClass::Path && path.is_none() {
a.path = Some(default_path(&a.effect, &o));
}
a.option = o;
a.option = o.clone();
if a.class == AnimClass::Path {
a.path = Some(default_path(&a.effect, o));
}
}
if let Some(b) = build_mode {
@@ -446,10 +282,7 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let i = match opt_usize_param(p, "index", "animation.clear")? {
Some(i) => i,
None => s.doc()?.selection.slide,
};
let i = usize_param(p, "index").unwrap_or(s.doc()?.selection.slide);
s.edit(|doc, _| {
if let Some(sl) = doc.slides.get_mut(i) {
Arc::make_mut(sl).animations.clear();
@@ -472,7 +305,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
fn painter_pick(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let id = id_param(p, "id", "animation.painter")?
let id = id_param(p, "id")
.or_else(|| st.selection.shapes.first().copied())
.ok_or_else(|| bad("animation.painter", "select an animated shape first"))?;
let sl = st.current_slide().ok_or_else(|| bad("animation.painter", "no slide"))?;
@@ -522,41 +355,8 @@ fn painter_apply(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use super::resolve_option;
#[test]
fn direction_words_resolve_to_codes() {
let fly = &["b", "lb", "l", "lt", "t", "rt", "r", "rb"][..];
assert_eq!(resolve_option(fly, "fromBottom").as_deref(), Some("b"));
assert_eq!(resolve_option(fly, "bottom").as_deref(), Some("b"));
assert_eq!(resolve_option(fly, "fromTopLeft").as_deref(), Some("lt"));
assert_eq!(resolve_option(fly, "fromBottomRight").as_deref(), Some("rb"));
assert_eq!(resolve_option(fly, "lt").as_deref(), Some("lt"));
assert_eq!(resolve_option(fly, "sideways"), None);
assert_eq!(resolve_option(fly, "fromBottomTopLeft"), None);
let wipe = &["r", "l", "u", "d", "ru", "lu", "rd", "ld"][..];
assert_eq!(resolve_option(wipe, "fromBottom").as_deref(), Some("d"));
assert_eq!(resolve_option(wipe, "upRight").as_deref(), Some("ru"));
let split = &["horzIn", "horzOut", "vertIn", "vertOut"][..];
assert_eq!(resolve_option(split, "HorzIn").as_deref(), Some("horzIn"));
assert_eq!(resolve_option(&[], "anything").as_deref(), Some("anything"));
}
use super::*;
#[test]
fn clear_rejects_invalid_index() {
let mut s = Session::with_new();
let r = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10.0, 10.0, 100.0, 100.0]})).unwrap();
let id = r.get("id").unwrap().as_u64().unwrap();
s.execute("animation.add", &json!({"effect": "fade", "class": "entrance", "ids": [id]})).unwrap();
for bad_index in [json!(-1), json!(1.5)] {
assert!(s.execute("animation.clear", &json!({"index": bad_index})).is_err());
let left = s.execute("animation.get", &json!({})).unwrap();
assert_eq!(left.as_array().unwrap().len(), 1);
}
}
#[test]
fn animation_painter_copies_effects_between_shapes() {
let mut s = Session::with_new();
@@ -650,139 +450,4 @@ mod tests {
s.execute("animation.painterApply", &json!({"ids": [id3]})).unwrap();
assert!(s.anim_painter.is_some());
}
fn setup_triggers() -> (Session, [u64; 4]) {
let mut s = Session::with_new();
let mut ids = [0u64; 4];
for (slot, x) in ids.iter_mut().zip([10.0, 150.0, 300.0, 450.0]) {
let r = s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, 10.0, 100.0, 100.0]})).unwrap();
*slot = r.get("id").unwrap().as_u64().unwrap();
}
(s, ids)
}
fn triggers(s: &Session) -> Vec<Option<deckcraft_model::ShapeId>> {
s.doc().unwrap().current_slide().unwrap().animations.iter().map(|x| x.trigger).collect()
}
#[test]
fn deleting_a_trigger_shape_clears_the_trigger() {
let (mut s, [a, b, c, d]) = setup_triggers();
let id = |v: u64| Some(deckcraft_model::ShapeId(v as u32));
s.execute("animation.add", &json!({"effect": "fade", "ids": [a]})).unwrap();
s.execute("animation.add", &json!({"effect": "fade", "ids": [d]})).unwrap();
s.execute("animation.timing", &json!({"index": 0, "trigger": b})).unwrap();
s.execute("animation.timing", &json!({"index": 1, "trigger": c})).unwrap();
assert_eq!(triggers(&s), vec![id(b), id(c)]);
s.execute("edit.delete", &json!({"ids": [b]})).unwrap();
assert_eq!(triggers(&s), vec![None, id(c)], "only the deleted trigger is cleared");
assert_eq!(s.doc().unwrap().current_slide().unwrap().animations.len(), 2, "the animated shapes keep their effects");
}
#[test]
fn deleting_a_group_clears_triggers_of_its_children() {
let (mut s, [a, b, c, _]) = setup_triggers();
let g = s.execute("arrange.group", &json!({"ids": [b, c]})).unwrap().get("id").unwrap().as_u64().unwrap();
s.execute("animation.add", &json!({"effect": "fade", "ids": [a]})).unwrap();
s.execute("animation.timing", &json!({"index": 0, "trigger": b})).unwrap();
assert_eq!(triggers(&s), vec![Some(deckcraft_model::ShapeId(b as u32))]);
s.execute("edit.delete", &json!({"ids": [g]})).unwrap();
assert_eq!(triggers(&s), vec![None], "the trigger was inside the deleted group");
assert_eq!(s.doc().unwrap().current_slide().unwrap().animations.len(), 1);
}
#[test]
fn invalid_index_is_an_error_not_the_selection() {
let mut s = Session::with_new();
let r = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10.0, 10.0, 100.0, 100.0]})).unwrap();
let id = r.get("id").unwrap().as_u64().unwrap();
s.execute("animation.add", &json!({"effect": "fade", "class": "entrance", "ids": [id]})).unwrap();
s.select(|_, sel| {
sel.shapes = vec![deckcraft_model::ShapeId(id as u32)];
})
.unwrap();
for bad_index in [json!(-1), json!(1.5), json!("x")] {
for cmd in ["animation.remove", "animation.timing", "animation.options"] {
let r = s.execute(cmd, &json!({"index": bad_index, "duration": 100}));
assert!(r.is_err(), "{cmd} accepted index {bad_index}: {r:?}");
}
let r = s.execute("animation.move", &json!({"index": bad_index, "to": 0}));
assert!(r.is_err(), "animation.move accepted index {bad_index}: {r:?}");
assert_eq!(s.execute("animation.get", &json!({})).unwrap().as_array().unwrap().len(), 1);
}
}
fn path_of(s: &mut Session) -> Option<String> {
let all = s.execute("animation.get", &json!({})).unwrap();
all.as_array().unwrap().last().and_then(|a| a.get("path")).and_then(Value::as_str).map(String::from)
}
fn shape(s: &mut Session) -> u64 {
s.execute("shape.insert", &json!({"preset": "ellipse", "rect": [100.0, 400.0, 20.0, 20.0]})).unwrap().get("id").unwrap().as_u64().unwrap()
}
/// #1576: points in slide points, as offsets from the shape, become the slide-fraction path.
#[test]
fn a_custom_path_takes_its_points() {
let mut s = Session::with_new();
let id = shape(&mut s);
let w = s.doc().unwrap().doc.slide_size.width;
let h = s.doc().unwrap().doc.slide_size.height;
let r = s
.execute(
"animation.add",
&json!({"effect": "customPath", "class": "path", "path": [[0, 0], [w / 2.0, -h / 4.0], [w, -h / 2.0]], "ids": [id]}),
)
.unwrap();
assert_eq!(r["path"], "M 0 0 L 0.5 -0.25 L 1 -0.5 E");
assert_eq!(path_of(&mut s).as_deref(), Some("M 0 0 L 0.5 -0.25 L 1 -0.5 E"));
// closed shapes end back at the start; set replaces; no path keeps the default
s.execute("animation.set", &json!({"effect": "customPath", "path": [[0, 0], [w / 4.0, 0], [w / 4.0, h / 4.0]], "closed": true, "ids": [id]}))
.unwrap();
assert_eq!(path_of(&mut s).as_deref(), Some("M 0 0 L 0.25 0 L 0.25 0.25 Z E"));
s.execute("animation.set", &json!({"effect": "customPath", "ids": [id]})).unwrap();
assert_eq!(path_of(&mut s).as_deref(), Some("M 0 0 L 0 0.25 E"));
}
#[test]
fn a_raw_path_string_is_kept_and_options_edits_it() {
let mut s = Session::with_new();
let id = shape(&mut s);
s.execute("animation.add", &json!({"effect": "customPath", "path": "M 0 0 C 0.1 0 0.2 0.1 0.3 0.1 E", "ids": [id]})).unwrap();
assert_eq!(path_of(&mut s).as_deref(), Some("M 0 0 C 0.1 0 0.2 0.1 0.3 0.1 E"));
s.execute("animation.options", &json!({"index": 0, "path": [[0, 0], [96, 54]]})).unwrap();
assert_eq!(path_of(&mut s).as_deref(), Some("M 0 0 L 0.1 0.1 E"));
}
#[test]
fn a_bad_path_is_refused_and_changes_nothing() {
let mut s = Session::with_new();
let id = shape(&mut s);
let many: Vec<Value> = (0..2_000).map(|i| json!([i, i])).collect();
for bad_path in [
json!([[0, 0]]),
json!([]),
json!([[0, 0], [1]]),
json!([[0, 0], ["a", 1]]),
json!([[0, 0], [1e300, 1]]),
json!([[0, 0], [null, 1]]),
json!("M 0 0 L <script> E"),
json!("not a path"),
json!("eeee1"),
json!("M 0 0 L 1e999 0 E"),
json!(5),
Value::Array(many),
Value::String("M 0 0 L 0.1 0.1 ".repeat(10_000)),
] {
let r = s.execute("animation.add", &json!({"effect": "customPath", "path": bad_path, "ids": [id]}));
assert!(r.is_err(), "{bad_path:.60}");
}
assert!(
s.execute("animation.add", &json!({"effect": "fade", "path": [[0, 0], [1, 1]], "ids": [id]})).is_err(),
"path only fits a motion path"
);
assert!(s.execute("animation.get", &json!({})).unwrap().as_array().unwrap().is_empty(), "a refused add left an animation behind");
}
}
+8 -207
View File
@@ -4,26 +4,11 @@ use deckcraft_geom::{Point, Rect, Xfrm};
use deckcraft_model::{Shape, ShapeId, ShapeKind};
use serde_json::{Value, json};
use super::{
CommandSpec, NO_ID_SPACE, bad, bool_or, cmd, edit_geometry, has_doc, has_selection, has_slide, has_two, id_param, ok, str_param, targets,
usize_param, with_param, xfrm_of,
};
use super::*;
use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"guide.add",
"Add Guide",
["View", "Show", "Guides"],
None,
"{vertical: bool, pos?: pt (default: the slide's centre)} → {index}. `defaults: true` adds the two centre guides when there are none",
has_doc,
guide_add
),
cmd!("guide.move", "Move Guide", [], None, "{index, pos: pt}", has_doc, guide_move),
cmd!("guide.delete", "Delete Guide", [], None, "{index}", has_doc, guide_delete),
cmd!(query "guide.list", "Guides", [], None, "{} → [{vertical, pos}]", has_doc, guide_list),
cmd!("arrange.bringToFront", "Bring to Front", ["Arrange"], Some("Cmd+Shift+]"), "{ids?}", has_selection, |s, p| order(s, p, 2)),
cmd!("arrange.bringForward", "Bring Forward", ["Arrange"], Some("Cmd+]"), "{ids?}", has_selection, |s, p| order(s, p, 1)),
cmd!("arrange.sendBackward", "Send Backward", ["Arrange"], Some("Cmd+["), "{ids?}", has_selection, |s, p| order(s, p, -1)),
@@ -144,7 +129,7 @@ fn order_list(list: &mut Vec<Shape>, ids: &[ShapeId], how: i32) {
/// Move one shape to `index` among its siblings (0 = back): the Selection pane's drag and drop.
/// A shape stays in the list that holds it, so a group's child stays in its group.
fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
let id = id_param(p, "id", "arrange.reorder")?.ok_or_else(|| bad("arrange.reorder", "missing `id`"))?;
let id = id_param(p, "id").ok_or_else(|| bad("arrange.reorder", "missing `id`"))?;
let to = usize_param(p, "index").ok_or_else(|| bad("arrange.reorder", "missing `index`"))?;
let st = s.doc()?;
let siblings: &[Shape] = match deckcraft_model::parent_of(st.shapes(), id) {
@@ -168,28 +153,12 @@ fn reorder(s: &mut Session, p: &Value) -> Result<Value> {
}
/// Bounds of shapes (rotation included).
pub(crate) fn union_bounds(xs: &[Xfrm]) -> Option<Rect> {
fn union_bounds(xs: &[Xfrm]) -> Option<Rect> {
let mut it = xs.iter().map(Xfrm::bounds);
let first = it.next()?;
Some(it.fold(first, |a, b| a.union(b)))
}
/// How deep groups may nest: as deep as the PPTX reader reads and the renderer draws. A saved
/// .deckcraft file stops opening at about 39 (the JSON reader's recursion limit), and walks over
/// the shape tree stop at 64.
pub const MAX_GROUP_DEPTH: usize = 32;
/// How many groups deep `shapes` nest (0 without groups).
fn group_depth(shapes: &[Shape]) -> usize {
let mut d = 0;
deckcraft_model::walk(shapes, &mut |sh, depth| {
if sh.is_group() {
d = d.max(depth + 1);
}
});
d
}
fn group(s: &mut Session, p: &Value) -> Result<Value> {
let ids = targets(s, p)?;
s.edit(|doc, sel| {
@@ -198,9 +167,6 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
if members.len() < 2 {
return Err(bad("arrange.group", "select two or more objects on the slide"));
}
if group_depth(&members) + 1 > MAX_GROUP_DEPTH {
return Err(bad("arrange.group", format!("groups can be nested at most {MAX_GROUP_DEPTH} deep")));
}
for m in &mut members {
if m.xfrm.is_none() {
m.xfrm = Some(xfrm_of(doc, sel, m));
@@ -211,7 +177,7 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
let xs: Vec<Xfrm> = members.iter().filter_map(|m| m.xfrm).collect();
let b = union_bounds(&xs).ok_or_else(|| bad("arrange.group", "nothing to group"))?;
let gx = Xfrm::new(b.x0, b.y0, b.width(), b.height());
let id = ShapeId(doc.alloc_id().ok_or_else(|| bad("arrange.group", NO_ID_SPACE))?);
let id = ShapeId(doc.alloc_id());
let n = super::current_shapes(doc, sel).map(|v| v.len()).unwrap_or(0);
let g = Shape {
id,
@@ -229,100 +195,8 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// After an edit: refit every group whose children's geometry changed to the union of its
/// children (PowerPoint keeps a group's box on its children, so moving one child grows or
/// shrinks the group). The children keep their place on the slide: the group's box and its child
/// space change together. `old` is the presentation before the edit; only slides the edit
/// touched are looked at, and a group whose own box changed (it was moved or resized) is left to
/// that edit.
pub(crate) fn refit_groups(old: &deckcraft_model::Presentation, new: &mut deckcraft_model::Presentation) {
// Each slide, master and layout is compared with its own earlier state, found by id: a move,
// insertion or deletion shifts the indices, and shape ids repeat across slides.
let old_slides: std::collections::HashMap<_, _> = old.slides.iter().map(|s| (s.id, s)).collect();
for slide in new.slides.iter_mut() {
let Some(before) = old_slides.get(&slide.id) else { continue };
if std::sync::Arc::ptr_eq(before, slide) {
continue;
}
let shapes = &mut std::sync::Arc::make_mut(slide).shapes;
refit_list(Some(&before.shapes), shapes, 0);
}
// A child edited in Slide Master, layout, notes or handout view refits its group there too.
for master in new.masters.iter_mut() {
if let Some(before) = old.masters.iter().find(|m| m.id == master.id)
&& !std::sync::Arc::ptr_eq(before, master)
{
refit_master(before, std::sync::Arc::make_mut(master));
}
}
for (before, after) in [(old.notes_master.as_ref(), new.notes_master.as_mut()), (old.handout_master.as_ref(), new.handout_master.as_mut())] {
if let (Some(before), Some(after)) = (before, after)
&& !std::sync::Arc::ptr_eq(before, after)
{
refit_master(before, std::sync::Arc::make_mut(after));
}
}
}
fn refit_master(old: &deckcraft_model::Master, new: &mut deckcraft_model::Master) {
refit_list(Some(&old.shapes), &mut new.shapes, 0);
for layout in new.layouts.iter_mut() {
refit_list(old.layouts.iter().find(|l| l.id == layout.id).map(|l| &l.shapes), &mut layout.shapes, 0);
}
}
fn refit_list(old: Option<&Vec<Shape>>, list: &mut [Shape], depth: usize) {
// Most edits touch a slide without groups: nothing to refit, and no per-shape lookup. Nesting
// is bounded like the model's other walks.
if depth > 64 || !list.iter().any(|sh| matches!(sh.kind, ShapeKind::Group { .. })) {
return;
}
let by_id: std::collections::HashMap<ShapeId, &Shape> = old.map(|o| o.iter().map(|x| (x.id, x)).collect()).unwrap_or_default();
for sh in list.iter_mut() {
let before = by_id.get(&sh.id).copied();
let old_children = before.and_then(|b| match &b.kind {
ShapeKind::Group { children, .. } => Some(children),
_ => None,
});
let own_before = before.map(|b| {
(
b.xfrm,
match &b.kind {
ShapeKind::Group { child, .. } => Some(*child),
_ => None,
},
)
});
let smart = sh.diagram.is_some();
let ShapeKind::Group { children, child } = &mut sh.kind else { continue };
refit_list(old_children, children, depth + 1);
if smart {
// A SmartArt graphic's box is its own; its shapes are regenerated inside it.
continue;
}
let (Some(old_children), Some((old_x, old_child))) = (old_children, own_before) else { continue };
if old_x != sh.xfrm || old_child != Some(*child) || children.is_empty() {
continue;
}
let same = old_children.len() == children.len() && old_children.iter().zip(children.iter()).all(|(a, b)| a.id == b.id && a.xfrm == b.xfrm);
if same {
continue;
}
let Some(group) = sh.xfrm else { continue };
let xs: Vec<Xfrm> = children.iter().filter_map(|c| c.xfrm).collect();
let Some(u) = union_bounds(&xs) else { continue };
if ![u.x0, u.y0, u.x1, u.y1].iter().all(|v| v.is_finite()) {
continue;
}
let union = Xfrm::new(u.x0, u.y0, u.width(), u.height());
let placed = child_to_parent(&group, child, &union);
sh.xfrm = Some(Xfrm { x: placed.x, y: placed.y, w: placed.w, h: placed.h, rot: group.rot, flip_h: group.flip_h, flip_v: group.flip_v });
*child = union;
}
}
/// A child's xfrm in slide space, given its group.
pub fn child_to_parent(group: &Xfrm, ch: &Xfrm, c: &Xfrm) -> Xfrm {
pub(crate) fn child_to_parent(group: &Xfrm, ch: &Xfrm, c: &Xfrm) -> Xfrm {
let sx = if ch.w.abs() > 1e-9 { group.w / ch.w } else { 1.0 };
let sy = if ch.h.abs() > 1e-9 { group.h / ch.h } else { 1.0 };
let a = deckcraft_geom::group_child_affine(group, Rect::new(ch.x, ch.y, ch.x + ch.w, ch.y + ch.h));
@@ -436,9 +310,9 @@ fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
let (start, end) = if to_slide {
if horiz { (0.0, size.width) } else { (0.0, size.height) }
} else {
let lo = |f: fn(&Rect) -> f64| boxes.iter().map(|b| f(&b.1)).fold(f64::INFINITY, f64::min);
let hi = |f: fn(&Rect) -> f64| boxes.iter().map(|b| f(&b.1)).fold(f64::NEG_INFINITY, f64::max);
if horiz { (lo(|r| r.x0), hi(|r| r.x1)) } else { (lo(|r| r.y0), hi(|r| r.y1)) }
let f = boxes.first().map(|b| b.1).unwrap_or_default();
let l = boxes.last().map(|b| b.1).unwrap_or_default();
if horiz { (f.x0, l.x1) } else { (f.y0, l.y1) }
};
let n = boxes.len();
let gap = if n > 1 { ((end - start) - total) / (n - 1) as f64 } else { 0.0 };
@@ -464,76 +338,3 @@ fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
Ok(())
})
}
/// Guides are kept on the slide; a file can hold at most this many.
const MAX_GUIDES: usize = 200;
fn guide_limit(s: &Session, vertical: bool) -> Result<f64> {
let size = s.doc()?.doc.slide_size;
Ok(if vertical { size.width } else { size.height })
}
fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
if bool_or(p, "defaults", false) {
if !s.doc()?.doc.guides.is_empty() {
return Ok(json!({"added": 0}));
}
let size = s.doc()?.doc.slide_size;
return s.edit(|doc, _| {
doc.guides = vec![
deckcraft_model::DrawGuide { vertical: true, pos: size.width / 2.0 },
deckcraft_model::DrawGuide { vertical: false, pos: size.height / 2.0 },
];
Ok(json!({"added": 2}))
});
}
let vertical = bool_or(p, "vertical", true);
let limit = guide_limit(s, vertical)?;
let pos = p.get("pos").and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(limit / 2.0).clamp(0.0, limit);
if s.doc()?.doc.guides.len() >= MAX_GUIDES {
return Err(bad("guide.add", "too many guides"));
}
s.edit(|doc, _| {
doc.guides.push(deckcraft_model::DrawGuide { vertical, pos });
Ok(json!({"index": doc.guides.len() - 1}))
})
}
fn guide_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
let i = usize_param(p, "index").ok_or_else(|| bad(cmd, "missing `index`"))?;
if i >= s.doc()?.doc.guides.len() {
return Err(bad(cmd, "no such guide"));
}
Ok(i)
}
fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
let i = guide_index(s, p, "guide.move")?;
let vertical = s.doc()?.doc.guides.get(i).is_some_and(|g| g.vertical);
let limit = guide_limit(s, vertical)?;
let pos = p.get("pos").and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("guide.move", "missing `pos`"))?.clamp(0.0, limit);
s.edit(|doc, _| {
if let Some(g) = doc.guides.get_mut(i) {
g.pos = pos;
}
Ok(json!({"index": i, "pos": pos}))
})
}
fn guide_delete(s: &mut Session, p: &Value) -> Result<Value> {
let i = guide_index(s, p, "guide.delete")?;
s.edit(|doc, _| {
if i < doc.guides.len() {
doc.guides.remove(i);
}
ok()
})
}
fn guide_list(s: &mut Session, _p: &Value) -> Result<Value> {
Ok(serde_json::to_value(&s.doc()?.doc.guides).unwrap_or_default())
}
#[cfg(test)]
#[path = "guides_tests.rs"]
mod guides_tests;
-202
View File
@@ -1,202 +0,0 @@
//! Picture Format ▸ Artistic Effects: a picture redrawn as a pencil sketch, blurred, grainy…
//!
//! The effect is applied to the pixels and the result becomes the picture, as PowerPoint does;
//! the original is kept (`PictureFill::artistic`) so the effect can be changed or removed, and
//! both are saved (`a14:imgLayer`). The effects approximate PowerPoint's look.
use deckcraft_model::style::Artistic;
use deckcraft_model::{MediaId, ShapeId, ShapeKind};
use image::{GrayImage, Rgba, RgbaImage};
use serde_json::{Value, json};
use super::{CommandSpec, NO_ID_SPACE, bad, cmd, has_selection, str_param, targets};
use crate::{Result, Session};
/// The effects offered: `a14` element name and label.
pub const EFFECTS: &[(&str, &str)] = &[
("artisticBlur", "Blur"),
("artisticPencilGrayscale", "Pencil Grayscale"),
("artisticLineDrawing", "Line Drawing"),
("artisticFilmGrain", "Film Grain"),
("artisticCutout", "Cutout"),
("artisticGlowEdges", "Glow Edges"),
("artisticPhotocopy", "Photocopy"),
];
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"picture.artisticEffect",
"Artistic Effects",
["Picture Format", "Adjust"],
None,
"{effect: none|artisticBlur|artisticPencilGrayscale|artisticLineDrawing|artisticFilmGrain|artisticCutout|artisticGlowEdges|artisticPhotocopy, ids?}",
has_selection,
artistic_effect
)]
}
/// Largest side processed; bigger pictures are scaled down first.
const MAX_SIDE: u32 = 3000;
fn luma(p: &Rgba<u8>) -> f32 {
0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32
}
fn gray(img: &RgbaImage) -> GrayImage {
GrayImage::from_fn(img.width(), img.height(), |x, y| image::Luma([luma(img.get_pixel(x, y)).round().clamp(0.0, 255.0) as u8]))
}
/// Sobel edge strength, 0–255.
fn edges(g: &GrayImage) -> GrayImage {
let (w, h) = g.dimensions();
let at = |x: i64, y: i64| g.get_pixel(x.clamp(0, w as i64 - 1) as u32, y.clamp(0, h as i64 - 1) as u32)[0] as f32;
GrayImage::from_fn(w, h, |x, y| {
let (x, y) = (x as i64, y as i64);
let gx = at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1) - at(x - 1, y - 1) - 2.0 * at(x - 1, y) - at(x - 1, y + 1);
let gy = at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1) - at(x - 1, y - 1) - 2.0 * at(x, y - 1) - at(x + 1, y - 1);
image::Luma([((gx * gx + gy * gy).sqrt() / 4.0).clamp(0.0, 255.0) as u8])
})
}
/// Applies `effect` to `img` (alpha kept).
pub fn apply(effect: &str, img: &RgbaImage) -> Option<RgbaImage> {
let (w, h) = img.dimensions();
let scale = ((w * w + h * h) as f32).sqrt() / 1000.0;
let alpha = |x: u32, y: u32| img.get_pixel(x, y)[3];
let out = match effect {
"artisticBlur" => image::imageops::blur(img, (6.0 * scale).max(1.0)),
"artisticPencilGrayscale" | "artisticLineDrawing" | "artisticPhotocopy" => {
let soft = image::imageops::blur(&gray(img), (0.8 * scale).max(0.5));
let e = edges(&soft);
RgbaImage::from_fn(w, h, |x, y| {
let ev = e.get_pixel(x, y)[0] as f32;
let gv = soft.get_pixel(x, y)[0] as f32;
let v = match effect {
"artisticPencilGrayscale" => 255.0 - ev * 2.0 - (255.0 - gv) * 0.25,
"artisticLineDrawing" => {
if ev > 28.0 {
255.0 - (ev - 28.0) * 3.0
} else {
255.0
}
}
_ => {
if ev > 40.0 || gv < 70.0 {
0.0
} else {
255.0
}
}
};
let v = v.clamp(0.0, 255.0) as u8;
Rgba([v, v, v, alpha(x, y)])
})
}
"artisticFilmGrain" => {
// Deterministic noise, so the same picture gives the same grain.
let mut seed: u32 = 0x9E37_79B9;
RgbaImage::from_fn(w, h, |x, y| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
let n = (seed % 61) as f32 - 30.0;
let p = img.get_pixel(x, y);
let c = |v: u8| ((v as f32 - 128.0) * 1.1 + 128.0 + n).clamp(0.0, 255.0) as u8;
Rgba([c(p[0]), c(p[1]), c(p[2]), p[3]])
})
}
"artisticCutout" => {
let soft = image::imageops::blur(img, (1.5 * scale).max(0.5));
RgbaImage::from_fn(w, h, |x, y| {
let p = soft.get_pixel(x, y);
let q = |v: u8| ((v as f32 / 255.0 * 3.0).round() / 3.0 * 255.0) as u8;
Rgba([q(p[0]), q(p[1]), q(p[2]), alpha(x, y)])
})
}
"artisticGlowEdges" => {
let e = edges(&gray(img));
RgbaImage::from_fn(w, h, |x, y| {
let k = (e.get_pixel(x, y)[0] as f32 / 255.0 * 2.5).min(1.0);
let p = img.get_pixel(x, y);
let c = |v: u8| (v as f32 * k + 255.0 * k * 0.3).clamp(0.0, 255.0) as u8;
Rgba([c(p[0]), c(p[1]), c(p[2]), p[3]])
})
}
_ => return None,
};
Some(out)
}
/// Decodes `data`, applies `effect` and encodes a PNG.
fn process(effect: &str, data: &[u8]) -> Result<Vec<u8>> {
let img = image::load_from_memory(data).map_err(|_| bad("picture.artisticEffect", "this picture's format can't be processed"))?;
let img = if img.width().max(img.height()) > MAX_SIDE { img.thumbnail(MAX_SIDE, MAX_SIDE) } else { img };
let out = apply(effect, &img.to_rgba8()).ok_or_else(|| bad("picture.artisticEffect", "unknown effect"))?;
let mut png = Vec::new();
image::DynamicImage::ImageRgba8(out)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.map_err(|_| bad("picture.artisticEffect", "the processed picture couldn't be stored"))?;
Ok(png)
}
fn artistic_effect(s: &mut Session, p: &Value) -> Result<Value> {
let effect = match str_param(p, "effect") {
Some("none") => None,
Some(e) if EFFECTS.iter().any(|(n, _)| *n == e) => Some(e.to_string()),
_ => return Err(bad("picture.artisticEffect", "`effect` is none or one of artisticBlur, artisticPencilGrayscale, …")),
};
let ids = targets(s, p)?;
let st = s.doc()?;
// (shape, original picture, its bytes and name)
let mut work: Vec<(ShapeId, MediaId, Option<(Vec<u8>, String)>)> = Vec::new();
for id in ids {
let Some(ShapeKind::Picture { fill }) = st.shape(id).map(|sh| &sh.kind) else { continue };
let original = fill.artistic.as_ref().map_or(fill.media, |a| a.original);
let item = st.doc.media(original).map(|m| (m.data.to_vec(), m.name.clone()));
work.push((id, original, item));
}
if work.is_empty() {
return Err(bad("picture.artisticEffect", "select a picture"));
}
let mut results: Vec<(ShapeId, MediaId, Option<(String, Vec<u8>)>)> = Vec::new();
for (id, original, item) in work {
let processed = match (&effect, item) {
(None, _) => None,
(Some(e), Some((data, name))) => {
Some((format!("{}-{}.png", name.rsplit_once('.').map_or(name.as_str(), |x| x.0), e), process(e, &data)?))
}
(Some(_), None) => return Err(bad("picture.artisticEffect", "the picture's data is missing")),
};
results.push((id, original, processed));
}
let effect2 = effect.clone();
s.edit(move |doc, sel| {
let mut set: Vec<(ShapeId, MediaId, Option<MediaId>)> = Vec::new();
for (id, original, processed) in &results {
let m = match processed {
Some((name, png)) => Some(doc.add_media(name, "image/png", png.clone()).ok_or_else(|| bad("picture.artisticEffect", NO_ID_SPACE))?),
None => None,
};
set.push((*id, *original, m));
}
let list = crate::shapes_mut(doc, sel).ok_or_else(|| bad("picture.artisticEffect", "no slide"))?;
for (id, original, m) in set {
if let Some(sh) = deckcraft_model::find_shape_mut(list, id)
&& let ShapeKind::Picture { fill } = &mut sh.kind
{
match (m, &effect2) {
(Some(m), Some(e)) => {
fill.media = m;
fill.artistic = Some(Artistic { effect: e.clone(), original });
}
_ => {
fill.media = original;
fill.artistic = None;
}
}
}
}
Ok(())
})?;
Ok(json!({"effect": effect}))
}
-249
View File
@@ -1,249 +0,0 @@
//! Picture Format ▸ Remove Background: a classical matte, no model. The background is what the
//! picture's edges reach through similar colours: a flood fill from every edge pixel, each step
//! close to the pixel before it (gradients and soft shadows) and to the edge colour it started
//! from (so it can't leak into the subject). It turns transparent, with a one-pixel soft edge.
use std::collections::VecDeque;
use deckcraft_model::{ShapeId, ShapeKind};
use serde_json::{Value, json};
use super::{CommandSpec, NO_ID_SPACE, bad, cmd, f64_or, has_selection, targets};
use crate::{Result, Session};
/// Larger pictures are refused rather than matted slowly (16 megapixels).
const MAX_PIXELS: u64 = 16_000_000;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"picture.removeBackground",
"Remove Background",
["Picture Format", "Adjust"],
None,
"{tolerance?: 0..100 (how different a colour may be from the edge's, default 20), ids?}",
has_selection,
remove_background
)]
}
fn dist(a: [u8; 4], b: [u8; 4]) -> f64 {
let d = |i: usize| f64::from(a[i]) - f64::from(b[i]);
(d(0) * d(0) + d(1) * d(1) + d(2) * d(2)).sqrt()
}
/// Make the background of `img` transparent. `tolerance` is 0–100. Returns how many pixels
/// became transparent.
pub fn matte(img: &mut image::RgbaImage, tolerance: f64) -> usize {
let (w, h) = (img.width() as usize, img.height() as usize);
if w == 0 || h == 0 {
return 0;
}
// Distances run 0–441 (black to white); the step limit follows gradients, the seed limit
// keeps the fill on the edge's colour.
let seed_tol = tolerance.clamp(0.0, 100.0) * 4.41;
let step_tol = (seed_tol * 0.35).max(6.0);
let px = |img: &image::RgbaImage, i: usize| img.get_pixel((i % w) as u32, (i / w) as u32).0;
// 0: subject, 1: background; the seed colour each background pixel was reached from.
let mut bg = vec![false; w * h];
let mut seed = vec![[0u8; 4]; w * h];
let mut queue = VecDeque::new();
let push_edge = |i: usize, bg: &mut [bool], seed: &mut [[u8; 4]], q: &mut VecDeque<usize>| {
if let Some(b) = bg.get_mut(i)
&& !*b
{
*b = true;
if let Some(s) = seed.get_mut(i) {
*s = px(img, i);
}
q.push_back(i);
}
};
for x in 0..w {
push_edge(x, &mut bg, &mut seed, &mut queue);
push_edge((h - 1) * w + x, &mut bg, &mut seed, &mut queue);
}
for y in 0..h {
push_edge(y * w, &mut bg, &mut seed, &mut queue);
push_edge(y * w + w - 1, &mut bg, &mut seed, &mut queue);
}
while let Some(i) = queue.pop_front() {
let (x, y) = (i % w, i / w);
let here = px(img, i);
let from = seed.get(i).copied().unwrap_or(here);
let mut near = [None; 4];
if x > 0 {
near[0] = Some(i - 1);
}
if x + 1 < w {
near[1] = Some(i + 1);
}
if y > 0 {
near[2] = Some(i - w);
}
if y + 1 < h {
near[3] = Some(i + w);
}
for j in near.into_iter().flatten() {
if bg.get(j).copied().unwrap_or(true) {
continue;
}
let c = px(img, j);
// Transparent pixels are background already.
if c[3] < 16 || (dist(c, here) <= step_tol && dist(c, from) <= seed_tol) {
if let Some(b) = bg.get_mut(j) {
*b = true;
}
if let Some(s) = seed.get_mut(j) {
*s = from;
}
queue.push_back(j);
}
}
}
// A background edge that is the subject's colour throughout (the subject touches the
// edge on every side) is no background: leave such a picture alone.
let n = bg.iter().filter(|b| **b).count();
if n == w * h {
return 0;
}
let is_bg = |x: usize, y: usize| bg.get(y * w + x).copied().unwrap_or(false);
let mut soft = vec![];
for y in 0..h {
for x in 0..w {
if is_bg(x, y) {
continue;
}
let touching =
(x > 0 && is_bg(x - 1, y)) || (x + 1 < w && is_bg(x + 1, y)) || (y > 0 && is_bg(x, y - 1)) || (y + 1 < h && is_bg(x, y + 1));
if touching {
soft.push((x, y));
}
}
}
for (i, b) in bg.iter().enumerate() {
if *b {
img.get_pixel_mut((i % w) as u32, (i / w) as u32).0[3] = 0;
}
}
for (x, y) in soft {
let p = img.get_pixel_mut(x as u32, y as u32);
p.0[3] = (u16::from(p.0[3]) * 2 / 3) as u8;
}
n
}
fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
let tolerance = f64_or(p, "tolerance", 20.0);
let ids = targets(s, p)?;
let mut done: Vec<(ShapeId, String, Vec<u8>)> = vec![];
{
let st = s.doc()?;
for id in &ids {
let Some(sh) = st.shape(*id) else { continue };
let ShapeKind::Picture { fill } = &sh.kind else { continue };
let Some(item) = st.doc.media(fill.media) else { continue };
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(item.data.as_slice())).with_guessed_format() else { continue };
let Ok((iw, ih)) = reader.into_dimensions() else { continue };
if u64::from(iw) * u64::from(ih) > MAX_PIXELS {
return Err(bad("picture.removeBackground", format!("{iw}×{ih} pixels is too large; compress the picture first")));
}
let Ok(dynimg) = image::load_from_memory(&item.data) else { continue };
let mut img = dynimg.to_rgba8();
if matte(&mut img, tolerance) == 0 {
continue;
}
let mut png = vec![];
if image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
continue;
}
let stem = item.name.rsplit_once('.').map_or(item.name.as_str(), |(a, _)| a);
done.push((*id, format!("{stem}-no-background.png"), png));
}
}
if done.is_empty() {
return Err(bad("picture.removeBackground", "no background found: select a picture whose edges show its background"));
}
let n = done.len();
s.edit(|doc, sel| {
let added: Vec<(ShapeId, deckcraft_model::MediaId)> = done
.into_iter()
.map(|(id, name, png)| Ok((id, doc.add_media(&name, "image/png", png).ok_or_else(|| bad("picture.removeBackground", NO_ID_SPACE))?)))
.collect::<Result<_>>()?;
let shapes = crate::shapes_mut(doc, sel).ok_or_else(|| bad("picture.removeBackground", "no slide"))?;
for (id, media) in added {
if let Some(sh) = deckcraft_model::find_shape_mut(shapes, id)
&& let ShapeKind::Picture { fill } = &mut sh.kind
{
fill.media = media;
}
}
Ok(())
})?;
Ok(json!({"pictures": n}))
}
#[cfg(test)]
mod tests {
use deckcraft_model::{ShapeId, ShapeKind};
use serde_json::json;
use super::*;
use crate::Session;
use crate::cmd::base64_encode;
/// A red disc on a white-to-grey gradient.
fn disc() -> image::RgbaImage {
image::RgbaImage::from_fn(80, 60, |x, y| {
let (dx, dy) = (f64::from(x) - 40.0, f64::from(y) - 30.0);
if dx * dx + dy * dy < 15.0 * 15.0 {
image::Rgba([220, 30, 30, 255])
} else {
let g = 255 - (x / 2) as u8;
image::Rgba([g, g, g, 255])
}
})
}
#[test]
fn matte_clears_the_gradient_and_keeps_the_subject() {
let mut img = disc();
let n = matte(&mut img, 20.0);
assert!(n > 80 * 60 / 2, "{n}");
assert_eq!(img.get_pixel(0, 0).0[3], 0);
assert_eq!(img.get_pixel(79, 59).0[3], 0, "the darker end of the gradient");
assert_eq!(img.get_pixel(40, 30).0, [220, 30, 30, 255]);
// The disc's rim is softened, not cut.
let rim = img.get_pixel(40, 16).0[3];
assert!(rim > 0 && rim < 255 || img.get_pixel(40, 15).0[3] < 255, "{rim}");
// A picture with nothing but subject at its edges is left alone.
let mut flat = image::RgbaImage::from_pixel(10, 10, image::Rgba([10, 200, 10, 255]));
assert_eq!(matte(&mut flat, 20.0), 0);
assert!(flat.pixels().all(|p| p.0[3] == 255));
}
#[test]
fn remove_background_replaces_the_picture_and_undoes() {
let mut png = vec![];
image::DynamicImage::ImageRgba8(disc()).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::with_new();
let r = s.execute("insert.picture", &json!({"data": base64_encode(&png), "name": "disc.png"})).unwrap();
let id = r["id"].as_u64().unwrap();
let media_of = |s: &Session| match &s.doc().unwrap().shape(ShapeId(id as u32)).unwrap().kind {
ShapeKind::Picture { fill } => fill.media,
_ => panic!("not a picture"),
};
let before = media_of(&s);
s.execute("picture.removeBackground", &json!({"ids": [id]})).unwrap();
let after = media_of(&s);
assert_ne!(before, after);
let item = s.doc().unwrap().doc.media(after).unwrap().clone();
assert_eq!(item.name, "disc-no-background.png");
let img = image::load_from_memory(&item.data).unwrap().to_rgba8();
assert_eq!(img.get_pixel(0, 0).0[3], 0);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(media_of(&s), before);
// Not a picture: refused.
s.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 0, 50, 50]})).unwrap();
assert!(s.execute("picture.removeBackground", &json!({})).is_err());
}
}
-73
View File
@@ -1,73 +0,0 @@
//! `slide.colorAt`, the colour the slide is drawn with at a point: what the Eyedropper takes (#367).
use serde_json::{Value, json};
use crate::Session;
fn deck() -> Session {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 200, 100]})).unwrap();
s.execute("shape.fill", &json!({"color": "#ff0000"})).unwrap();
s
}
fn color_at(s: &mut Session, x: f64, y: f64) -> Value {
s.execute("slide.colorAt", &json!({"x": x, "y": y})).unwrap()
}
#[test]
fn a_point_in_a_shape_gives_its_fill_and_one_beside_it_the_background() {
let mut s = deck();
let inside = color_at(&mut s, 150.0, 150.0);
assert_eq!(inside["color"], "FF0000");
assert_eq!(inside["alpha"], 255);
let beside = color_at(&mut s, 700.0, 450.0);
assert_ne!(beside["color"], "FF0000");
// Just inside and just outside the shape's corner.
assert_eq!(color_at(&mut s, 101.0, 101.0)["color"], "FF0000");
assert_eq!(color_at(&mut s, 99.0, 99.0)["color"], beside["color"]);
// A finer or coarser picture gives the same colour.
for scale in [0.5, 1.0, 4.0] {
let v = s.execute("slide.colorAt", &json!({"x": 150, "y": 150, "scale": scale})).unwrap();
assert_eq!(v["color"], "FF0000", "scale {scale}");
}
// It is a query: the deck is not changed and nothing goes on the undo stack.
let revision = s.doc().unwrap().revision;
color_at(&mut s, 150.0, 150.0);
assert_eq!(s.doc().unwrap().revision, revision);
}
#[test]
fn a_see_through_fill_gives_the_colour_it_is_drawn_with() {
let mut s = deck();
let background = color_at(&mut s, 700.0, 450.0)["color"].as_str().unwrap().to_string();
s.execute("shape.fill", &json!({"transparency": 0.5})).unwrap();
let v = color_at(&mut s, 150.0, 150.0);
let c = v["color"].as_str().unwrap();
assert_ne!(c, "FF0000", "half of the background shows through");
assert_ne!(c, background);
assert_eq!(v["alpha"], 255, "the slide is opaque");
}
#[test]
fn points_outside_the_slide_and_bad_parameters_are_errors() {
let mut s = deck();
for p in [
json!({"x": -1, "y": 10}),
json!({"x": 10, "y": -0.5}),
json!({"x": 1e9, "y": 10}),
json!({"x": 10, "y": 1e9}),
json!({"x": 10}),
json!({"y": 10}),
json!({"x": "10", "y": 10}),
json!({"x": 10, "y": 10, "slide": 99}),
] {
assert!(s.execute("slide.colorAt", &p).is_err(), "{p}");
}
// Odd scales are clamped, not refused or crashed on.
for scale in [0.0, -3.0, 1e9] {
let v = s.execute("slide.colorAt", &json!({"x": 150, "y": 150, "scale": scale}));
assert!(v.is_ok(), "{scale}: {v:?}");
}
}
-447
View File
@@ -1,447 +0,0 @@
//! Picture Format ▸ Adjust ▸ Compress Pictures: downsample pictures to a target resolution for
//! the size they are shown at, and optionally delete their cropped-away areas.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use deckcraft_model::style::PictureFill;
use deckcraft_model::{MediaId, Shape, ShapeId, ShapeKind};
use serde_json::{Value, json};
use super::{CommandSpec, NO_ID_SPACE, bad, bool_or, cmd, f64_param, has_doc, targets};
use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"picture.compress",
"Compress Pictures",
["Picture Format", "Adjust"],
None,
"{ppi?: 330|220|150|96 (default 220), deleteCropped?: bool (default true), all?: bool (every picture in the presentation; default the selected pictures), ids?} → {pictures, before, after}",
has_doc,
compress
)]
}
/// A picture compressed for one shape: new bytes, content type and the crop it now needs.
struct Packed {
bytes: Vec<u8>,
content_type: &'static str,
crop: [f64; 4],
}
/// Whether `crop` cuts something away (and only cuts: negative values pad, and are kept).
fn real_crop(c: &[f64; 4]) -> bool {
c.iter().all(|v| (0.0..1.0).contains(v)) && c.iter().any(|v| *v > 0.0) && c[0] + c[2] < 1.0 && c[1] + c[3] < 1.0
}
/// Largest picture decoded for compression, in pixels (a 61 MP camera frame fits); bigger ones
/// are left as they are.
const MAX_PIXELS: u64 = 64_000_000;
/// Most memory the decoder may allocate for one picture.
const MAX_DECODE_BYTES: u64 = 512 << 20;
/// Decode `data` within [`MAX_PIXELS`] and [`MAX_DECODE_BYTES`]: the size is read from the header
/// first, so a picture claiming to be huge is never decoded.
fn decode(data: &[u8], format: image::ImageFormat) -> Option<image::DynamicImage> {
let (w, h) = image::ImageReader::with_format(std::io::Cursor::new(data), format).into_dimensions().ok()?;
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
return None;
}
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(data), format);
let mut limits = image::Limits::default();
limits.max_image_width = Some(w);
limits.max_image_height = Some(h);
limits.max_alloc = Some(MAX_DECODE_BYTES);
reader.limits(limits);
reader.decode().ok()
}
/// Compress `data` for a picture shown `w_pt` × `h_pt` with `crop`, at `ppi`. `None` when the
/// format isn't a raster we re-encode (SVG, EMF, GIF…) or nothing would get smaller.
fn pack(data: &[u8], crop: [f64; 4], w_pt: f64, h_pt: f64, ppi: f64, delete_cropped: bool) -> Option<Packed> {
use image::ImageFormat as F;
let format = image::guess_format(data).ok()?;
if !matches!(format, F::Png | F::Jpeg | F::Bmp | F::Tiff | F::WebP) {
return None;
}
let mut img = decode(data, format)?;
let (iw, ih) = (img.width() as f64, img.height() as f64);
if iw < 1.0 || ih < 1.0 {
return None;
}
let cut = delete_cropped && real_crop(&crop);
let mut new_crop = crop;
// The share of the image that is visible across and down.
let (mut fx, mut fy) = ((1.0 - crop[0] - crop[2]).max(0.01), (1.0 - crop[1] - crop[3]).max(0.01));
if cut {
let x = (crop[0] * iw).floor() as u32;
let y = (crop[1] * ih).floor() as u32;
let w = ((fx * iw).round() as u32).clamp(1, img.width() - x.min(img.width() - 1));
let h = ((fy * ih).round() as u32).clamp(1, img.height() - y.min(img.height() - 1));
img = img.crop_imm(x, y, w, h);
new_crop = [0.0; 4];
(fx, fy) = (1.0, 1.0);
} else if !crop.iter().all(|v| v.is_finite()) {
return None;
}
// Pixels needed for the whole (possibly still cropped) image at `ppi`.
let need_w = (w_pt.abs() / 72.0 * ppi / fx).ceil().max(1.0);
let need_h = (h_pt.abs() / 72.0 * ppi / fy).ceil().max(1.0);
let k = (need_w / img.width() as f64).max(need_h / img.height() as f64);
let resized = k < 1.0;
if resized {
let w = ((img.width() as f64 * k).round() as u32).max(1);
let h = ((img.height() as f64 * k).round() as u32).max(1);
img = img.resize_exact(w, h, image::imageops::FilterType::Lanczos3);
}
if !resized && !cut {
return None;
}
let alpha = img.color().has_alpha() && img.to_rgba8().pixels().any(|p| p.0[3] < 255);
let mut out = std::io::Cursor::new(Vec::new());
let content_type = if format == F::Jpeg && !alpha {
let rgb = img.to_rgb8();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 85).encode_image(&rgb).ok()?;
"image/jpeg"
} else {
img.write_to(&mut out, F::Png).ok()?;
"image/png"
};
let bytes = out.into_inner();
// Never make a picture bigger just to resample it; deleting a crop is worth it regardless.
if bytes.len() >= data.len() && !cut {
return None;
}
Some(Packed { bytes, content_type, crop: new_crop })
}
/// Pictures accepted by `want`, with width and height measured in slide space through group transforms.
fn pictures_mut<'a>(
shapes: &'a mut [Shape],
want: &dyn Fn(ShapeId) -> bool,
out: &mut Vec<(&'a mut Shape, f64, f64)>,
to_slide: deckcraft_geom::Affine,
depth: usize,
) {
if depth > 64 {
return;
}
for sh in shapes {
let Some(xfrm) = sh.xfrm else { continue };
let local_to_slide = to_slide * xfrm.affine();
if matches!(&sh.kind, ShapeKind::Picture { .. }) && want(sh.id) {
let origin = local_to_slide * deckcraft_geom::Point::ZERO;
let across = local_to_slide * deckcraft_geom::Point::new(xfrm.w, 0.0);
let down = local_to_slide * deckcraft_geom::Point::new(0.0, xfrm.h);
out.push((sh, (across - origin).hypot(), (down - origin).hypot()));
continue;
}
if let ShapeKind::Group { children, child } = &mut sh.kind {
let child_rect = deckcraft_geom::Rect::new(child.x, child.y, child.x + child.w, child.y + child.h);
let child_to_slide = to_slide * deckcraft_geom::group_child_affine(&xfrm, child_rect);
pictures_mut(children, want, out, child_to_slide, depth + 1);
}
}
}
fn compress(s: &mut Session, p: &Value) -> Result<Value> {
let ppi = f64_param(p, "ppi").unwrap_or(220.0);
if !ppi.is_finite() || !(36.0..=1200.0).contains(&ppi) {
return Err(bad("picture.compress", "`ppi` must be between 36 and 1200 (PowerPoint offers 330, 220, 150 and 96)"));
}
let delete_cropped = bool_or(p, "deleteCropped", true);
let all = bool_or(p, "all", false);
let ids: HashSet<ShapeId> = if all { HashSet::new() } else { targets(s, p)?.into_iter().collect() };
if !all && ids.is_empty() {
return Err(bad("picture.compress", "select a picture, or pass all: true"));
}
let current = s.doc()?.selection.slide;
s.edit(|doc, _| {
let want = |id: ShapeId| all || ids.contains(&id);
let mut before = 0usize;
let mut after = 0usize;
let mut count = 0usize;
let mut changed: Vec<MediaId> = vec![];
// The same picture at the same size and crop compresses once.
let mut cache: HashMap<(u32, [u64; 4], u64, u64), Option<(MediaId, [f64; 4], usize)>> = HashMap::new();
let range: Vec<usize> = if all { (0..doc.slides.len()).collect() } else { vec![current] };
for i in range {
let Some(slide) = doc.slides.get(i).cloned() else { continue };
let mut slide = slide.as_ref().clone();
let mut pics = vec![];
pictures_mut(&mut slide.shapes, &want, &mut pics, deckcraft_geom::Affine::IDENTITY, 0);
let mut touched = false;
for (sh, w, h) in pics {
let ShapeKind::Picture { fill } = &mut sh.kind else { continue };
let PictureFill { media, crop, .. } = fill.clone();
let key = (media.0, crop.map(f64::to_bits), w.to_bits(), h.to_bits());
let hit = match cache.get(&key) {
Some(v) => *v,
None => {
let packed = doc.media(media).filter(|m| !m.data.is_empty()).and_then(|m| {
let old = m.data.len();
pack(&m.data, crop, w, h, ppi, delete_cropped).map(|pk| (pk, old, m.name.clone()))
});
let v = match packed {
Some((pk, old, name)) => {
before += old;
after += pk.bytes.len();
let stem = std::path::Path::new(&name).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or(name);
let ext = if pk.content_type == "image/jpeg" { "jpg" } else { "png" };
let id = doc
.add_media(&format!("{stem}.{ext}"), pk.content_type, pk.bytes)
.ok_or_else(|| bad("picture.compress", NO_ID_SPACE))?;
Some((id, pk.crop, old))
}
None => None,
};
cache.insert(key, v);
v
}
};
if let Some((id, new_crop, _)) = hit {
changed.push(media);
fill.media = id;
fill.crop = new_crop;
count += 1;
touched = true;
}
}
if touched && let Some(sl) = doc.slides.get_mut(i) {
*sl = Arc::new(slide);
}
}
// Drop the originals nothing uses any more, so the saved file actually shrinks.
if !changed.is_empty() {
// Typed walk of every reference (artistic originals, fills, posters, sounds, fonts…).
let used: HashSet<MediaId> = crate::media_refs::presentation_media(doc).into_iter().collect();
doc.media.retain(|m| !changed.contains(&m.id) || used.contains(&m.id));
}
Ok(json!({"pictures": count, "before": before, "after": after, "ppi": ppi}))
})
}
#[cfg(test)]
mod tests {
use super::*;
fn png(w: u32, h: u32) -> Vec<u8> {
let img = image::RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 7 % 256) as u8, (y * 5 % 256) as u8, ((x ^ y) % 256) as u8]));
let mut out = std::io::Cursor::new(Vec::new());
image::DynamicImage::ImageRgb8(img).write_to(&mut out, image::ImageFormat::Png).unwrap();
out.into_inner()
}
#[test]
fn pack_downsamples_to_the_shown_size() {
// 2000 px shown at 1 inch: 150 ppi needs 150 px.
let pk = pack(&png(2000, 1000), [0.0; 4], 72.0, 36.0, 150.0, true).unwrap();
let img = image::load_from_memory(&pk.bytes).unwrap();
assert_eq!((img.width(), img.height()), (150, 75));
assert_eq!(pk.content_type, "image/png");
// Already small enough: nothing to do.
assert!(pack(&png(100, 50), [0.0; 4], 72.0, 36.0, 150.0, true).is_none());
// Not a raster we re-encode.
assert!(pack(b"<svg xmlns='http://www.w3.org/2000/svg'/>", [0.0; 4], 72.0, 72.0, 150.0, true).is_none());
}
#[test]
fn grouped_pictures_use_their_displayed_size() {
let mut s = Session::with_new();
let original = png(600, 600);
s.edit(|doc, _| {
let media = doc.add_media("grouped.png", "image/png", original.clone()).ok_or_else(|| bad("test", "media"))?;
let picture = Shape {
id: ShapeId(70_101),
xfrm: Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0)),
kind: ShapeKind::Picture { fill: PictureFill { media, ..Default::default() } },
..Default::default()
};
let nested = Shape {
id: ShapeId(70_102),
xfrm: Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0)),
kind: ShapeKind::Group { children: vec![picture], child: deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0) },
..Default::default()
};
let group = Shape {
id: ShapeId(70_103),
xfrm: Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 720.0, 720.0)),
kind: ShapeKind::Group { children: vec![nested], child: deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0) },
..Default::default()
};
let slide = doc.slides.first_mut().ok_or_else(|| bad("test", "slide"))?;
Arc::make_mut(slide).shapes.push(group);
Ok(())
})
.unwrap();
let result = s.execute("picture.compress", &json!({"all": true, "ppi": 96, "deleteCropped": false})).unwrap();
assert_eq!(result["pictures"], 0, "a 600 px image displayed at 720×720 pt is already below the requested sampling density");
assert!(
s.doc().unwrap().doc.media.iter().any(|m| m.data.as_slice() == original.as_slice()),
"the under-target original media must remain untouched"
);
}
#[test]
fn anisotropic_nested_group_scaling_controls_sampling_dimensions() {
let mut s = Session::with_new();
let original = png(2000, 1000);
s.edit(|doc, _| {
let media = doc.add_media("scaled-group.png", "image/png", original).ok_or_else(|| bad("test", "media"))?;
let picture = Shape {
id: ShapeId(70_111),
xfrm: Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0)),
kind: ShapeKind::Picture { fill: PictureFill { media, ..Default::default() } },
..Default::default()
};
let nested = Shape {
id: ShapeId(70_112),
xfrm: Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0)),
kind: ShapeKind::Group { children: vec![picture], child: deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0) },
..Default::default()
};
let group = Shape {
id: ShapeId(70_113),
xfrm: Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 720.0, 360.0)),
kind: ShapeKind::Group { children: vec![nested], child: deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0) },
..Default::default()
};
let slide = doc.slides.first_mut().ok_or_else(|| bad("test", "slide"))?;
Arc::make_mut(slide).shapes.push(group);
Ok(())
})
.unwrap();
let result = s.execute("picture.compress", &json!({"all": true, "ppi": 96, "deleteCropped": false})).unwrap();
assert_eq!(result["pictures"], 1);
let slide = s.doc().unwrap().doc.slides.first().unwrap();
let picture = slide.shapes.iter().find(|sh| sh.id == ShapeId(70_113)).unwrap();
let ShapeKind::Group { children, .. } = &picture.kind else { panic!("outer group expected") };
let ShapeKind::Group { children, .. } = &children[0].kind else { panic!("nested group expected") };
let ShapeKind::Picture { fill } = &children[0].kind else { panic!("picture expected") };
let media = s.doc().unwrap().doc.media(fill.media).unwrap();
let image = image::load_from_memory(&media.data).unwrap();
assert_eq!((image.width(), image.height()), (960, 480));
}
#[test]
fn ungrouped_picture_still_compresses_and_deletes_its_crop() {
let mut s = Session::with_new();
let original = png(800, 800);
s.edit(|doc, _| {
let media = doc.add_media("cropped.png", "image/png", original).ok_or_else(|| bad("test", "media"))?;
let slide = doc.slides.first_mut().ok_or_else(|| bad("test", "slide"))?;
Arc::make_mut(slide).shapes.push(Shape {
id: ShapeId(70_104),
xfrm: Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 72.0)),
kind: ShapeKind::Picture { fill: PictureFill { media, crop: [0.5, 0.0, 0.0, 0.0], ..Default::default() } },
..Default::default()
});
Ok(())
})
.unwrap();
let result = s.execute("picture.compress", &json!({"all": true, "ppi": 96, "deleteCropped": true})).unwrap();
assert_eq!(result["pictures"], 1);
let slide = s.doc().unwrap().doc.slides.first().unwrap();
let picture = slide.shapes.iter().find(|sh| sh.id == ShapeId(70_104)).unwrap();
let ShapeKind::Picture { fill } = &picture.kind else { panic!("picture expected") };
assert_eq!(fill.crop, [0.0; 4]);
let media = s.doc().unwrap().doc.media(fill.media).unwrap();
let image = image::load_from_memory(&media.data).unwrap();
assert_eq!((image.width(), image.height()), (96, 192));
}
#[test]
fn pack_deletes_cropped_areas_or_keeps_them() {
let src = png(400, 400);
// Left half cropped away, shown 2 in wide at 100 ppi → 200 px of the visible half.
let pk = pack(&src, [0.5, 0.0, 0.0, 0.0], 144.0, 288.0, 100.0, true).unwrap();
assert_eq!(pk.crop, [0.0; 4]);
let img = image::load_from_memory(&pk.bytes).unwrap();
assert_eq!((img.width(), img.height()), (200, 400));
// Keeping the crop: the whole image stays, scaled so the visible half has its pixels.
let pk = pack(&src, [0.5, 0.0, 0.0, 0.0], 72.0, 72.0, 100.0, false).unwrap();
assert_eq!(pk.crop, [0.5, 0.0, 0.0, 0.0]);
let img = image::load_from_memory(&pk.bytes).unwrap();
assert_eq!(img.width(), 200);
}
/// A PNG whose header claims `w` × `h` (no pixel data): enough for the size check.
fn png_header(w: u32, h: u32) -> Vec<u8> {
fn crc(bytes: &[u8]) -> u32 {
let mut c = 0xFFFF_FFFFu32;
for b in bytes {
c ^= u32::from(*b);
for _ in 0..8 {
c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
}
}
!c
}
fn chunk(out: &mut Vec<u8>, kind: &[u8], data: &[u8]) {
let body: Vec<u8> = kind.iter().chain(data).copied().collect();
out.extend((data.len() as u32).to_be_bytes());
out.extend(&body);
out.extend(crc(&body).to_be_bytes());
}
let mut ihdr = w.to_be_bytes().to_vec();
ihdr.extend(h.to_be_bytes());
ihdr.extend([8, 2, 0, 0, 0]);
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
chunk(&mut out, b"IHDR", &ihdr);
chunk(&mut out, b"IDAT", &[]);
chunk(&mut out, b"IEND", &[]);
out
}
#[test]
fn huge_pictures_are_not_decoded() {
// 72 MP: over the cap, though within what the decoder would allocate by default.
let data = png_header(9_000, 8_000);
assert_eq!(
image::ImageReader::with_format(std::io::Cursor::new(&data), image::ImageFormat::Png).into_dimensions().ok(),
Some((9_000, 8_000))
);
assert!(decode(&data, image::ImageFormat::Png).is_none());
assert!(pack(&data, [0.0; 4], 72.0, 72.0, 96.0, true).is_none());
}
/// Compressing a picture whose media is also another picture's artistic-effect original must
/// keep that media: the effect needs it to be changed or removed.
#[test]
fn media_still_used_as_an_artistic_original_is_kept() {
use deckcraft_model::style::Artistic;
let mut s = Session::with_new();
let big = png(1200, 600);
let processed = png(1100, 600);
s.edit(|doc, _| {
let original = doc.add_media("original.png", "image/png", big.clone()).expect("media");
let shown = doc.add_media("processed.png", "image/png", processed.clone()).expect("media");
let slide = Arc::make_mut(doc.slides.first_mut().ok_or_else(|| bad("test", "no slide"))?);
let xfrm = Some(deckcraft_geom::Xfrm::new(0.0, 0.0, 72.0, 36.0));
let with_effect =
PictureFill { media: shown, artistic: Some(Artistic { effect: "artisticBlur".into(), original }), ..Default::default() };
slide.shapes.push(Shape { id: ShapeId(70_001), xfrm, kind: ShapeKind::Picture { fill: with_effect }, ..Default::default() });
slide.shapes.push(Shape {
id: ShapeId(70_002),
xfrm,
kind: ShapeKind::Picture { fill: PictureFill { media: original, ..Default::default() } },
..Default::default()
});
Ok(())
})
.unwrap();
let r = s.execute("picture.compress", &json!({"all": true, "ppi": 96})).unwrap();
assert_eq!(r["pictures"], 2, "{r}");
let doc = &s.doc().unwrap().doc;
// Every reference left in the deck resolves to media that is still there.
for id in crate::media_refs::presentation_media(doc) {
assert!(doc.media(id).is_some(), "{id:?} was deleted while still referenced");
}
assert!(doc.media.iter().any(|m| m.data.as_slice() == big.as_slice()), "the artistic original was deleted");
assert!(!doc.media.iter().any(|m| m.data.as_slice() == processed.as_slice()), "the replaced processed picture is dropped");
}
}
+476 -220
View File
@@ -1,68 +1,29 @@
//! Design tab and masters: themes, colours, fonts, backgrounds, slide size, header & footer,
//! Slide Master view.
use std::collections::BTreeSet;
use std::sync::Arc;
use deckcraft_geom::Size;
use deckcraft_model::text::{Run, RunKind, TextBody};
use deckcraft_model::theme::{builtin_color_schemes, builtin_font_schemes, builtin_format_schemes, builtin_themes};
use deckcraft_model::theme::{builtin_color_schemes, builtin_font_schemes, builtin_themes};
use deckcraft_model::{Background, Fill, PhType, Presentation, Shape, ShapeId, defaults};
use serde_json::{Value, json};
use super::{
CommandSpec, NO_ID_SPACE, always, bad, bool_or, bool_param, cmd, color_param, color_value, f64_param, has_doc, has_slide, ok, opt_usize_param,
rect_param, str_param, usize_param, with_param,
};
use super::*;
use crate::{Result, Session, Target};
mod colors;
mod master_view;
mod slide_background;
mod slide_setup;
use colors::{colors, effects, fonts, variant, variants};
use master_view::{
close_master, delete_layout, handout_placeholders, handout_view, in_handout, in_notes_master, insert_layout, insert_placeholder, master_view,
notes_placeholders, notes_view, placeholders, preserve, rename_layout,
};
pub use master_view::{handout_placeholder, notes_placeholder};
use slide_background::{background, hide_bg_graphics};
pub use slide_setup::{civil, date_field_text, today};
use slide_setup::{header_footer, scale_shapes, slide_size};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("design.theme", "Themes", ["Design", "Themes"], None, "{name} (see design.themes)", has_doc, theme),
cmd!(
"design.browseTheme",
"Browse for Themes…",
["Design", "Themes"],
None,
"{path} | {name, data: base64} — apply a .pptx or .potx's slide master and layouts (slides move to the matching layouts), or a .thmx's theme",
has_doc,
browse_theme
),
cmd!(query "design.themes", "Theme Gallery", [], None, "{} → themes, colour schemes, font schemes and effect schemes", always, themes),
cmd!(
"design.colors",
"Colors",
["Design", "Variants"],
None,
"{} opens Create New Theme Colors | {name} | {colors: {dk1|lt1|dk2|lt2|accent1..6|hlink|folHlink: #RRGGBB}}",
has_doc,
colors
),
cmd!("design.variant", "Variants", ["Design", "Variants"], None, "{index: 0..3} (see design.variants)", has_doc, variant),
cmd!(query "design.variants", "Variant Gallery", [], None, "{} → the current theme's four colour variants and which is applied", has_doc, variants),
cmd!("design.fonts", "Fonts", ["Design", "Variants"], None, "{} opens Create New Theme Fonts | {name} | {major, minor}", has_doc, fonts),
cmd!("design.effects", "Effects", ["Design", "Variants"], None, "{name} (see design.themes)", has_doc, effects),
cmd!(query "design.themes", "Theme Gallery", [], None, "{} → themes, colour schemes and font schemes", always, themes),
cmd!("design.colors", "Colors", ["Design", "Variants"], None, "{name} | {colors: {accent1: #RRGGBB, …}}", has_doc, colors),
cmd!("design.fonts", "Fonts", ["Design", "Variants"], None, "{name} | {major, minor}", has_doc, fonts),
cmd!(
"design.background",
"Format Background",
["Design", "Customize"],
None,
"{color? | gradient? | picture?: base64 | pattern? | style?: 1..12 | reset?, all?: bool, index?, transparency?: 0..1, pictureProps?: {tile?, offsetX?, offsetY?: pt, scaleX?, scaleY?: 0.01..10, align?, mirror?, stretch?: [l,t,r,b], rotateWithShape?}, copy?: bool}",
"{color? | gradient? | picture?: base64 | style?: 1..12 | reset?, all?: bool (apply to all), index?}",
has_slide,
background
),
@@ -72,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Slide Size",
["Design", "Customize"],
None,
"{preset: widescreen|standard|…, orientation?: portrait|landscape, scale?: maximize|ensureFit|none} | {w: pt, h: pt, orientation?: portrait|landscape, scale?: maximize|ensureFit|none}",
"{preset?: widescreen|standard|… | w, h: pt, scale?: maximize|ensureFit|none}",
has_doc,
slide_size
),
@@ -86,42 +47,6 @@ pub fn specs() -> Vec<CommandSpec> {
header_footer
),
cmd!(noundo "view.slideMaster", "Slide Master", ["View", "Master Views"], None, "{master?: index, layout?: index}", has_doc, master_view),
cmd!(
"view.handoutMaster",
"Handout Master",
["View", "Master Views"],
None,
"{} (creates the handout master with header, date, footer and page number if the deck has none)",
has_doc,
handout_view
),
cmd!(
"handout.placeholders",
"Handout Placeholders",
["Handout Master", "Placeholders"],
None,
"{header?: bool, date?: bool, footer?: bool, pageNumber?: bool} (show or hide each)",
in_handout,
handout_placeholders
),
cmd!(
"view.notesMaster",
"Notes Master",
["View", "Master Views"],
None,
"{} (creates the notes master with header, date, slide image, notes body, footer and page number if the deck has none)",
has_doc,
notes_view
),
cmd!(
"notes.placeholders",
"Notes Placeholders",
["Notes Master", "Placeholders"],
None,
"{header?, date?, slideImage?, body?, footer?, pageNumber?: bool} (show or hide each)",
in_notes_master,
notes_placeholders
),
cmd!(noundo "view.closeMaster", "Close Master View", ["Slide Master", "Close"], None, "{}", has_doc, close_master),
cmd!("master.insertLayout", "Insert Layout", ["Slide Master", "Edit Master"], None, "{name?}", has_doc, insert_layout),
cmd!("master.renameLayout", "Rename Layout", ["Slide Master", "Edit Master"], None, "{name, master?, layout?}", has_doc, rename_layout),
@@ -135,16 +60,6 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
insert_placeholder
),
cmd!("master.preserve", "Preserve", ["Slide Master", "Edit Master"], None, "{preserve?: bool}", has_doc, preserve),
cmd!(
"master.placeholders",
"Layout Placeholders",
["Slide Master", "Edit Master"],
None,
"{title?: bool, footers?: bool}",
has_doc,
placeholders
),
]
}
@@ -164,133 +79,10 @@ fn theme(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"theme": name}))
}
fn browse_theme(s: &mut Session, p: &Value) -> Result<Value> {
let bytes = if let Some(data) = str_param(p, "data") {
super::base64_decode(data).ok_or_else(|| bad("design.browseTheme", "invalid base64 `data`"))?
} else {
#[cfg(not(target_arch = "wasm32"))]
{
let path = str_param(p, "path").ok_or_else(|| bad("design.browseTheme", "give `path` or `data`"))?;
crate::io::read_file(path).map_err(crate::EngineError::Other)?
}
#[cfg(target_arch = "wasm32")]
return Err(bad("design.browseTheme", "give `data`"));
};
if !deckcraft_pptx::sniff(&bytes) {
return Err(bad("design.browseTheme", "not a theme or PowerPoint file"));
}
// A presentation or template brings its slide master and layouts, as in PowerPoint; a .thmx
// (its main part is a theme, not a presentation) brings the theme alone.
if let Ok(src) = super::file::open_presentation("theme.pptx", &bytes)
&& src.masters.first().is_some_and(|m| !m.layouts.is_empty())
{
return apply_master(s, &src);
}
let (theme, media) = deckcraft_pptx::import_theme(&bytes).map_err(|e| bad("design.browseTheme", e.to_string()))?;
let name = theme.name.clone();
s.edit(|doc, sel| {
// The theme's pictures (format-scheme blip fills) get ids of this deck.
let mut map = std::collections::HashMap::new();
for m in &media {
let id = doc.add_media(&m.name, &m.content_type, m.data.as_ref().clone()).ok_or_else(|| bad("design.browseTheme", NO_ID_SPACE))?;
map.insert(m.id.0, id.0);
}
let theme = if map.is_empty() { theme.clone() } else { remap_media_ids(&theme, &map)? };
let mi = master_index(doc, sel);
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("design.browseTheme", "no master"))?);
m.theme = theme;
m.color_map = vec![];
Ok(())
})?;
Ok(json!({"theme": name}))
}
/// Design › Browse for Themes… with a `.pptx` / `.potx`: its first master and layouts replace the
/// master the current slide uses (a preserved master stays beside it), stretched to this deck's
/// slide size. Each slide on it moves to the new layout with the same name, else the same kind,
/// keeping its content as Layout does.
fn apply_master(s: &mut Session, src: &Presentation) -> Result<Value> {
let from = src.masters.first().ok_or_else(|| bad("design.browseTheme", "no master"))?;
let theme = from.theme.name.clone();
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
let old = doc.masters.get(mi).cloned().ok_or_else(|| bad("design.browseTheme", "no master"))?;
let (mut media, mut layouts) = Default::default();
let mut m = super::reuse::import_master("design.browseTheme", doc, src, from, &mut media, &mut layouts)?;
let (sx, sy) = (doc.slide_size.width / src.slide_size.width.max(1.0), doc.slide_size.height / src.slide_size.height.max(1.0));
if (sx - 1.0).abs() > 1e-9 || (sy - 1.0).abs() > 1e-9 {
scale_shapes(&mut m.shapes, sx, sy, 1.0, 0.0, 0.0);
for l in &mut m.layouts {
scale_shapes(&mut l.shapes, sx, sy, 1.0, 0.0, 0.0);
}
}
let moves: Vec<(usize, deckcraft_model::LayoutId)> =
doc.slides.iter().enumerate().filter_map(|(i, sl)| old.layout(sl.layout).and_then(|l| matching_layout(&m, l)).map(|l| (i, l))).collect();
let layouts = m.layouts.len();
if old.preserve {
doc.masters.insert(mi, Arc::new(m));
} else if let Some(slot) = doc.masters.get_mut(mi) {
*slot = Arc::new(m);
}
for (i, l) in &moves {
super::slide::apply_layout(doc, *i, *l)?;
}
if let Target::Layout { master, .. } = sel.target {
sel.target = Target::Master { master };
}
sel.shapes.clear();
sel.text = None;
Ok(json!({"theme": theme, "layouts": layouts, "slides": moves.len()}))
})
}
/// The layout of `m` a slide on `from` moves to: same name, else same kind (not for custom
/// layouts), else Title and Content, else the first.
fn matching_layout(m: &deckcraft_model::Master, from: &deckcraft_model::Layout) -> Option<deckcraft_model::LayoutId> {
use deckcraft_model::LayoutType;
let ls = &m.layouts;
ls.iter()
.find(|l| !from.name.is_empty() && l.name.trim().eq_ignore_ascii_case(from.name.trim()))
.or_else(|| ls.iter().find(|l| from.kind != LayoutType::Custom && l.kind == from.kind))
.or_else(|| ls.iter().find(|l| l.kind == LayoutType::TitleAndContent))
.or_else(|| ls.first())
.map(|l| l.id)
}
/// `theme` with every `media` id field rewritten through `map` (format-scheme picture fills).
fn remap_media_ids(theme: &deckcraft_model::theme::Theme, map: &std::collections::HashMap<u32, u32>) -> Result<deckcraft_model::theme::Theme> {
fn rec(v: &mut Value, map: &std::collections::HashMap<u32, u32>, depth: usize) {
if depth > 64 {
return;
}
match v {
Value::Object(o) => {
for (k, x) in o.iter_mut() {
if k == "media"
&& let Some(n) = x.as_u64().and_then(|n| u32::try_from(n).ok())
&& let Some(new) = map.get(&n)
{
*x = json!(new);
} else {
rec(x, map, depth + 1);
}
}
}
Value::Array(a) => a.iter_mut().for_each(|x| rec(x, map, depth + 1)),
_ => {}
}
}
let mut v = serde_json::to_value(theme).map_err(|e| bad("design.browseTheme", e.to_string()))?;
rec(&mut v, map, 0);
serde_json::from_value(v).map_err(|e| bad("design.browseTheme", e.to_string()))
}
fn master_index(doc: &Presentation, sel: &crate::Selection) -> usize {
match sel.target {
Target::Master { master } | Target::Layout { master, .. } => master,
Target::Slides | Target::Handout | Target::NotesMaster => {
doc.slides.get(sel.slide).and_then(|s| doc.masters.iter().position(|m| m.layout(s.layout).is_some())).unwrap_or(0)
}
Target::Slides => doc.slides.get(sel.slide).and_then(|s| doc.masters.iter().position(|m| m.layout(s.layout).is_some())).unwrap_or(0),
}
}
@@ -299,12 +91,476 @@ fn themes(_s: &mut Session, _p: &Value) -> Result<Value> {
"themes": builtin_themes().iter().map(|t| json!({"name": t.name, "major": t.fonts.major.latin, "minor": t.fonts.minor.latin, "colors": t.colors.colors.iter().map(|c| format!("#{}", c.hex())).collect::<Vec<_>>()})).collect::<Vec<_>>(),
"colorSchemes": builtin_color_schemes().iter().map(|c| c.name.clone()).collect::<Vec<_>>(),
"fontSchemes": builtin_font_schemes().iter().map(|f| json!({"name": f.name, "major": f.major.latin, "minor": f.minor.latin})).collect::<Vec<_>>(),
"effectSchemes": builtin_format_schemes().iter().map(|f| f.name.clone()).collect::<Vec<_>>(),
}))
}
#[cfg(test)]
mod tests;
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let scheme = if let Some(name) = str_param(p, "name") {
Some(
builtin_color_schemes()
.into_iter()
.find(|c| c.name.eq_ignore_ascii_case(name))
.ok_or_else(|| bad("design.colors", format!("no colour scheme `{name}`")))?,
)
} else {
None
};
let custom = p.get("colors").and_then(Value::as_object).cloned();
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("design.colors", "no master"))?);
if let Some(sc) = &scheme {
m.theme.colors = sc.clone();
}
if let Some(c) = &custom {
for (k, v) in c {
if let (Some(slot), Some(rgb)) = (deckcraft_color::SchemeSlot::from_xml(k), v.as_str().and_then(deckcraft_color::Rgba::from_hex)) {
m.theme.colors.set(slot, rgb);
}
}
m.theme.colors.name = "Custom".into();
}
Ok(())
})?;
ok()
}
fn fonts(s: &mut Session, p: &Value) -> Result<Value> {
let scheme = if let Some(name) = str_param(p, "name") {
builtin_font_schemes()
.into_iter()
.find(|f| f.name.eq_ignore_ascii_case(name))
.ok_or_else(|| bad("design.fonts", format!("no font scheme `{name}`")))?
} else {
let major = str_param(p, "major").ok_or_else(|| bad("design.fonts", "give `name`, or `major` and `minor`"))?;
let minor = str_param(p, "minor").unwrap_or(major);
deckcraft_model::theme::FontScheme {
name: "Custom".into(),
major: deckcraft_model::theme::FontSet { latin: major.into(), ..Default::default() },
minor: deckcraft_model::theme::FontSet { latin: minor.into(), ..Default::default() },
}
};
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("design.fonts", "no master"))?).theme.fonts = scheme;
Ok(())
})?;
ok()
}
fn background(s: &mut Session, p: &Value) -> Result<Value> {
let bg: Option<Background> = if bool_or(p, "reset", false) {
None
} else if let Some(c) = color_param(p, "color") {
Some(Background::Fill { fill: Fill::solid(c) })
} else if let Some(i) = usize_param(p, "style") {
// Background styles: 3 theme bg fills × 4 colours (bg1, bg2, tx1, tx2).
let slots =
[deckcraft_color::SchemeSlot::Bg1, deckcraft_color::SchemeSlot::Bg2, deckcraft_color::SchemeSlot::Tx2, deckcraft_color::SchemeSlot::Tx1];
let i = i.clamp(1, 12) - 1;
Some(Background::Ref {
idx: 1001 + (i / 4) as u32,
color: deckcraft_model::ColorRef::scheme(slots.get(i % 4).copied().unwrap_or(deckcraft_color::SchemeSlot::Bg1)),
})
} else if let Some(g) = p.get("gradient") {
let mut g = super::shape::gradient_param(g).ok_or_else(|| bad("design.background", "gradient needs two or more `stops`"))?;
g.rotate_with_shape = false;
Some(Background::Fill { fill: Fill::Gradient(g) })
} else if let Some(pt) = p.get("pattern") {
Some(Background::Fill {
fill: Fill::Pattern(deckcraft_model::style::PatternFill {
preset: pt.get("preset").and_then(Value::as_str).unwrap_or("pct50").to_string(),
fg: pt.get("fg").and_then(color_value).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent1)),
bg: pt.get("bg").and_then(color_value).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Bg1)),
}),
})
} else if p.get("picture").is_some() {
let (name, bytes) = super::insert::media_bytes(&with_param(p, "data", p.get("picture").cloned().unwrap_or_default()), "design.background")?;
let ct = super::insert::content_type(&name, &bytes);
let media = s.edit(|doc, _| Ok(doc.add_media(&name, ct, bytes)))?;
Some(Background::Fill { fill: Fill::Picture(deckcraft_model::style::PictureFill { media, ..Default::default() }) })
} else {
return Err(bad("design.background", "give `color`, `gradient`, `pattern`, `picture`, `style` or `reset`"));
};
let all = bool_or(p, "all", false);
let index = usize_param(p, "index");
s.edit(|doc, sel| {
match sel.target {
Target::Master { master } => {
if let Some(m) = doc.masters.get_mut(master) {
Arc::make_mut(m).background = bg.clone();
}
}
Target::Layout { master, layout } => {
if let Some(l) = doc.masters.get_mut(master).and_then(|m| Arc::make_mut(m).layouts.get_mut(layout)) {
l.background = bg.clone();
}
}
Target::Slides => {
let list: Vec<usize> = if all { (0..doc.slides.len()).collect() } else { vec![index.unwrap_or(sel.slide)] };
for i in list {
if let Some(sl) = doc.slides.get_mut(i) {
Arc::make_mut(sl).background = bg.clone();
}
}
}
}
Ok(())
})?;
ok()
}
fn hide_bg_graphics(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(|doc, sel| {
if let Some(sl) = doc.slides.get_mut(sel.slide) {
let sl = Arc::make_mut(sl);
sl.show_master_shapes = !bool_param(p, "hide").unwrap_or(sl.show_master_shapes);
}
Ok(())
})?;
ok()
}
fn scale_shapes(shapes: &mut [Shape], sx: f64, sy: f64, k: f64, ox: f64, oy: f64) {
for sh in shapes {
if let Some(x) = sh.xfrm.as_mut() {
x.x = x.x * sx + ox;
x.y = x.y * sy + oy;
x.w *= sx;
x.h *= sy;
}
if let Some(t) = sh.text.as_mut() {
deckcraft_model::edit::format_all(t, &|r| {
if let Some(sz) = r.size.as_mut() {
*sz = (*sz * k).max(1.0);
}
});
}
}
}
fn slide_size(s: &mut Session, p: &Value) -> Result<Value> {
let size = if let Some(pre) = str_param(p, "preset") {
let k = pre.to_ascii_lowercase();
let found = defaults::SLIDE_SIZES.iter().find(|(l, _, _)| l.to_ascii_lowercase().starts_with(&k) || l.to_ascii_lowercase().contains(&k));
let (_, w, h) = found.ok_or_else(|| bad("design.slideSize", format!("unknown preset `{pre}`")))?;
Size::new(*w, *h)
} else {
Size::new(
f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(72.0, 4032.0),
f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(72.0, 4032.0),
)
};
let mode = str_param(p, "scale").unwrap_or("ensureFit").to_string();
s.edit(|doc, _| {
let old = doc.slide_size;
let (sx, sy) = (size.width / old.width.max(1.0), size.height / old.height.max(1.0));
let (sx, sy, k, ox, oy) = match mode.as_str() {
"none" => (1.0, 1.0, 1.0, 0.0, 0.0),
"maximize" => {
let k = sx.max(sy);
(k, k, k, (size.width - old.width * k) / 2.0, (size.height - old.height * k) / 2.0)
}
_ => {
let k = sx.min(sy);
(k, k, k, (size.width - old.width * k) / 2.0, (size.height - old.height * k) / 2.0)
}
};
// Masters and layouts stretch to the new size; slides scale by mode.
let (msx, msy) = (size.width / old.width.max(1.0), size.height / old.height.max(1.0));
for m in &mut doc.masters {
let m = Arc::make_mut(m);
scale_shapes(&mut m.shapes, msx, msy, 1.0, 0.0, 0.0);
for l in &mut m.layouts {
scale_shapes(&mut l.shapes, msx, msy, 1.0, 0.0, 0.0);
}
}
for sl in &mut doc.slides {
scale_shapes(&mut Arc::make_mut(sl).shapes, sx, sy, k, ox, oy);
}
doc.slide_size = size;
Ok(())
})?;
Ok(json!({"w": size.width, "h": size.height}))
}
fn header_footer(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(|doc, sel| {
let hf = &mut doc.header_footer;
if let Some(v) = bool_param(p, "date") {
hf.date = v;
}
if let Some(v) = str_param(p, "dateText") {
hf.date_text = v.into();
}
if let Some(v) = bool_param(p, "slideNumber") {
hf.slide_number = v;
}
if let Some(v) = bool_param(p, "footer") {
hf.footer = v;
}
if let Some(v) = str_param(p, "footerText") {
hf.footer_text = v.into();
hf.footer = hf.footer || !v.is_empty();
}
if let Some(v) = bool_param(p, "hideOnTitle") {
hf.hide_on_title = v;
}
let hf = hf.clone();
let date_given = str_param(p, "dateText").is_some();
let all = bool_or(p, "all", true);
let list: Vec<usize> = if all { (0..doc.slides.len()).collect() } else { vec![sel.slide] };
for i in list {
let Some(layout) = doc.slides.get(i).map(|x| x.layout) else { continue };
let lay = doc.layout(layout).map(|(_, l)| l.clone());
let is_title = lay.as_ref().is_some_and(|l| l.kind == deckcraft_model::LayoutType::Title);
let want = |k: PhType| {
!(hf.hide_on_title && is_title)
&& match k {
PhType::Date => hf.date,
PhType::SlideNum => hf.slide_number,
PhType::Footer => hf.footer,
_ => false,
}
};
let mut new_ids = vec![];
for _ in 0..3 {
new_ids.push(ShapeId(doc.alloc_id()));
}
let Some(sl) = doc.slides.get_mut(i) else { continue };
let sl = Arc::make_mut(sl);
for (n, k) in [PhType::Date, PhType::Footer, PhType::SlideNum].into_iter().enumerate() {
let has = sl.shapes.iter().position(|x| x.ph_type() == Some(k));
match (has, want(k)) {
(Some(pos), false) => {
sl.shapes.remove(pos);
}
(None, true) => {
let lp = lay.as_ref().and_then(|l| l.shapes.iter().find(|x| x.ph_type() == Some(k)).cloned());
let Some(lp) = lp else { continue };
let body = match k {
PhType::SlideNum => TextBody {
paragraphs: vec![deckcraft_model::Paragraph {
runs: vec![Run {
text: "‹#›".into(),
props: Default::default(),
kind: RunKind::Field { field: "slidenum".into() },
}],
..Default::default()
}],
..Default::default()
},
PhType::Date if hf.date_text.is_empty() => TextBody {
paragraphs: vec![deckcraft_model::Paragraph {
runs: vec![Run { text: today(), props: Default::default(), kind: RunKind::Field { field: "datetime1".into() } }],
..Default::default()
}],
..Default::default()
},
PhType::Date => TextBody::from_text(&hf.date_text),
_ => TextBody::from_text(&hf.footer_text),
};
sl.shapes.push(Shape {
id: new_ids.get(n).copied().unwrap_or_default(),
name: lp.name.clone(),
ph: lp.ph.clone(),
text: Some(body),
..Default::default()
});
}
(Some(pos), true) if k == PhType::Footer => {
if let Some(sh) = sl.shapes.get_mut(pos) {
sh.text = Some(TextBody::from_text(&hf.footer_text));
}
}
(Some(pos), true) if k == PhType::Date && date_given => {
if let Some(sh) = sl.shapes.get_mut(pos) {
set_date(sh, &hf.date_text);
}
}
_ => {}
}
}
}
Ok(())
})?;
ok()
}
/// Point a slide's date placeholder at a fixed date (its own plain text) or, for an empty
/// `fixed`, at an automatic date field (one it already has keeps its format).
fn set_date(sh: &mut Shape, fixed: &str) {
let runs = || sh.text.iter().flat_map(|t| &t.paragraphs).flat_map(|p| &p.runs);
let has_field = runs().any(|r| matches!(&r.kind, RunKind::Field { field } if deckcraft_text::datetime::is_date_field(field)));
let props = runs().next().map(|r| r.props.clone()).unwrap_or_default();
let (text, kind) = match fixed {
"" if has_field => return,
"" => (today(), RunKind::Field { field: "datetime1".into() }),
_ if !has_field && sh.text.as_ref().is_some_and(|t| t.text() == fixed) => return,
_ => (fixed.to_string(), RunKind::Text),
};
let para = deckcraft_model::Paragraph { runs: vec![Run { text, props, kind }], ..Default::default() };
sh.text = Some(TextBody { paragraphs: vec![para], ..sh.text.clone().unwrap_or_default() });
}
/// Today's local date as a `datetime1` field shows it (M/D/YYYY): the saved text of a new date
/// field. Empty where there is no clock (wasm).
pub fn today() -> String {
date_field_text("datetime1")
}
/// What date field `kind` shows now (empty if unknown or there is no clock).
pub fn date_field_text(kind: &str) -> String {
use deckcraft_text::datetime::{DateTime, field_text};
DateTime::now_local().and_then(|now| field_text(kind, None, now)).unwrap_or_default()
}
/// Days since 1970-01-01 → (year, month, day) (Howard Hinnant's algorithm).
pub fn civil(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
fn master_view(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let mi = usize_param(p, "master").unwrap_or_else(|| master_index(&st.doc, &st.selection));
let layout = usize_param(p, "layout")
.or_else(|| st.current_slide().and_then(|sl| st.doc.masters.get(mi).and_then(|m| m.layouts.iter().position(|l| l.id == sl.layout))));
let target = match layout {
Some(l) => Target::Layout { master: mi, layout: l },
None => Target::Master { master: mi },
};
s.select(|_, sel| {
sel.target = target;
sel.shapes.clear();
sel.text = None;
})?;
Ok(serde_json::to_value(target).unwrap_or_default())
}
fn close_master(s: &mut Session, _p: &Value) -> Result<Value> {
s.select(|_, sel| {
sel.target = Target::Slides;
sel.shapes.clear();
sel.text = None;
})?;
ok()
}
fn insert_layout(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").unwrap_or("Custom Layout").to_string();
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
let id = deckcraft_model::LayoutId(doc.alloc_id());
let tid = ShapeId(doc.alloc_id());
let size = doc.slide_size;
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("master.insertLayout", "no master"))?);
let title = m.shapes.iter().find(|x| x.ph_type() == Some(PhType::Title)).cloned().map(|mut t| {
t.id = tid;
t.text = Some(TextBody::default());
t
});
let _ = size;
let at = match sel.target {
Target::Layout { layout, .. } => layout + 1,
_ => m.layouts.len(),
};
m.layouts.insert(
at.min(m.layouts.len()),
deckcraft_model::Layout {
id,
name,
kind: deckcraft_model::LayoutType::Custom,
shapes: title.into_iter().collect(),
background: None,
show_master_shapes: true,
preserve: true,
color_map: None,
raw_ext: None,
},
);
sel.target = Target::Layout { master: mi, layout: at.min(m.layouts.len().saturating_sub(1)) };
Ok(json!({"id": id}))
})
}
fn layout_target(s: &Session, p: &Value) -> Result<(usize, usize)> {
let st = s.doc()?;
let (m, l) = match st.selection.target {
Target::Layout { master, layout } => (master, layout),
_ => (master_index(&st.doc, &st.selection), 0),
};
Ok((usize_param(p, "master").unwrap_or(m), usize_param(p, "layout").unwrap_or(l)))
}
fn rename_layout(s: &mut Session, p: &Value) -> Result<Value> {
let (mi, li) = layout_target(s, p)?;
let name = str_param(p, "name").ok_or_else(|| bad("master.renameLayout", "missing `name`"))?.to_string();
s.edit(|doc, _| {
let l =
doc.masters.get_mut(mi).and_then(|m| Arc::make_mut(m).layouts.get_mut(li)).ok_or_else(|| bad("master.renameLayout", "no such layout"))?;
l.name = name;
Ok(())
})?;
ok()
}
fn delete_layout(s: &mut Session, p: &Value) -> Result<Value> {
let (mi, li) = layout_target(s, p)?;
s.edit(|doc, sel| {
let id = doc.masters.get(mi).and_then(|m| m.layouts.get(li)).map(|l| l.id).ok_or_else(|| bad("master.deleteLayout", "no such layout"))?;
if doc.slides.iter().any(|x| x.layout == id) {
return Err(bad("master.deleteLayout", "slides use this layout"));
}
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("master.deleteLayout", "no master"))?);
if m.layouts.len() <= 1 {
return Err(bad("master.deleteLayout", "a master needs at least one layout"));
}
m.layouts.remove(li);
sel.target = Target::Layout { master: mi, layout: li.min(m.layouts.len().saturating_sub(1)) };
Ok(())
})?;
ok()
}
fn insert_placeholder(s: &mut Session, p: &Value) -> Result<Value> {
let kind = match str_param(p, "kind").unwrap_or("content") {
"text" => PhType::Body,
"picture" => PhType::Picture,
"chart" => PhType::Chart,
"table" => PhType::Table,
"media" => PhType::Media,
_ => PhType::Obj,
};
if !matches!(s.doc()?.selection.target, Target::Layout { .. }) {
return Err(bad("master.insertPlaceholder", "select a layout in Slide Master view"));
}
let size = s.doc()?.doc.slide_size;
let rect = rect_param(p, "rect").unwrap_or(deckcraft_geom::Xfrm::new(size.width * 0.25, size.height * 0.3, size.width * 0.5, size.height * 0.4));
let idx = s.doc()?.shapes().iter().filter_map(|x| x.ph.as_ref().map(|p| p.idx)).max().unwrap_or(0) + 1;
let shape = Shape {
xfrm: Some(rect),
ph: Some(deckcraft_model::Placeholder { kind, idx, ..Default::default() }),
text: Some(TextBody::default()),
..Default::default()
};
let id = super::insert::add_shape(s, shape, true)?;
Ok(json!({"id": id}))
}
#[cfg(test)]
mod browse_theme_tests;
mod tests {
#[test]
fn civil_dates() {
assert_eq!(super::civil(0), (1970, 1, 1));
assert_eq!(super::civil(20_734), (2026, 10, 8));
}
}
@@ -1,291 +0,0 @@
use std::sync::Arc;
use deckcraft_model::text::RunKind;
use deckcraft_model::{Background, Fill, PhType};
use serde_json::json;
use crate::{Session, Target};
#[test]
fn applies_the_theme_of_another_deck_and_undoes() {
let mut other = Session::with_new();
other.execute("design.fonts", &json!({"major": "Lato", "minor": "Source Sans 3"})).unwrap();
other.execute("design.colors", &json!({"colors": {"accent1": "#123456"}})).unwrap();
let data = other.execute("file.saveBytes", &json!({"format": "pptx"})).unwrap()["data"].as_str().unwrap().to_string();
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "titleAndContent", "title": "T", "body": "B"})).unwrap();
let before = s.doc().unwrap().doc.masters[0].theme.clone();
s.execute("design.browseTheme", &json!({"name": "Brand.pptx", "data": data})).unwrap();
let t = &s.doc().unwrap().doc.masters[0].theme;
assert_eq!(t.fonts.major.latin, "Lato");
assert_eq!(t.fonts.minor.latin, "Source Sans 3");
assert_eq!(t.colors.get(deckcraft_color::SchemeSlot::Accent1).hex().to_lowercase(), "123456");
assert!(s.doc().unwrap().doc.validate().is_empty());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.masters[0].theme, before);
assert!(s.execute("design.browseTheme", &json!({"data": "AAAA"})).is_err());
assert!(s.execute("design.browseTheme", &json!({})).is_err());
}
/// A 4:3 brand template: a logo and a background on the master, its layouts renamed (so slides
/// can only find them by kind) and its content layout's title moved.
fn brand_template() -> (String, Vec<u8>, deckcraft_model::Xfrm) {
let mut img = image::RgbaImage::new(2, 2);
img.put_pixel(0, 0, image::Rgba([200, 20, 30, 255]));
let mut logo = Vec::new();
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut logo), image::ImageFormat::Png).unwrap();
let mut t = Session::with_new();
t.execute("design.slideSize", &json!({"preset": "standard", "scale": "none"})).unwrap();
let title = t
.edit(|doc, _| {
let media = doc.add_media("logo.png", "image/png", logo.clone()).unwrap();
let id = deckcraft_model::ShapeId(doc.alloc_id().unwrap());
let m = Arc::make_mut(doc.masters.get_mut(0).unwrap());
m.shapes.push(deckcraft_model::Shape {
id,
name: "Logo".into(),
kind: deckcraft_model::ShapeKind::Picture { fill: deckcraft_model::style::PictureFill { media, ..Default::default() } },
xfrm: Some(deckcraft_model::Xfrm { x: 600.0, y: 20.0, w: 100.0, h: 40.0, ..Default::default() }),
..Default::default()
});
m.background = Some(Background::Fill { fill: Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(0x0A, 0x2B, 0x4C))) });
for l in &mut m.layouts {
l.name = format!("Brand {}", l.name);
}
let obj = m.layouts.iter_mut().find(|l| l.kind == deckcraft_model::LayoutType::TitleAndContent).unwrap();
let title = obj.shapes.iter_mut().find(|sh| sh.ph_type().is_some_and(PhType::is_title)).unwrap();
let x = deckcraft_model::Xfrm { x: 72.0, y: 400.0, w: 576.0, h: 80.0, ..Default::default() };
title.xfrm = Some(x);
Ok(x)
})
.unwrap();
(crate::cmd::base64_encode(&deckcraft_pptx::export_as(&t.doc().unwrap().doc, "potx").unwrap()), logo, title)
}
#[test]
fn a_template_brings_its_master_and_layouts_and_slides_follow() {
let (data, logo, title) = brand_template();
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "titleAndContent", "title": "Agenda", "body": "Point one"})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = undo_len(&s);
let r = s.execute("design.browseTheme", &json!({"name": "Brand.potx", "data": data})).unwrap();
assert_eq!(r["slides"], json!(2), "{r}");
assert_eq!(undo_len(&s), n + 1, "one undo step");
let doc = &s.doc().unwrap().doc;
assert!(doc.validate().is_empty(), "{:?}", doc.validate());
assert_eq!(doc.masters.len(), 1, "the old master is replaced");
let m = &doc.masters[0];
assert_ne!(m.id, before.masters[0].id);
assert!(m.layouts.iter().all(|l| l.name.starts_with("Brand ")));
assert!(matches!(m.background, Some(Background::Fill { fill: Fill::Solid { .. } })));
let pic = m.shapes.iter().find(|sh| sh.name == "Logo").expect("the master's logo comes along");
let deckcraft_model::ShapeKind::Picture { fill } = &pic.kind else { panic!("logo is a picture") };
assert_eq!(doc.media(fill.media).map(|m| m.data.as_ref().clone()), Some(logo));
// The 4:3 master stretches to this deck's 16:9.
let k = doc.slide_size.width / 720.0;
let px = pic.xfrm.unwrap();
assert!((px.x - 600.0 * k).abs() < 0.01 && (px.w - 100.0 * k).abs() < 0.01 && (px.y - 20.0).abs() < 0.01, "{px:?}");
// Each slide moved to the brand layout of its kind, and kept its text.
for (old, new) in before.slides.iter().zip(&doc.slides) {
let (_, was) = before.layout(old.layout).unwrap();
let (owner, now) = doc.layout(new.layout).expect("on a layout of the new master");
assert_eq!(owner.id, m.id);
assert_eq!(now.kind, was.kind);
}
let agenda = doc.slides.iter().find(|sl| sl.shapes.iter().any(|sh| sh.text.as_ref().is_some_and(|t| t.text() == "Agenda"))).unwrap();
assert!(agenda.shapes.iter().any(|sh| sh.text.as_ref().is_some_and(|t| t.text() == "Point one")));
let (_, lay) = doc.layout(agenda.layout).unwrap();
let lt = lay.shapes.iter().find(|sh| sh.ph_type().is_some_and(PhType::is_title)).unwrap().xfrm.unwrap();
assert!((lt.x - title.x * k).abs() < 0.01 && (lt.y - title.y).abs() < 0.01, "{lt:?}");
let st = agenda.shapes.iter().find(|sh| sh.ph_type().is_some_and(PhType::is_title)).unwrap();
assert!(st.xfrm.is_none(), "the slide title follows the new layout");
s.execute("edit.undo", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.masters, before.masters);
assert_eq!(doc.slides, before.slides);
}
#[test]
fn a_preserved_master_stays_beside_the_template() {
let (data, _, _) = brand_template();
let mut s = Session::with_new();
s.execute("view.slideMaster", &json!({"master": 0, "layout": 1})).unwrap();
s.execute("master.preserve", &json!({"preserve": true})).unwrap();
s.execute("view.slideMaster", &json!({"master": 0})).unwrap();
s.execute("master.preserve", &json!({"preserve": true})).unwrap();
let old = s.doc().unwrap().doc.masters[0].id;
s.execute("view.slideMaster", &json!({"master": 0, "layout": 1})).unwrap();
s.execute("design.browseTheme", &json!({"name": "Brand.pptx", "data": data})).unwrap();
let st = s.doc().unwrap();
assert_eq!(st.doc.masters.len(), 2);
assert_eq!(st.doc.masters[1].id, old);
assert_eq!(st.selection.target, Target::Master { master: 0 }, "Slide Master view shows the new master");
let new = &st.doc.masters[0];
assert!(st.doc.slides.iter().all(|sl| new.layout(sl.layout).is_some()));
}
fn undo_len(s: &crate::Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn effect_scheme_replaces_format_and_keeps_colours_and_fonts() {
let mut s = crate::Session::with_new();
let listed = s.execute("design.themes", &json!({})).unwrap();
let names: Vec<String> = listed["effectSchemes"].as_array().unwrap().iter().filter_map(|v| v.as_str().map(str::to_string)).collect();
assert_eq!(names, ["DeckCraft", "Soft", "Crisp", "Lift", "Glow", "Plain"]);
let n = undo_len(&s);
s.execute("design.effects", &json!({"name": "DeckCraft"})).unwrap();
assert_eq!(undo_len(&s), n, "the scheme already on the theme is not an undo step");
let err = s.execute("design.effects", &json!({"name": "Office"})).unwrap_err().to_string();
assert!(err.contains("no effect scheme"), "{err}");
assert!(s.execute("design.effects", &json!({})).is_err());
assert_eq!(undo_len(&s), n);
s.execute("design.theme", &json!({"name": "Harbor"})).unwrap();
let before = s.doc().unwrap().doc.masters[0].theme.clone();
s.execute("design.effects", &json!({"name": "soft"})).unwrap();
let theme = s.doc().unwrap().doc.masters[0].theme.clone();
assert_eq!(theme.name, "Harbor");
assert_eq!(theme.colors, before.colors);
assert_eq!(theme.fonts, before.fonts);
assert_eq!(theme.format.name, "Soft");
assert!(theme.format.effects[0].outer_shadow.is_some());
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Effects");
let n = undo_len(&s);
s.execute("design.effects", &json!({"name": "Soft"})).unwrap();
assert_eq!(undo_len(&s), n, "the same scheme is not an undo step");
s.execute("design.effects", &json!({"name": "Glow"})).unwrap();
let glow = s.doc().unwrap().doc.masters[0].theme.format.effects[2].glow.clone();
assert!(glow.is_some_and(|g| (g.radius - 12.0).abs() < 1e-6));
s.execute("design.effects", &json!({"name": "Plain"})).unwrap();
let plain = s.doc().unwrap().doc.masters[0].theme.format.clone();
assert!(plain.effects.iter().all(|e| e.outer_shadow.is_none() && e.glow.is_none()));
assert_eq!(plain.lines[2].width, Some(0.75));
}
fn shapes(s: &Session) -> Vec<deckcraft_model::Shape> {
s.doc().unwrap().shapes().to_vec()
}
fn has_title(s: &Session) -> bool {
shapes(s).iter().any(|sh| sh.ph_type().is_some_and(PhType::is_title))
}
fn has_footers(s: &Session) -> bool {
shapes(s).iter().any(|sh| sh.ph_type().is_some_and(PhType::is_footer_kind))
}
#[test]
fn preserve_and_placeholders_edit_the_open_master_or_layout() {
for id in ["master.preserve", "master.placeholders"] {
assert!(crate::command_specs().iter().any(|c| c.id == id), "{id}");
}
let mut s = Session::with_new();
let blank = s.doc().unwrap().doc.masters[0].layouts.iter().position(|l| l.name == "Blank").unwrap();
s.execute("view.slideMaster", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection.target, Target::Layout { master: 0, layout: 0 });
s.execute("view.slideMaster", &json!({"master": 0})).unwrap();
assert_eq!(s.doc().unwrap().selection.target, Target::Master { master: 0 });
assert!(!s.doc().unwrap().doc.masters[0].preserve);
let n = s.doc().unwrap().history.undo.len();
s.execute("master.preserve", &json!({"preserve": false})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), n, "the same value is not an undo step");
s.execute("master.preserve", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.masters[0].preserve);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Preserve");
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().doc.masters[0].preserve);
s.execute("master.placeholders", &json!({"footers": false})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Layout Placeholders");
assert!(has_title(&s));
assert!(!has_footers(&s));
s.execute("edit.undo", &json!({})).unwrap();
assert!(has_footers(&s));
master_view_closed_rejects(&mut s, blank);
}
fn master_view_closed_rejects(s: &mut Session, blank: usize) {
s.execute("view.closeMaster", &json!({})).unwrap();
let n = s.doc().unwrap().history.undo.len();
let err = s.execute("master.preserve", &json!({})).unwrap_err();
assert!(err.to_string().contains("open Slide Master view"), "{err}");
let err = s.execute("master.placeholders", &json!({"title": true})).unwrap_err();
assert!(err.to_string().contains("open Slide Master view"), "{err}");
let err = s.execute("master.placeholders", &json!({})).unwrap_err();
assert!(err.to_string().contains("give title or footers"), "{err}");
assert_eq!(s.doc().unwrap().history.undo.len(), n);
layout_placeholders_edit_one_undo_step(s, blank);
}
fn layout_placeholders_edit_one_undo_step(s: &mut Session, blank: usize) {
s.execute("view.slideMaster", &json!({"master": 0, "layout": blank})).unwrap();
assert_eq!(s.doc().unwrap().selection.target, Target::Layout { master: 0, layout: blank });
assert!(s.doc().unwrap().doc.masters[0].layouts[blank].preserve);
assert!(!has_title(s));
assert!(has_footers(s));
let n = s.doc().unwrap().history.undo.len();
s.execute("master.placeholders", &json!({"title": false, "footers": true})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), n, "already in that state");
s.execute("master.placeholders", &json!({"title": true, "footers": false})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), n + 1, "both keys are one undo step");
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Layout Placeholders");
assert!(has_title(s));
assert!(!has_footers(s));
let title = shapes(s).into_iter().find(|sh| sh.ph_type().is_some_and(PhType::is_title)).unwrap();
assert_eq!(title.name, "Title 1");
assert_eq!(title.ph.unwrap().idx, 0);
assert!(title.text.unwrap().paragraphs.iter().all(|para| para.runs.is_empty()));
s.execute("edit.undo", &json!({})).unwrap();
assert!(!has_title(s));
assert!(has_footers(s));
s.execute("master.placeholders", &json!({"footers": false})).unwrap();
s.execute("master.placeholders", &json!({"footers": true})).unwrap();
let restored = shapes(s);
assert!(restored.iter().any(|sh| sh.ph_type() == Some(PhType::Date)));
assert!(restored.iter().any(|sh| sh.ph_type() == Some(PhType::Footer)));
let num = restored.iter().find(|sh| sh.ph_type() == Some(PhType::SlideNum)).unwrap();
let run = &num.text.as_ref().unwrap().paragraphs[0].runs[0];
assert_eq!(run.text, "‹#›");
assert!(matches!(&run.kind, RunKind::Field { field } if field == "slidenum"));
assert!(s.doc().unwrap().doc.masters[0].layouts[blank].preserve);
s.execute("master.preserve", &json!({"preserve": false})).unwrap();
assert!(!s.doc().unwrap().doc.masters[0].layouts[blank].preserve);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Preserve");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.masters[0].layouts[blank].preserve);
missing_title_placeholder_is_recreated(s);
}
fn missing_title_placeholder_is_recreated(s: &mut Session) {
s.edit(|doc, _| {
let m = std::sync::Arc::make_mut(doc.masters.get_mut(0).unwrap());
m.shapes.retain(|sh| !sh.ph_type().is_some_and(PhType::is_title));
Ok(())
})
.unwrap();
s.execute("master.placeholders", &json!({"title": true})).unwrap();
let title = shapes(s).into_iter().find(|sh| sh.ph_type() == Some(PhType::Title)).unwrap();
assert_eq!(title.name, "Title");
let box_ = title.xfrm.unwrap();
assert!((box_.x - 60.0).abs() < 0.01 && (box_.y - 29.0).abs() < 0.01);
assert!((box_.w - 840.0).abs() < 0.01 && (box_.h - 104.0).abs() < 0.01);
}
-257
View File
@@ -1,257 +0,0 @@
use super::{
Arc, Result, Session, Value, bad, builtin_color_schemes, builtin_font_schemes, builtin_format_schemes, json, master_index, ok, str_param,
};
pub(super) fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let name_v = p.get("name");
let colors_v = p.get("colors");
if name_v.is_none() && colors_v.is_none() {
let sc = current_colors(s)?;
s.ui_requests.push(crate::UiRequest::Dialog { id: "themeColors".into(), params: scheme_dialog_params(&sc) });
return ok();
}
let given = match name_v {
None => None,
Some(Value::String(n)) => {
let n = n.trim();
if n.is_empty() {
return Err(bad("design.colors", "name is empty"));
}
Some(n.to_string())
}
Some(_) => return Err(bad("design.colors", "`name` must be a string")),
};
let slots = parse_color_slots(colors_v)?;
let current = current_colors(s)?;
let next = next_scheme(&current, given.as_deref(), slots.as_deref())?;
if next == current {
return ok();
}
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("design.colors", "no master"))?);
m.theme.colors = next;
Ok(())
})?;
ok()
}
pub(super) fn variant(s: &mut Session, p: &Value) -> Result<Value> {
let index = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("design.variant", "missing `index` (0..3)"))? as usize;
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("design.variant", "no master"))?);
let v = deckcraft_model::theme::theme_variants(&m.theme);
m.theme.colors =
v.get(index).cloned().ok_or_else(|| bad("design.variant", format!("no variant {index}; 0..{}", v.len().saturating_sub(1))))?;
Ok(())
})?;
Ok(json!({"variant": index}))
}
pub(super) fn variants(s: &mut Session, _p: &Value) -> Result<Value> {
let st = s.doc()?;
let mi = master_index(&st.doc, &st.selection);
let th = st.doc.masters.get(mi).map(|m| m.theme.clone()).unwrap_or_default();
let v = deckcraft_model::theme::theme_variants(&th);
let current = v.iter().position(|c| c.colors == th.colors.colors);
Ok(json!({
"theme": th.name,
"current": current,
"variants": v.iter().map(|c| json!({"name": c.name, "colors": c.colors.iter().map(|x| format!("#{}", x.hex())).collect::<Vec<_>>()})).collect::<Vec<_>>(),
}))
}
fn current_colors(s: &Session) -> Result<deckcraft_color::ColorScheme> {
let st = s.doc()?;
let mi = master_index(&st.doc, &st.selection);
st.doc.masters.get(mi).map(|m| m.theme.colors.clone()).ok_or_else(|| bad("design.colors", "no master"))
}
fn scheme_dialog_params(sc: &deckcraft_color::ColorScheme) -> Value {
let mut colors = serde_json::Map::new();
for slot in deckcraft_color::SchemeSlot::THEME {
colors.insert(slot.xml_name().to_string(), Value::String(format!("#{}", sc.get(slot).hex())));
}
json!({"name": sc.name, "colors": colors})
}
/// `None` when the key is absent. Present values must be the twelve stored slots; aliases such
/// as `bg1` are rejected because `ColorScheme::set` ignores them.
fn parse_color_slots(colors_v: Option<&Value>) -> Result<Option<Vec<(deckcraft_color::SchemeSlot, deckcraft_color::Rgba)>>> {
let Some(v) = colors_v else { return Ok(None) };
let Some(map) = v.as_object() else {
return Err(bad("design.colors", "`colors` must be an object"));
};
if map.is_empty() {
return Err(bad("design.colors", "`colors` is empty"));
}
let mut slots = Vec::with_capacity(map.len());
for (k, v) in map {
let Some(slot) = deckcraft_color::SchemeSlot::from_xml(k) else {
return Err(bad("design.colors", format!("unknown colour `{k}`")));
};
if !deckcraft_color::SchemeSlot::THEME.contains(&slot) {
return Err(bad("design.colors", format!("`{k}` is not a theme colour")));
}
let Some(rgb) = v.as_str().and_then(deckcraft_color::Rgba::from_hex) else {
return Err(bad("design.colors", format!("`{k}` needs a colour like #RRGGBB")));
};
slots.push((slot, rgb));
}
Ok(Some(slots))
}
/// A builtin `name` is applied first, then `colors` overlays those slots. The stored scheme name
/// is the given name, or `Custom` when only colours are sent. An unknown name without colours is an error.
fn next_scheme(
current: &deckcraft_color::ColorScheme,
given: Option<&str>,
slots: Option<&[(deckcraft_color::SchemeSlot, deckcraft_color::Rgba)]>,
) -> Result<deckcraft_color::ColorScheme> {
let mut next = current.clone();
if let Some(name) = given {
if let Some(builtin) = builtin_color_schemes().into_iter().find(|c| c.name.eq_ignore_ascii_case(name)) {
next = builtin;
} else if slots.is_none() {
return Err(bad("design.colors", format!("no colour scheme `{name}`")));
}
next.name = name.to_string();
}
if let Some(changes) = slots {
for (slot, rgb) in changes {
next.set(*slot, *rgb);
}
if given.is_none() {
next.name = "Custom".into();
}
}
Ok(next)
}
pub(super) fn fonts(s: &mut Session, p: &Value) -> Result<Value> {
let name_v = p.get("name");
let major_v = p.get("major");
let minor_v = p.get("minor");
if name_v.is_none() && major_v.is_none() && minor_v.is_none() {
let scheme = current_fonts(s)?;
s.ui_requests.push(crate::UiRequest::Dialog { id: "themeFonts".into(), params: font_dialog_params(&scheme) });
return ok();
}
let given = match name_v {
None => None,
Some(Value::String(n)) => {
let n = n.trim();
if n.is_empty() {
return Err(bad("design.fonts", "name is empty"));
}
Some(n.to_string())
}
Some(_) => return Err(bad("design.fonts", "`name` must be a string")),
};
let major = face_param("major", major_v)?;
let minor = face_param("minor", minor_v)?;
let current = current_fonts(s)?;
let next = next_font_scheme(&current, given.as_deref(), major.as_deref(), minor.as_deref())?;
if next == current {
return ok();
}
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("design.fonts", "no master"))?).theme.fonts = next;
Ok(())
})?;
ok()
}
fn current_fonts(s: &Session) -> Result<deckcraft_model::theme::FontScheme> {
let st = s.doc()?;
let mi = master_index(&st.doc, &st.selection);
st.doc.masters.get(mi).map(|m| m.theme.fonts.clone()).ok_or_else(|| bad("design.fonts", "no master"))
}
fn font_dialog_params(scheme: &deckcraft_model::theme::FontScheme) -> Value {
json!({"name": scheme.name, "major": scheme.major.latin, "minor": scheme.minor.latin})
}
/// `None` when the key is absent. A present face must be a non-blank string.
fn face_param(key: &str, v: Option<&Value>) -> Result<Option<String>> {
match v {
None => Ok(None),
Some(Value::String(s)) => {
let s = s.trim();
if s.is_empty() { Err(bad("design.fonts", format!("`{key}` is empty"))) } else { Ok(Some(s.to_string())) }
}
Some(_) => Err(bad("design.fonts", format!("`{key}` must be a string"))),
}
}
/// A builtin `name` is applied first, then `major` / `minor` replace only the latin faces (East
/// Asian, complex-script and per-script slots stay). The stored name is the given string when
/// faces are overlaid or the name is not a builtin; a name-only builtin keeps its own name.
/// Faces without a name are a custom scheme: an omitted `minor` copies `major`.
fn next_font_scheme(
current: &deckcraft_model::theme::FontScheme,
given: Option<&str>,
major: Option<&str>,
minor: Option<&str>,
) -> Result<deckcraft_model::theme::FontScheme> {
let mut next = current.clone();
if let Some(name) = given {
let replaced = if let Some(builtin) = builtin_font_schemes().into_iter().find(|f| f.name.eq_ignore_ascii_case(name)) {
next = builtin;
true
} else {
false
};
if !replaced && major.is_none() && minor.is_none() {
return Err(bad("design.fonts", format!("no font scheme `{name}`")));
}
if major.is_some() || minor.is_some() || !replaced {
next.name = name.to_string();
}
}
if given.is_none() {
if let Some(face) = major {
next.major.latin = face.to_string();
if minor.is_none() {
next.minor.latin = face.to_string();
}
}
if let Some(face) = minor {
next.minor.latin = face.to_string();
}
next.name = "Custom".into();
} else {
if let Some(face) = major {
next.major.latin = face.to_string();
}
if let Some(face) = minor {
next.minor.latin = face.to_string();
}
}
Ok(next)
}
pub(super) fn effects(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("design.effects", "missing `name`"))?;
let scheme = builtin_format_schemes()
.into_iter()
.find(|f| f.name.eq_ignore_ascii_case(name))
.ok_or_else(|| bad("design.effects", format!("no effect scheme `{name}`")))?;
let stored = scheme.name.clone();
let same = {
let st = s.doc()?;
let mi = master_index(&st.doc, &st.selection);
st.doc.masters.get(mi).is_some_and(|m| m.theme.format == scheme)
};
if same {
return Ok(json!({"name": stored}));
}
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("design.effects", "no master"))?).theme.format = scheme;
Ok(())
})?;
Ok(json!({"name": stored}))
}
-501
View File
@@ -1,501 +0,0 @@
use super::{
Arc, Fill, NO_ID_SPACE, PhType, Result, Run, RunKind, Session, Shape, ShapeId, Size, Target, TextBody, Value, bad, bool_param, json,
master_index, ok, opt_usize_param, rect_param, str_param,
};
pub(super) fn master_view(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let mi = opt_usize_param(p, "master", "view.slideMaster")?.unwrap_or_else(|| master_index(&st.doc, &st.selection));
// A master thumbnail sends `{master}` and means the master itself. `{master, layout}` selects
// that layout. With neither key, follow the current slide's layout.
let layout = if p.get("master").is_some() && p.get("layout").is_none() {
None
} else {
opt_usize_param(p, "layout", "view.slideMaster")?
.or_else(|| st.current_slide().and_then(|sl| st.doc.masters.get(mi).and_then(|m| m.layouts.iter().position(|l| l.id == sl.layout))))
};
let target = match layout {
Some(l) => Target::Layout { master: mi, layout: l },
None => Target::Master { master: mi },
};
s.select(|_, sel| {
sel.target = target;
sel.shapes.clear();
sel.text = None;
})?;
Ok(serde_json::to_value(target).unwrap_or_default())
}
pub(super) fn in_handout(s: &Session) -> std::result::Result<(), String> {
if s.active().is_some_and(|d| d.selection.target == Target::Handout) { Ok(()) } else { Err("open View ▸ Handout Master first".into()) }
}
/// The four handout-master placeholders PowerPoint offers, in a page of `size`.
pub fn handout_placeholder(kind: PhType, size: Size, id: ShapeId) -> Shape {
let (w, h) = (size.width, size.height);
let (name, idx, x, y) = match kind {
PhType::Header => ("Header Placeholder", 0, 0.0, 0.0),
PhType::Date => ("Date Placeholder", 1, w * 0.57, 0.0),
PhType::Footer => ("Footer Placeholder", 2, 0.0, h * 0.95),
_ => ("Slide Number Placeholder", 3, w * 0.57, h * 0.95),
};
let mut text = TextBody::default();
if let Some(p) = text.paragraphs.first_mut()
&& matches!(kind, PhType::Date | PhType::SlideNum)
{
p.props.align = Some(deckcraft_model::text::Align::Right);
}
Shape {
id,
name: format!("{name} {}", idx + 1),
xfrm: Some(deckcraft_geom::Xfrm::new(x, y, w * 0.43, h * 0.05)),
ph: Some(deckcraft_model::Placeholder { kind, idx, size: Some("quarter".into()), ..Default::default() }),
text: Some(text),
..Default::default()
}
}
const HANDOUT_KINDS: [(&str, PhType); 4] =
[("header", PhType::Header), ("date", PhType::Date), ("footer", PhType::Footer), ("pageNumber", PhType::SlideNum)];
pub(super) fn handout_view(s: &mut Session, _p: &Value) -> Result<Value> {
let created = s.doc()?.doc.handout_master.is_none();
if created {
s.edit(|doc, _| {
let mut m = deckcraft_model::Master {
name: "Handout Master".into(),
theme: doc.masters.first().map(|m| m.theme.clone()).unwrap_or_default(),
color_map: doc.masters.first().map(|m| m.color_map.clone()).unwrap_or_default(),
..Default::default()
};
let size = doc.notes_size;
for (_, k) in HANDOUT_KINDS {
let id = ShapeId(doc.alloc_id().ok_or_else(|| bad("view.handoutMaster", NO_ID_SPACE))?);
m.shapes.push(handout_placeholder(k, size, id));
}
doc.handout_master = Some(Arc::new(m));
Ok(())
})?;
}
s.select(|_, sel| {
sel.target = Target::Handout;
sel.shapes.clear();
sel.text = None;
})?;
Ok(json!({"created": created}))
}
pub(super) fn handout_placeholders(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(|doc, _| {
let size = doc.notes_size;
let mut ids = vec![];
for (key, _) in HANDOUT_KINDS {
let id = match p.get(key).and_then(Value::as_bool) {
Some(_) => Some(ShapeId(doc.alloc_id().ok_or_else(|| bad("handout.placeholders", NO_ID_SPACE))?)),
None => None,
};
ids.push(id);
}
let m = Arc::make_mut(doc.handout_master.as_mut().ok_or_else(|| bad("handout.placeholders", "no handout master"))?);
for ((key, kind), id) in HANDOUT_KINDS.into_iter().zip(ids) {
let (Some(on), Some(id)) = (p.get(key).and_then(Value::as_bool), id) else { continue };
let has = m.shapes.iter().any(|x| x.ph_type() == Some(kind));
if on && !has {
m.shapes.push(handout_placeholder(kind, size, id));
} else if !on {
m.shapes.retain(|x| x.ph_type() != Some(kind));
}
}
Ok(())
})?;
let m = s.doc()?.doc.handout_master.clone();
let shown = |k: PhType| m.as_ref().is_some_and(|m| m.shapes.iter().any(|x| x.ph_type() == Some(k)));
Ok(json!({"header": shown(PhType::Header), "date": shown(PhType::Date), "footer": shown(PhType::Footer), "pageNumber": shown(PhType::SlideNum)}))
}
pub(super) fn in_notes_master(s: &Session) -> std::result::Result<(), String> {
if s.active().is_some_and(|d| d.selection.target == Target::NotesMaster) { Ok(()) } else { Err("open View ▸ Notes Master first".into()) }
}
const NOTES_KINDS: [(&str, PhType); 6] = [
("header", PhType::Header),
("date", PhType::Date),
("slideImage", PhType::SlideImage),
("body", PhType::Body),
("footer", PhType::Footer),
("pageNumber", PhType::SlideNum),
];
/// A notes-master placeholder in a page of `size`, laid out as PowerPoint's default notes master.
pub fn notes_placeholder(kind: PhType, size: Size, id: ShapeId) -> Shape {
let (w, h) = (size.width, size.height);
match kind {
PhType::SlideImage => Shape {
id,
name: "Slide Image Placeholder 3".into(),
xfrm: Some(deckcraft_geom::Xfrm::new(w * 0.125, h * 0.125, w * 0.75, h * 0.375)),
ph: Some(deckcraft_model::Placeholder { kind, idx: 2, ..Default::default() }),
fill: Some(Fill::None),
line: Some(deckcraft_model::Line::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::BLACK), 1.0)),
..Default::default()
},
PhType::Body => {
let mut text = TextBody::default();
text.paragraphs = vec![deckcraft_model::text::Paragraph::new("Click to edit Master text styles")];
Shape {
id,
name: "Notes Placeholder 4".into(),
xfrm: Some(deckcraft_geom::Xfrm::new(w * 0.1, h * 0.53, w * 0.8, h * 0.36)),
ph: Some(deckcraft_model::Placeholder { kind, idx: 3, size: Some("quarter".into()), ..Default::default() }),
text: Some(text),
..Default::default()
}
}
_ => {
let mut s = handout_placeholder(kind, size, id);
if let Some(ph) = s.ph.as_mut() {
ph.idx = match kind {
PhType::Header => 0,
PhType::Date => 1,
PhType::Footer => 4,
_ => 5,
};
}
s
}
}
}
pub(super) fn notes_view(s: &mut Session, _p: &Value) -> Result<Value> {
let created = s.doc()?.doc.notes_master.as_ref().is_none_or(|m| m.shapes.is_empty());
if created {
s.edit(|doc, _| {
let mut m = doc.notes_master.as_deref().cloned().unwrap_or_else(|| deckcraft_model::Master {
name: "Notes Master".into(),
theme: doc.masters.first().map(|m| m.theme.clone()).unwrap_or_default(),
color_map: doc.masters.first().map(|m| m.color_map.clone()).unwrap_or_default(),
..Default::default()
});
let size = doc.notes_size;
for (_, k) in NOTES_KINDS {
let id = ShapeId(doc.alloc_id().ok_or_else(|| bad("view.notesMaster", NO_ID_SPACE))?);
m.shapes.push(notes_placeholder(k, size, id));
}
doc.notes_master = Some(Arc::new(m));
Ok(())
})?;
}
s.select(|_, sel| {
sel.target = Target::NotesMaster;
sel.shapes.clear();
sel.text = None;
})?;
Ok(json!({"created": created}))
}
pub(super) fn notes_placeholders(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(|doc, _| {
let size = doc.notes_size;
let ids: Vec<ShapeId> =
NOTES_KINDS.iter().map(|_| doc.alloc_id().map(ShapeId).ok_or_else(|| bad("notes.placeholders", NO_ID_SPACE))).collect::<Result<_>>()?;
let m = Arc::make_mut(doc.notes_master.as_mut().ok_or_else(|| bad("notes.placeholders", "no notes master"))?);
for ((key, kind), id) in NOTES_KINDS.into_iter().zip(ids) {
let Some(on) = p.get(key).and_then(Value::as_bool) else { continue };
let has = m.shapes.iter().any(|x| x.ph_type() == Some(kind));
if on && !has {
m.shapes.push(notes_placeholder(kind, size, id));
} else if !on {
m.shapes.retain(|x| x.ph_type() != Some(kind));
}
}
Ok(())
})?;
let m = s.doc()?.doc.notes_master.clone();
let mut out = serde_json::Map::new();
for (key, kind) in NOTES_KINDS {
out.insert(key.into(), json!(m.as_ref().is_some_and(|m| m.shapes.iter().any(|x| x.ph_type() == Some(kind)))));
}
Ok(Value::Object(out))
}
pub(super) fn close_master(s: &mut Session, _p: &Value) -> Result<Value> {
s.select(|_, sel| {
sel.target = Target::Slides;
sel.shapes.clear();
sel.text = None;
})?;
ok()
}
pub(super) fn insert_layout(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").unwrap_or("Custom Layout").to_string();
s.edit(|doc, sel| {
let mi = master_index(doc, sel);
let id = deckcraft_model::LayoutId(doc.alloc_id().ok_or_else(|| bad("master.insertLayout", NO_ID_SPACE))?);
let tid = ShapeId(doc.alloc_id().ok_or_else(|| bad("master.insertLayout", NO_ID_SPACE))?);
let size = doc.slide_size;
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("master.insertLayout", "no master"))?);
let title = m.shapes.iter().find(|x| x.ph_type() == Some(PhType::Title)).cloned().map(|mut t| {
t.id = tid;
t.text = Some(TextBody::default());
t
});
let _ = size;
let at = match sel.target {
Target::Layout { layout, .. } => layout + 1,
_ => m.layouts.len(),
};
m.layouts.insert(
at.min(m.layouts.len()),
deckcraft_model::Layout {
id,
name,
kind: deckcraft_model::LayoutType::Custom,
shapes: title.into_iter().collect(),
background: None,
show_master_shapes: true,
preserve: true,
color_map: None,
raw_ext: None,
},
);
sel.target = Target::Layout { master: mi, layout: at.min(m.layouts.len().saturating_sub(1)) };
Ok(json!({"id": id}))
})
}
fn layout_target(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
let st = s.doc()?;
let (m, l) = match st.selection.target {
Target::Layout { master, layout } => (master, layout),
_ => (master_index(&st.doc, &st.selection), 0),
};
Ok((opt_usize_param(p, "master", cmd)?.unwrap_or(m), opt_usize_param(p, "layout", cmd)?.unwrap_or(l)))
}
pub(super) fn rename_layout(s: &mut Session, p: &Value) -> Result<Value> {
let (mi, li) = layout_target(s, p, "master.renameLayout")?;
let name = str_param(p, "name").ok_or_else(|| bad("master.renameLayout", "missing `name`"))?.to_string();
s.edit(|doc, _| {
let l =
doc.masters.get_mut(mi).and_then(|m| Arc::make_mut(m).layouts.get_mut(li)).ok_or_else(|| bad("master.renameLayout", "no such layout"))?;
l.name = name;
Ok(())
})?;
ok()
}
pub(super) fn delete_layout(s: &mut Session, p: &Value) -> Result<Value> {
let (mi, li) = layout_target(s, p, "master.deleteLayout")?;
s.edit(|doc, sel| {
let id = doc.masters.get(mi).and_then(|m| m.layouts.get(li)).map(|l| l.id).ok_or_else(|| bad("master.deleteLayout", "no such layout"))?;
if doc.slides.iter().any(|x| x.layout == id) {
return Err(bad("master.deleteLayout", "slides use this layout"));
}
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("master.deleteLayout", "no master"))?);
if m.layouts.len() <= 1 {
return Err(bad("master.deleteLayout", "a master needs at least one layout"));
}
m.layouts.remove(li);
sel.target = Target::Layout { master: mi, layout: li.min(m.layouts.len().saturating_sub(1)) };
Ok(())
})?;
ok()
}
pub(super) fn insert_placeholder(s: &mut Session, p: &Value) -> Result<Value> {
let kind = match str_param(p, "kind").unwrap_or("content") {
"text" => PhType::Body,
"picture" => PhType::Picture,
"chart" => PhType::Chart,
"table" => PhType::Table,
"media" => PhType::Media,
_ => PhType::Obj,
};
if !matches!(s.doc()?.selection.target, Target::Layout { .. }) {
return Err(bad("master.insertPlaceholder", "select a layout in Slide Master view"));
}
let size = s.doc()?.doc.slide_size;
let rect = rect_param(p, "rect").unwrap_or(deckcraft_geom::Xfrm::new(size.width * 0.25, size.height * 0.3, size.width * 0.5, size.height * 0.4));
let idx = s.doc()?.shapes().iter().filter_map(|x| x.ph.as_ref().map(|p| p.idx)).max().unwrap_or(0) + 1;
let shape = Shape {
xfrm: Some(rect),
ph: Some(deckcraft_model::Placeholder { kind, idx, ..Default::default() }),
text: Some(TextBody::default()),
..Default::default()
};
let id = crate::cmd::insert::add_shape(s, "master.insertPlaceholder", shape, true)?;
Ok(json!({"id": id}))
}
pub(super) fn preserve(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let (on_master, mi, li, current) = match st.selection.target {
Target::Master { master } => {
let on = st.doc.masters.get(master).map(|m| m.preserve).ok_or_else(|| bad("master.preserve", "no such master"))?;
(true, master, 0, on)
}
Target::Layout { master, layout } => {
let on = st
.doc
.masters
.get(master)
.and_then(|m| m.layouts.get(layout))
.map(|l| l.preserve)
.ok_or_else(|| bad("master.preserve", "no such layout"))?;
(false, master, layout, on)
}
Target::Slides | Target::Handout | Target::NotesMaster => return Err(bad("master.preserve", "open Slide Master view")),
};
let next = bool_param(p, "preserve").unwrap_or(!current);
if next == current {
return Ok(json!({"preserve": next}));
}
s.edit(|doc, _| {
if on_master {
let m = Arc::make_mut(doc.masters.get_mut(mi).ok_or_else(|| bad("master.preserve", "no such master"))?);
m.preserve = next;
} else {
let l =
doc.masters.get_mut(mi).and_then(|m| Arc::make_mut(m).layouts.get_mut(li)).ok_or_else(|| bad("master.preserve", "no such layout"))?;
l.preserve = next;
}
Ok(())
})?;
Ok(json!({"preserve": next}))
}
pub(super) fn placeholders(s: &mut Session, p: &Value) -> Result<Value> {
let title = bool_param(p, "title");
let footers = bool_param(p, "footers");
if title.is_none() && footers.is_none() {
return Err(bad("master.placeholders", "give title or footers"));
}
let st = s.doc()?;
if matches!(st.selection.target, Target::Slides) {
return Err(bad("master.placeholders", "open Slide Master view"));
}
let has_title = st.shapes().iter().any(|sh| sh.ph_type().is_some_and(PhType::is_title));
let has_footers = st.shapes().iter().any(|sh| sh.ph_type().is_some_and(PhType::is_footer_kind));
let title_changes = title.is_some_and(|want| want != has_title);
let footer_changes = footers.is_some_and(|want| want != has_footers);
if !title_changes && !footer_changes {
return Ok(json!({"title": has_title, "footers": has_footers}));
}
let mut add = Vec::new();
if title == Some(true) && !has_title {
add.push(PhType::Title);
}
if footers == Some(true) && !has_footers {
add.extend([PhType::Date, PhType::Footer, PhType::SlideNum]);
}
let size = st.doc.slide_size;
s.edit(|doc, sel| {
let mut ids = Vec::with_capacity(add.len());
for _ in 0..add.len() {
ids.push(ShapeId(doc.alloc_id().ok_or_else(|| bad("master.placeholders", NO_ID_SPACE))?));
}
let prototypes = match sel.target {
Target::Master { master } | Target::Layout { master, .. } => doc.masters.get(master).map(|m| m.shapes.clone()).unwrap_or_default(),
Target::Slides => Vec::new(),
Target::Handout | Target::NotesMaster => return Err(bad("master.placeholders", "open Slide Master view")),
};
let shapes = crate::shapes_mut(doc, sel).ok_or_else(|| bad("master.placeholders", "open Slide Master view"))?;
if title == Some(false) {
shapes.retain(|sh| !sh.ph_type().is_some_and(PhType::is_title));
}
if footers == Some(false) {
shapes.retain(|sh| !sh.ph_type().is_some_and(PhType::is_footer_kind));
}
for (kind, id) in add.into_iter().zip(ids) {
let idx = free_ph_idx(shapes, preferred_ph_idx(kind));
let proto = prototypes.iter().find(|sh| match kind {
PhType::Title => sh.ph_type().is_some_and(PhType::is_title),
other => sh.ph_type() == Some(other),
});
let shape = match proto {
Some(src) => retarget_placeholder(src.clone(), id, idx),
None => synthesized_placeholder(kind, id, idx, size),
};
shapes.push(shape);
}
Ok(())
})?;
let st = s.doc()?;
let title = st.shapes().iter().any(|sh| sh.ph_type().is_some_and(PhType::is_title));
let footers = st.shapes().iter().any(|sh| sh.ph_type().is_some_and(PhType::is_footer_kind));
Ok(json!({"title": title, "footers": footers}))
}
fn preferred_ph_idx(kind: PhType) -> u32 {
match kind {
PhType::Title | PhType::CtrTitle => 0,
PhType::Date => 10,
PhType::Footer => 11,
PhType::SlideNum => 12,
_ => 1,
}
}
fn free_ph_idx(shapes: &[Shape], preferred: u32) -> u32 {
let taken = |idx: u32| shapes.iter().any(|sh| sh.ph.as_ref().is_some_and(|p| p.idx == idx));
if !taken(preferred) { preferred } else { shapes.iter().filter_map(|sh| sh.ph.as_ref().map(|p| p.idx)).max().unwrap_or(0).saturating_add(1) }
}
/// A copy of a master placeholder, with a new id and index. Prompt text is cleared; a slide
/// number keeps its `‹#›` field.
fn retarget_placeholder(mut sh: Shape, id: ShapeId, idx: u32) -> Shape {
sh.id = id;
if let Some(ph) = sh.ph.as_mut() {
ph.idx = idx;
}
let slide_num = sh.ph_type() == Some(PhType::SlideNum);
if slide_num {
let paras = vec![slide_number_paragraph()];
if let Some(text) = sh.text.as_mut() {
text.paragraphs = paras;
} else {
sh.text = Some(TextBody { paragraphs: paras, ..Default::default() });
}
} else if let Some(text) = sh.text.as_mut() {
text.paragraphs.clear();
}
sh
}
fn synthesized_placeholder(kind: PhType, id: ShapeId, idx: u32, size: Size) -> Shape {
let (name, text) = match kind {
PhType::Date => ("Date Placeholder", TextBody::default()),
PhType::Footer => ("Footer Placeholder", TextBody::default()),
PhType::SlideNum => ("Slide Number Placeholder", TextBody { paragraphs: vec![slide_number_paragraph()], ..Default::default() }),
_ => ("Title", TextBody::default()),
};
Shape {
id,
name: name.into(),
xfrm: Some(placeholder_rect(kind, size)),
ph: Some(deckcraft_model::Placeholder { kind, idx, ..Default::default() }),
text: Some(text),
..Default::default()
}
}
/// Standard placeholder boxes at 960×540, scaled to the slide size.
fn placeholder_rect(kind: PhType, size: Size) -> deckcraft_geom::Xfrm {
let sx = size.width / 960.0;
let sy = size.height / 540.0;
let (x, y, w, h) = match kind {
PhType::Date => (60.0, 500.0, 216.0, 28.0),
PhType::Footer => (318.0, 500.0, 324.0, 28.0),
PhType::SlideNum => (684.0, 500.0, 216.0, 28.0),
_ => (60.0, 29.0, 840.0, 104.0),
};
deckcraft_geom::Xfrm::new(x * sx, y * sy, w * sx, h * sy)
}
fn slide_number_paragraph() -> deckcraft_model::Paragraph {
deckcraft_model::Paragraph {
runs: vec![Run { text: "‹#›".into(), props: Default::default(), kind: RunKind::Field { field: "slidenum".into() } }],
..Default::default()
}
}
@@ -1,302 +0,0 @@
use super::{
Arc, BTreeSet, Background, Fill, NO_ID_SPACE, Presentation, Result, Session, Target, Value, bad, bool_or, bool_param, color_param, color_value,
f64_param, ok, opt_usize_param, usize_param, with_param,
};
pub(super) fn background(s: &mut Session, p: &Value) -> Result<Value> {
if bool_or(p, "copy", false) {
return copy_slide_background(s);
}
// Check the index before anything is edited: a picture is added to the media first.
let index = opt_usize_param(p, "index", "design.background")?;
let props = p.get("pictureProps").filter(|v| v.is_object()).cloned();
let transparency = f64_param(p, "transparency");
let reset = bool_or(p, "reset", false);
let color = color_param(p, "color");
let style = usize_param(p, "style");
let op = if reset {
BgOp::Set(None)
} else if let Some(mut c) = color {
if let Some(t) = transparency {
set_solid_transparency(&mut c, t);
}
BgOp::Set(Some(Background::Fill { fill: Fill::solid(c) }))
} else if let Some(i) = style {
// Background styles: 3 theme bg fills × 4 colours (bg1, bg2, tx1, tx2).
let slots =
[deckcraft_color::SchemeSlot::Bg1, deckcraft_color::SchemeSlot::Bg2, deckcraft_color::SchemeSlot::Tx2, deckcraft_color::SchemeSlot::Tx1];
let i = i.clamp(1, 12) - 1;
BgOp::Set(Some(Background::Ref {
idx: 1001 + (i / 4) as u32,
color: deckcraft_model::ColorRef::scheme(slots.get(i % 4).copied().unwrap_or(deckcraft_color::SchemeSlot::Bg1)),
}))
} else if let Some(g) = p.get("gradient") {
let mut g = crate::cmd::shape::gradient_param(g).ok_or_else(|| bad("design.background", "gradient needs two or more `stops`"))?;
g.rotate_with_shape = false;
BgOp::Set(Some(Background::Fill { fill: Fill::Gradient(g) }))
} else if let Some(pt) = p.get("pattern") {
BgOp::Set(Some(Background::Fill {
fill: Fill::Pattern(deckcraft_model::style::PatternFill {
preset: pt.get("preset").and_then(Value::as_str).unwrap_or("pct50").to_string(),
fg: pt.get("fg").and_then(color_value).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent1)),
bg: pt.get("bg").and_then(color_value).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Bg1)),
}),
}))
} else if p.get("picture").is_some() {
let (name, bytes) =
crate::cmd::insert::media_bytes(&with_param(p, "data", p.get("picture").cloned().unwrap_or_default()), "design.background")?;
let ct = crate::cmd::insert::content_type(&name, &bytes);
let media = s.edit(|doc, _| doc.add_media(&name, ct, bytes).ok_or_else(|| bad("design.background", NO_ID_SPACE)))?;
let mut pf = deckcraft_model::style::PictureFill { media, ..Default::default() };
if let Some(pp) = &props {
apply_picture_props(&mut pf, pp);
}
if let Some(t) = transparency {
set_picture_transparency(&mut pf, t);
}
BgOp::Set(Some(Background::Fill { fill: Fill::Picture(pf) }))
} else if props.is_some() || transparency.is_some() {
BgOp::Adjust
} else {
return Err(bad(
"design.background",
"give `color`, `gradient`, `pattern`, `picture`, `style`, `reset`, `pictureProps`, `transparency` or `copy`",
));
};
let all = bool_or(p, "all", false);
if matches!(op, BgOp::Adjust) {
let next = {
let st = s.doc()?;
let current = background_of(&st.doc, &st.selection, index);
let picture = matches!(current, Some(Background::Fill { fill: Fill::Picture(_) }));
let solid = matches!(current, Some(Background::Fill { fill: Fill::Solid { .. } }));
if props.is_some() && !picture {
return Err(bad("design.background", "picture options need a picture background"));
}
if transparency.is_some() && !picture && !solid {
return Err(bad("design.background", "transparency needs a solid or picture background"));
}
let mut next = current.clone();
if let Some(bg) = next.as_mut() {
adjust_background(bg, props.as_ref(), transparency);
}
if next == current { None } else { Some(next) }
};
let Some(next) = next else { return ok() };
s.edit(|doc, sel| {
write_background(doc, sel, index, false, next);
Ok(())
})?;
return ok();
}
let BgOp::Set(bg) = op else { return ok() };
let unchanged = {
let st = s.doc()?;
backgrounds_already(&st.doc, &st.selection, index, all, &bg)
};
if unchanged {
return ok();
}
s.edit(|doc, sel| {
write_background(doc, sel, index, all, bg);
Ok(())
})?;
ok()
}
enum BgOp {
Set(Option<Background>),
Adjust,
}
fn background_of(doc: &Presentation, sel: &crate::Selection, index: Option<usize>) -> Option<Background> {
match sel.target {
Target::Master { master } => doc.masters.get(master).and_then(|m| m.background.clone()),
Target::Layout { master, layout } => doc.masters.get(master).and_then(|m| m.layouts.get(layout)).and_then(|l| l.background.clone()),
t @ (Target::Handout | Target::NotesMaster) => crate::page_master(doc, t).and_then(|m| m.background.clone()),
Target::Slides => doc.slides.get(index.unwrap_or(sel.slide)).and_then(|sl| sl.background.clone()),
}
}
fn used_master_indices(doc: &Presentation) -> BTreeSet<usize> {
let fallback = (!doc.masters.is_empty()).then_some(0);
doc.slides.iter().filter_map(|sl| doc.masters.iter().position(|m| m.layout(sl.layout).is_some()).or(fallback)).collect()
}
fn backgrounds_already(doc: &Presentation, sel: &crate::Selection, index: Option<usize>, all: bool, bg: &Option<Background>) -> bool {
match sel.target {
Target::Master { master } => doc.masters.get(master).is_some_and(|m| m.background == *bg),
Target::Layout { master, layout } => doc.masters.get(master).and_then(|m| m.layouts.get(layout)).is_some_and(|l| l.background == *bg),
t @ (Target::Handout | Target::NotesMaster) => crate::page_master(doc, t).is_some_and(|m| m.background == *bg),
Target::Slides => {
let list: Vec<usize> = if all { (0..doc.slides.len()).collect() } else { vec![index.unwrap_or(sel.slide)] };
let slides_match = !list.is_empty() && list.iter().all(|i| doc.slides.get(*i).is_some_and(|sl| sl.background == *bg));
if all && bg.is_some() {
let masters = used_master_indices(doc);
let masters_match = !masters.is_empty() && masters.iter().all(|&idx| doc.masters.get(idx).is_some_and(|m| m.background == *bg));
let layouts_match = !masters.is_empty()
&& masters.iter().all(|&idx| doc.masters.get(idx).is_some_and(|m| m.layouts.iter().all(|l| l.background.is_none())));
slides_match && masters_match && layouts_match
} else {
slides_match
}
}
}
}
fn write_background(doc: &mut Presentation, sel: &crate::Selection, index: Option<usize>, all: bool, bg: Option<Background>) {
match sel.target {
Target::Master { master } => {
if let Some(m) = doc.masters.get_mut(master) {
Arc::make_mut(m).background = bg;
}
}
Target::Layout { master, layout } => {
if let Some(l) = doc.masters.get_mut(master).and_then(|m| Arc::make_mut(m).layouts.get_mut(layout)) {
l.background = bg;
}
}
t @ (Target::Handout | Target::NotesMaster) => {
if let Some(m) = crate::page_master_mut(doc, t) {
Arc::make_mut(m).background = bg;
}
}
Target::Slides => {
if all && bg.is_some() {
for idx in used_master_indices(doc) {
if let Some(m) = doc.masters.get_mut(idx) {
let m = Arc::make_mut(m);
m.background = bg.clone();
for l in &mut m.layouts {
l.background = None;
}
}
}
}
let list: Vec<usize> = if all { (0..doc.slides.len()).collect() } else { vec![index.unwrap_or(sel.slide)] };
for i in list {
if let Some(sl) = doc.slides.get_mut(i) {
Arc::make_mut(sl).background = bg.clone();
}
}
}
}
}
fn copy_slide_background(s: &mut Session) -> Result<Value> {
let bg = {
let st = s.doc()?;
if !matches!(st.selection.target, Target::Slides) {
return Err(bad("design.background", "copy applies to slides"));
}
let bg = st.doc.slides.get(st.selection.slide).and_then(|sl| sl.background.clone());
let slides_match = st.doc.slides.iter().all(|sl| sl.background == bg);
let masters_match = if bg.is_some() {
let masters = used_master_indices(&st.doc);
!masters.is_empty() && masters.iter().all(|&idx| st.doc.masters.get(idx).is_some_and(|m| m.background == bg))
} else {
true
};
if slides_match && masters_match {
return ok();
}
bg
};
s.edit(|doc, sel| {
write_background(doc, sel, None, true, bg);
Ok(())
})?;
ok()
}
fn adjust_background(bg: &mut Background, props: Option<&Value>, transparency: Option<f64>) {
match bg {
Background::Fill { fill: Fill::Picture(pf) } => {
if let Some(pp) = props {
apply_picture_props(pf, pp);
}
if let Some(t) = transparency {
set_picture_transparency(pf, t);
}
}
Background::Fill { fill: Fill::Solid { color } } => {
if let Some(t) = transparency {
set_solid_transparency(color, t);
}
}
_ => {}
}
}
fn set_picture_transparency(pf: &mut deckcraft_model::style::PictureFill, t: f64) {
let a = 1.0 - t.clamp(0.0, 1.0);
pf.alpha = (a < 1.0).then_some(a);
}
fn set_solid_transparency(color: &mut deckcraft_model::ColorRef, t: f64) {
color.mods.retain(|m| !matches!(m, deckcraft_color::ColorTransform::Alpha(_)));
let t = t.clamp(0.0, 1.0);
if t > 0.0 {
color.mods.push(deckcraft_color::ColorTransform::Alpha(((1.0 - t) * 100_000.0).round() as i32));
}
}
/// Picture-fill options for Format Background (tile, offsets, scale, alignment, mirror, stretch).
fn apply_picture_props(pf: &mut deckcraft_model::style::PictureFill, pp: &Value) {
use deckcraft_model::style::PictureMode;
let f = |k: &str| pp.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
if let Some(up) = pp.get("rotateWithShape").and_then(Value::as_bool) {
pf.upright = !up;
}
match pp.get("tile").and_then(Value::as_bool) {
Some(true) if !matches!(pf.mode, PictureMode::Tile { .. }) => {
pf.mode = PictureMode::Tile { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, flip: "none".into(), align: "tl".into() };
}
Some(false) if !matches!(pf.mode, PictureMode::Stretch { .. }) => pf.mode = PictureMode::default(),
_ => {}
}
match &mut pf.mode {
PictureMode::Tile { tx, ty, sx, sy, flip, align } => {
if let Some(v) = f("offsetX") {
*tx = v.clamp(-4000.0, 4000.0);
}
if let Some(v) = f("offsetY") {
*ty = v.clamp(-4000.0, 4000.0);
}
if let Some(v) = f("scaleX") {
*sx = v.clamp(0.01, 10.0);
}
if let Some(v) = f("scaleY") {
*sy = v.clamp(0.01, 10.0);
}
if let Some(m) = pp.get("mirror").and_then(Value::as_str).filter(|m| matches!(*m, "none" | "x" | "y" | "xy")) {
*flip = m.to_string();
}
if let Some(a) =
pp.get("align").and_then(Value::as_str).filter(|a| matches!(*a, "tl" | "t" | "tr" | "l" | "ctr" | "r" | "bl" | "b" | "br"))
{
*align = a.to_string();
}
}
PictureMode::Stretch { fill_rect } => {
if let Some(arr) = pp.get("stretch").and_then(Value::as_array) {
for (slot, v) in fill_rect.iter_mut().zip(arr) {
if let Some(v) = v.as_f64().filter(|v| v.is_finite()) {
*slot = v.clamp(-10.0, 0.99);
}
}
}
}
}
}
pub(super) fn hide_bg_graphics(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(|doc, sel| {
if let Some(sl) = doc.slides.get_mut(sel.slide) {
let sl = Arc::make_mut(sl);
sl.show_master_shapes = !bool_param(p, "hide").unwrap_or(sl.show_master_shapes);
}
Ok(())
})?;
ok()
}
-339
View File
@@ -1,339 +0,0 @@
use super::{
Arc, NO_ID_SPACE, PhType, Result, Run, RunKind, Session, Shape, ShapeId, Size, TextBody, Value, bad, bool_or, bool_param, defaults, f64_param,
json, ok, str_param,
};
pub(super) fn scale_shapes(shapes: &mut [Shape], sx: f64, sy: f64, k: f64, ox: f64, oy: f64) {
for sh in shapes {
if let Some(x) = sh.xfrm.as_mut() {
x.x = x.x * sx + ox;
x.y = x.y * sy + oy;
x.w *= sx;
x.h *= sy;
}
if let Some(t) = sh.text.as_mut() {
deckcraft_model::edit::format_all(t, &|r| {
if let Some(sz) = r.size.as_mut() {
*sz = (*sz * k).max(1.0);
}
});
}
}
}
pub(super) fn slide_size(s: &mut Session, p: &Value) -> Result<Value> {
let size = if let Some(pre) = str_param(p, "preset") {
let k = pre.to_ascii_lowercase();
let found = defaults::SLIDE_SIZES.iter().find(|(l, _, _)| l.to_ascii_lowercase().starts_with(&k) || l.to_ascii_lowercase().contains(&k));
let (_, w, h) = found.ok_or_else(|| bad("design.slideSize", format!("unknown preset `{pre}`")))?;
Size::new(*w, *h)
} else {
Size::new(
f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(72.0, 4032.0),
f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(72.0, 4032.0),
)
};
let size = match str_param(p, "orientation") {
Some("portrait") if size.width > size.height => Size::new(size.height, size.width),
Some("landscape") if size.height > size.width => Size::new(size.height, size.width),
Some("portrait" | "landscape") | None => size,
Some(o) => return Err(bad("design.slideSize", format!("unknown orientation `{o}`"))),
};
let mode = str_param(p, "scale").unwrap_or("ensureFit").to_string();
s.edit(|doc, _| {
let old = doc.slide_size;
let (sx, sy) = (size.width / old.width.max(1.0), size.height / old.height.max(1.0));
let (sx, sy, k, ox, oy) = match mode.as_str() {
"none" => (1.0, 1.0, 1.0, 0.0, 0.0),
"maximize" => {
let k = sx.max(sy);
(k, k, k, (size.width - old.width * k) / 2.0, (size.height - old.height * k) / 2.0)
}
_ => {
let k = sx.min(sy);
(k, k, k, (size.width - old.width * k) / 2.0, (size.height - old.height * k) / 2.0)
}
};
// Masters and layouts stretch to the new size; slides scale by mode.
let (msx, msy) = (size.width / old.width.max(1.0), size.height / old.height.max(1.0));
for m in &mut doc.masters {
let m = Arc::make_mut(m);
scale_shapes(&mut m.shapes, msx, msy, 1.0, 0.0, 0.0);
for l in &mut m.layouts {
scale_shapes(&mut l.shapes, msx, msy, 1.0, 0.0, 0.0);
}
}
for sl in &mut doc.slides {
scale_shapes(&mut Arc::make_mut(sl).shapes, sx, sy, k, ox, oy);
}
doc.slide_size = size;
Ok(())
})?;
Ok(json!({"w": size.width, "h": size.height}))
}
pub(super) fn header_footer(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(|doc, sel| {
let hf = &mut doc.header_footer;
if let Some(v) = bool_param(p, "date") {
hf.date = v;
}
if let Some(v) = str_param(p, "dateText") {
hf.date_text = v.into();
}
if let Some(v) = str_param(p, "dateFormat") {
// Refused rather than ignored: a format that renders nothing would leave the
// placeholder showing its saved text for ever.
if !deckcraft_text::datetime::DATE_KINDS.contains(&v) {
return Err(bad("design.headerFooter", "dateFormat: one of datetime1…datetime13"));
}
hf.date_format = v.into();
}
if let Some(v) = bool_param(p, "slideNumber") {
hf.slide_number = v;
}
if let Some(v) = bool_param(p, "footer") {
hf.footer = v;
}
if let Some(v) = str_param(p, "footerText") {
hf.footer_text = v.into();
hf.footer = hf.footer || !v.is_empty();
}
if let Some(v) = bool_param(p, "hideOnTitle") {
hf.hide_on_title = v;
}
let hf = hf.clone();
let date_given = str_param(p, "dateText").is_some();
let format_given = str_param(p, "dateFormat").is_some();
let all = bool_or(p, "all", true);
let list: Vec<usize> = if all { (0..doc.slides.len()).collect() } else { vec![sel.slide] };
for i in list {
let Some(layout) = doc.slides.get(i).map(|x| x.layout) else { continue };
let lay = doc.layout(layout).map(|(_, l)| l.clone());
let is_title = lay.as_ref().is_some_and(|l| l.kind == deckcraft_model::LayoutType::Title);
let want = |k: PhType| {
!(hf.hide_on_title && is_title)
&& match k {
PhType::Date => hf.date,
PhType::SlideNum => hf.slide_number,
PhType::Footer => hf.footer,
_ => false,
}
};
let mut new_ids = vec![];
for _ in 0..3 {
new_ids.push(ShapeId(doc.alloc_id().ok_or_else(|| bad("design.headerFooter", NO_ID_SPACE))?));
}
let Some(sl) = doc.slides.get_mut(i) else { continue };
let sl = Arc::make_mut(sl);
for (n, k) in [PhType::Date, PhType::Footer, PhType::SlideNum].into_iter().enumerate() {
let has = sl.shapes.iter().position(|x| x.ph_type() == Some(k));
match (has, want(k)) {
(Some(pos), false) => {
sl.shapes.remove(pos);
}
(None, true) => {
let lp = lay.as_ref().and_then(|l| l.shapes.iter().find(|x| x.ph_type() == Some(k)).cloned());
let Some(lp) = lp else { continue };
let body = match k {
PhType::SlideNum => TextBody {
paragraphs: vec![deckcraft_model::Paragraph {
runs: vec![Run {
text: "‹#›".into(),
props: Default::default(),
kind: RunKind::Field { field: "slidenum".into() },
}],
..Default::default()
}],
..Default::default()
},
PhType::Date if hf.date_text.is_empty() => TextBody {
paragraphs: vec![deckcraft_model::Paragraph {
runs: vec![Run {
text: date_now(&hf.date_format),
props: Default::default(),
kind: RunKind::Field { field: date_kind(&hf.date_format).into() },
}],
..Default::default()
}],
..Default::default()
},
PhType::Date => TextBody::from_text(&hf.date_text),
_ => TextBody::from_text(&hf.footer_text),
};
sl.shapes.push(Shape {
id: new_ids.get(n).copied().unwrap_or_default(),
name: lp.name.clone(),
ph: lp.ph.clone(),
text: Some(body),
..Default::default()
});
}
(Some(pos), true) if k == PhType::Footer => {
if let Some(sh) = sl.shapes.get_mut(pos) {
sh.text = Some(TextBody::from_text(&hf.footer_text));
}
}
(Some(pos), true) if k == PhType::Date && (date_given || format_given) => {
if let Some(sh) = sl.shapes.get_mut(pos) {
set_date(sh, &hf.date_text, &hf.date_format);
}
}
_ => {}
}
}
}
Ok(())
})?;
ok()
}
/// The date field type `format` names, `datetime1` when it is empty or unknown.
fn date_kind(format: &str) -> &str {
if deckcraft_text::datetime::DATE_KINDS.contains(&format) { format } else { "datetime1" }
}
/// The saved text of a date field of `format`, as it shows now.
fn date_now(format: &str) -> String {
let kind = date_kind(format);
deckcraft_text::datetime::DateTime::now_local().and_then(|now| deckcraft_text::datetime::field_text(kind, None, now)).unwrap_or_else(today)
}
/// Point a slide's date placeholder at a fixed date (its own plain text) or, for an empty
/// `fixed`, at an automatic date field (one it already has keeps its format).
fn set_date(sh: &mut Shape, fixed: &str, format: &str) {
let runs = || sh.text.iter().flat_map(|t| &t.paragraphs).flat_map(|p| &p.runs);
let field_now = runs().find_map(|r| match &r.kind {
RunKind::Field { field } if deckcraft_text::datetime::is_date_field(field) => Some(field.clone()),
_ => None,
});
let has_field = field_now.is_some();
let props = runs().next().map(|r| r.props.clone()).unwrap_or_default();
let want = date_kind(format);
let (text, kind) = match fixed {
// Automatic: keep the field, but follow a format that has changed.
"" if field_now.as_deref() == Some(want) => return,
"" if has_field && format.is_empty() => return,
"" => (date_now(format), RunKind::Field { field: want.into() }),
_ if !has_field && sh.text.as_ref().is_some_and(|t| t.text() == fixed) => return,
_ => (fixed.to_string(), RunKind::Text),
};
let para = deckcraft_model::Paragraph { runs: vec![Run { text, props, kind }], ..Default::default() };
sh.text = Some(TextBody { paragraphs: vec![para], ..sh.text.clone().unwrap_or_default() });
}
/// Today's local date as a `datetime1` field shows it (M/D/YYYY): the saved text of a new date
/// field. Empty where there is no clock (wasm).
pub fn today() -> String {
date_field_text("datetime1")
}
/// What date field `kind` shows now (empty if unknown or there is no clock).
pub fn date_field_text(kind: &str) -> String {
use deckcraft_text::datetime::{DateTime, field_text};
DateTime::now_local().and_then(|now| field_text(kind, None, now)).unwrap_or_default()
}
/// Days since 1970-01-01 → (year, month, day), exact for every `i64`.
pub fn civil(z: i64) -> (i64, u32, u32) {
use chrono::Datelike;
// `NaiveDate` covers only about ±262143 years, and the Gregorian calendar repeats every 400
// years (146_097 days). chrono converts the day within its cycle and whole cycles go back
// into the year (an i128 for i64::MAX/MIN). 1970-01-01 is `num_days_from_ce` 719_163, and
// 0..146_097 days from it always fits.
let (cycles, rest) = (z.div_euclid(146_097), z.rem_euclid(146_097));
match i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt) {
Some(d) => {
let y = i128::from(d.year()) + i128::from(cycles) * 400;
(i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }), d.month(), d.day())
}
None => (1970, 1, 1),
}
}
#[cfg(test)]
mod header_footer_date_tests {
use deckcraft_model::PhType;
use deckcraft_model::text::RunKind;
use serde_json::json;
use crate::Session;
/// The date field of the Date placeholders of every slide: (saved text, field type).
fn dates(s: &Session) -> Vec<(String, Option<String>)> {
let d = &s.doc().unwrap().doc;
d.slides
.iter()
.flat_map(|sl| sl.shapes.iter())
.filter(|sh| sh.ph_type() == Some(PhType::Date))
.flat_map(|sh| sh.text.iter())
.flat_map(|t| t.paragraphs.iter())
.flat_map(|p| p.runs.iter())
.map(|r| {
let kind = match &r.kind {
RunKind::Field { field } => Some(field.clone()),
_ => None,
};
(r.text.clone(), kind)
})
.collect()
}
fn sample(kind: &str) -> String {
let now = deckcraft_text::datetime::DateTime::now_local().expect("a local date");
deckcraft_text::datetime::field_text(kind, None, now).expect("a sample")
}
/// Runs `design.headerFooter` and checks the slide's date run is an automatic `kind` field.
/// The clock is read before and after the command, so a second ticking over between the
/// command and the read cannot fail the comparison. Returns the run text.
fn run_automatic(s: &mut Session, params: serde_json::Value, kind: &str) -> String {
let before = sample(kind);
s.execute("design.headerFooter", &params).unwrap();
let after = sample(kind);
let got = dates(s);
assert_eq!(got.len(), 1, "{got:?}");
assert_eq!(got[0].1.as_deref(), Some(kind));
assert!(got[0].0 == before || got[0].0 == after, "{got:?} is neither {before:?} nor {after:?}");
got[0].0.clone()
}
/// Header & Footer's automatic date takes the format it is given. `HeaderFooter::date_format`
/// existed for this and was never read: the placeholder was always `datetime1`, and a
/// `dateFormat` parameter was accepted and silently dropped.
#[test]
fn the_automatic_date_takes_the_format_it_is_given() {
let mut s = Session::with_new();
// Default: the short date, as before.
run_automatic(&mut s, json!({"date": true, "dateText": "", "all": true}), "datetime1");
// A format: the field type changes and the saved text is that format's.
run_automatic(&mut s, json!({"date": true, "dateFormat": "datetime5", "all": true}), "datetime5");
assert_eq!(s.doc().unwrap().doc.header_footer.date_format, "datetime5");
// A time format works the same way, and these two differ, so the format is really read.
let time = run_automatic(&mut s, json!({"date": true, "dateFormat": "datetime11", "all": true}), "datetime11");
assert_ne!(time, sample("datetime5"));
// Asking again changes nothing (and does not rewrite the run).
let again = run_automatic(&mut s, json!({"date": true, "dateFormat": "datetime11", "all": true}), "datetime11");
assert_eq!(again, time);
// A fixed date still wins: plain text, no field.
s.execute("design.headerFooter", &json!({"date": true, "dateText": "4 July 1776", "all": true})).unwrap();
assert_eq!(dates(&s), vec![("4 July 1776".to_string(), None)]);
// Back to automatic: the remembered format comes back, not datetime1.
run_automatic(&mut s, json!({"date": true, "dateText": "", "dateFormat": "datetime11", "all": true}), "datetime11");
// An unknown format is refused rather than ignored, and changes nothing.
for bad in ["datetime0", "datetime14", "nonsense", ""] {
assert!(s.execute("design.headerFooter", &json!({"date": true, "dateFormat": bad})).is_err(), "{bad}");
}
assert_eq!(s.doc().unwrap().doc.header_footer.date_format, "datetime11");
let got = dates(&s);
assert_eq!(got.len(), 1, "{got:?}");
assert_eq!(got[0].1.as_deref(), Some("datetime11"));
}
}
-500
View File
@@ -1,500 +0,0 @@
use std::sync::Arc;
use deckcraft_color::SchemeSlot;
use deckcraft_model::style::PictureMode;
use deckcraft_model::theme::{FontScheme, ScriptFont, builtin_color_schemes, builtin_font_schemes};
use deckcraft_model::{Background, Fill};
use serde_json::{Value, json};
use crate::{Session, UiRequest};
fn scheme(s: &Session) -> deckcraft_color::ColorScheme {
s.doc().unwrap().doc.masters[0].theme.colors.clone()
}
fn font_scheme(s: &Session) -> FontScheme {
s.doc().unwrap().doc.masters[0].theme.fonts.clone()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn png() -> String {
let mut img = image::RgbaImage::new(2, 2);
img.put_pixel(0, 0, image::Rgba([10, 20, 30, 255]));
let mut bytes = Vec::new();
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
crate::cmd::base64_encode(&bytes)
}
fn picture(s: &Session) -> deckcraft_model::style::PictureFill {
match &s.doc().unwrap().doc.slides[0].background {
Some(Background::Fill { fill: Fill::Picture(pf) }) => pf.clone(),
other => panic!("expected a picture background, got {other:?}"),
}
}
#[test]
fn layout_commands_reject_invalid_index() {
let mut s = Session::with_new();
s.execute("master.insertLayout", &json!({})).unwrap();
let count = |s: &Session| s.doc().unwrap().doc.masters.iter().map(|m| m.layouts.len()).sum::<usize>();
let names = |s: &Session| s.doc().unwrap().doc.masters.iter().flat_map(|m| m.layouts.iter().map(|l| l.name.clone())).collect::<Vec<_>>();
let n = count(&s);
let before = names(&s);
for bad in [json!(-1), json!(1.5)] {
assert!(s.execute("master.deleteLayout", &json!({"layout": bad})).is_err());
assert!(s.execute("master.deleteLayout", &json!({"master": bad})).is_err());
assert!(s.execute("master.renameLayout", &json!({"layout": bad, "name": "x"})).is_err());
assert_eq!(count(&s), n);
assert_eq!(names(&s), before);
}
s.execute("master.deleteLayout", &json!({})).unwrap();
assert_eq!(count(&s), n - 1);
}
#[test]
fn civil_dates() {
assert_eq!(super::civil(0), (1970, 1, 1));
assert_eq!(super::civil(20_734), (2026, 10, 8));
// Past `NaiveDate`'s range the 400-year cycles carry the year, exactly, up to the extremes.
assert_eq!(super::civil(95_026_602), (262_144, 1, 1));
assert_eq!(super::civil(-96_465_964), (-262_145, 3, 1));
assert_eq!(super::civil(i64::MAX), (25_252_734_927_768_524, 7, 27));
assert_eq!(super::civil(i64::MIN), (-25_252_734_927_764_585, 6, 7));
}
#[test]
fn colors_dialog_apply_and_reject() {
let mut s = Session::with_new();
let original = scheme(&s);
let n = undo_len(&s);
s.execute("design.colors", &json!({})).unwrap();
s.execute("design.colors", &Value::Null).unwrap();
assert_eq!(scheme(&s), original);
assert_eq!(undo_len(&s), n, "opening the dialog does not edit");
assert_eq!(s.ui_requests.len(), 2);
match &s.ui_requests[0] {
UiRequest::Dialog { id, params } => {
assert_eq!(id, "themeColors");
assert_eq!(params["name"], "DeckCraft");
let colors = params["colors"].as_object().unwrap();
assert_eq!(colors.len(), 12);
assert_eq!(colors["accent1"].as_str().unwrap(), format!("#{}", original.get(SchemeSlot::Accent1).hex()));
assert!(colors.contains_key("folHlink"));
}
other => panic!("expected a dialog, got {other:?}"),
}
s.execute("design.colors", &json!({"name": "Harbor"})).unwrap();
let harbor = builtin_color_schemes().into_iter().find(|c| c.name == "Harbor").unwrap();
assert_eq!(scheme(&s).name, "Harbor");
assert_eq!(scheme(&s).get(SchemeSlot::Accent1), harbor.get(SchemeSlot::Accent1));
assert_eq!(undo_len(&s), n + 1);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Colors");
s.execute("design.colors", &json!({"name": "Harbor"})).unwrap();
assert_eq!(undo_len(&s), n + 1, "the same scheme is not an undo step");
colors_dialog_rejects(&mut s, n, &harbor);
}
fn colors_dialog_rejects(s: &mut Session, n: usize, harbor: &deckcraft_color::ColorScheme) {
let err = s.execute("design.colors", &json!({"name": "Nope"})).unwrap_err().to_string();
assert!(err.contains("no colour scheme `Nope`"), "{err}");
assert!(s.execute("design.colors", &json!({"name": " "})).is_err());
assert!(s.execute("design.colors", &json!({"name": 1})).is_err());
assert!(s.execute("design.colors", &json!({"colors": {}})).is_err());
assert!(s.execute("design.colors", &json!({"colors": "red"})).is_err());
assert!(s.execute("design.colors", &json!({"colors": {"bg1": "#112233"}})).is_err());
assert!(s.execute("design.colors", &json!({"colors": {"tx1": "#112233"}})).is_err());
assert!(s.execute("design.colors", &json!({"colors": {"phClr": "#112233"}})).is_err());
assert!(s.execute("design.colors", &json!({"colors": {"nope": "#112233"}})).is_err());
assert!(s.execute("design.colors", &json!({"colors": {"accent1": "zz"}})).is_err());
assert!(s.execute("design.colors", &json!({"name": "Harbor", "colors": {}})).is_err());
assert_eq!(scheme(s).name, "Harbor");
assert_eq!(scheme(s).get(SchemeSlot::Accent1), harbor.get(SchemeSlot::Accent1));
assert_eq!(undo_len(s), n + 1);
colors_dialog_custom_overrides(s, n, harbor);
}
fn colors_dialog_custom_overrides(s: &mut Session, n: usize, harbor: &deckcraft_color::ColorScheme) {
s.execute("design.colors", &json!({"colors": {"accent1": "112233"}})).unwrap();
assert_eq!(scheme(s).name, "Custom");
assert_eq!(scheme(s).get(SchemeSlot::Accent1).hex(), "112233");
assert_eq!(scheme(s).get(SchemeSlot::Accent2), harbor.get(SchemeSlot::Accent2));
assert_eq!(undo_len(s), n + 2);
let meadow = builtin_color_schemes().into_iter().find(|c| c.name == "Meadow").unwrap();
s.execute("design.colors", &json!({"name": "Meadow", "colors": {"lt1": "#010203"}})).unwrap();
assert_eq!(scheme(s).name, "Meadow");
assert_eq!(scheme(s).get(SchemeSlot::Lt1).hex(), "010203");
assert_eq!(scheme(s).get(SchemeSlot::Accent1), meadow.get(SchemeSlot::Accent1));
assert_eq!(undo_len(s), n + 3);
s.execute("design.colors", &json!({"name": "Talk", "colors": {"dk1": "#ABCDEF"}})).unwrap();
assert_eq!(scheme(s).name, "Talk");
assert_eq!(scheme(s).get(SchemeSlot::Dk1).hex(), "ABCDEF");
assert_eq!(scheme(s).get(SchemeSlot::Lt1).hex(), "010203");
assert_eq!(scheme(s).get(SchemeSlot::Accent1), meadow.get(SchemeSlot::Accent1));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(scheme(s).name, "Meadow");
assert_eq!(scheme(s).get(SchemeSlot::Dk1), meadow.get(SchemeSlot::Dk1));
}
#[test]
fn fonts_dialog_apply_and_reject() {
let mut s = Session::with_new();
let original = font_scheme(&s);
let n = undo_len(&s);
s.execute("design.fonts", &json!({})).unwrap();
s.execute("design.fonts", &Value::Null).unwrap();
s.execute("design.fonts", &json!([1, 2])).unwrap();
assert_eq!(font_scheme(&s), original);
assert_eq!(undo_len(&s), n, "opening the dialog does not edit");
assert_eq!(s.ui_requests.len(), 3);
match &s.ui_requests[0] {
UiRequest::Dialog { id, params } => {
assert_eq!(id, "themeFonts");
assert_eq!(params["name"], original.name);
assert_eq!(params["major"], original.major.latin);
assert_eq!(params["minor"], original.minor.latin);
}
other => panic!("expected a dialog, got {other:?}"),
}
s.execute("design.fonts", &json!({"name": "classic"})).unwrap();
let classic = builtin_font_schemes().into_iter().find(|f| f.name == "Classic").unwrap();
assert_eq!(font_scheme(&s), classic, "a builtin name keeps that scheme, including its own name");
assert_eq!(undo_len(&s), n + 1);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Fonts");
s.execute("design.fonts", &json!({"name": "Classic"})).unwrap();
assert_eq!(undo_len(&s), n + 1, "the same scheme is not an undo step");
let err = s.execute("design.fonts", &json!({"name": "Nope"})).unwrap_err().to_string();
assert!(err.contains("no font scheme `Nope`"), "{err}");
assert!(s.execute("design.fonts", &json!({"name": " "})).is_err());
assert!(s.execute("design.fonts", &json!({"name": 1})).is_err());
assert!(s.execute("design.fonts", &json!({"major": ""})).is_err());
assert!(s.execute("design.fonts", &json!({"major": " "})).is_err());
assert!(s.execute("design.fonts", &json!({"minor": 1})).is_err());
assert!(s.execute("design.fonts", &json!({"name": "Classic", "major": ""})).is_err());
assert_eq!(font_scheme(&s), classic);
assert_eq!(undo_len(&s), n + 1);
fonts_dialog_custom_overrides(&mut s);
}
fn fonts_dialog_custom_overrides(s: &mut Session) {
s.edit(|doc, _| {
let fonts = &mut std::sync::Arc::make_mut(&mut doc.masters[0]).theme.fonts;
fonts.major.ea = "EA Major".into();
fonts.minor.cs = "CS Minor".into();
fonts.major.scripts.push(ScriptFont { script: "Arab".into(), typeface: "Noto Naskh Arabic".into() });
Ok(())
})
.unwrap();
let marked = font_scheme(s);
let n = undo_len(s);
s.execute("design.fonts", &json!({"major": " Lato "})).unwrap();
let custom = font_scheme(s);
assert_eq!(custom.name, "Custom");
assert_eq!(custom.major.latin, "Lato");
assert_eq!(custom.minor.latin, "Lato", "an omitted minor copies major");
assert_eq!(custom.major.ea, "EA Major");
assert_eq!(custom.minor.cs, "CS Minor");
assert_eq!(custom.major.scripts, marked.major.scripts);
assert_eq!(undo_len(s), n + 1);
s.execute("design.fonts", &json!({"minor": "Roboto"})).unwrap();
assert_eq!(font_scheme(s).name, "Custom");
assert_eq!(font_scheme(s).major.latin, "Lato");
assert_eq!(font_scheme(s).minor.latin, "Roboto");
assert_eq!(font_scheme(s).major.ea, "EA Major");
assert_eq!(undo_len(s), n + 2);
s.execute("design.fonts", &json!({"name": "Classic", "major": "Inter"})).unwrap();
assert_eq!(font_scheme(s).name, "Classic");
assert_eq!(font_scheme(s).major.latin, "Inter");
assert_eq!(font_scheme(s).minor.latin, "Open Sans");
assert_eq!(font_scheme(s).major.ea, "");
assert!(font_scheme(s).major.scripts.is_empty(), "a builtin is applied before the latin overlay");
assert_eq!(undo_len(s), n + 3);
s.edit(|doc, _| {
std::sync::Arc::make_mut(&mut doc.masters[0]).theme.fonts.major.ea = "Kept".into();
Ok(())
})
.unwrap();
s.execute("design.fonts", &json!({"name": "Talk", "minor": "Nunito Sans"})).unwrap();
assert_eq!(font_scheme(s).name, "Talk");
assert_eq!(font_scheme(s).major.latin, "Inter");
assert_eq!(font_scheme(s).minor.latin, "Nunito Sans");
assert_eq!(font_scheme(s).major.ea, "Kept");
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Fonts");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(font_scheme(s).name, "Classic");
assert_eq!(font_scheme(s).major.ea, "Kept");
assert_eq!(font_scheme(s).minor.latin, "Open Sans");
}
#[test]
fn background_picture_options_tile_transparency_and_copy() {
let mut s = Session::with_new();
let n = undo_len(&s);
let err = s.execute("design.background", &json!({"pictureProps": {"tile": true}})).unwrap_err().to_string();
assert!(err.contains("picture background"), "{err}");
assert!(s.execute("design.background", &json!({"transparency": 0.2})).is_err());
assert_eq!(undo_len(&s), n);
s.execute("design.background", &json!({"color": "accent1", "transparency": 0.25})).unwrap();
match &s.doc().unwrap().doc.slides[0].background {
Some(Background::Fill { fill: Fill::Solid { color } }) => assert!((color.alpha() - 0.75).abs() < 1e-4, "{}", color.alpha()),
other => panic!("expected a solid background, got {other:?}"),
}
let n = undo_len(&s);
s.execute("design.background", &json!({"transparency": 0.25})).unwrap();
assert_eq!(undo_len(&s), n, "the same transparency is not an undo step");
s.execute("design.background", &json!({"picture": png(), "name": "dot.png", "transparency": 0.4, "pictureProps": {"tile": true}})).unwrap();
let pf = picture(&s);
assert!((pf.alpha.unwrap_or(1.0) - 0.6).abs() < 1e-6);
assert!(matches!(pf.mode, PictureMode::Tile { .. }));
let n = undo_len(&s);
s.execute(
"design.background",
&json!({"pictureProps": {"offsetX": 12.0, "offsetY": -3.0, "scaleX": 0.5, "scaleY": 50.0, "align": "ctr", "mirror": "xy", "rotateWithShape": false}}),
)
.unwrap();
match picture(&s).mode {
PictureMode::Tile { tx, ty, sx, sy, flip, align } => {
assert_eq!((tx, ty, sx, sy), (12.0, -3.0, 0.5, 10.0));
assert_eq!(flip, "xy");
assert_eq!(align, "ctr");
}
other => panic!("expected a tile, got {other:?}"),
}
assert!(picture(&s).upright);
s.execute("design.background", &json!({"pictureProps": {"align": "bogus", "offsetX": "nope"}})).unwrap();
match picture(&s).mode {
PictureMode::Tile { tx, align, .. } => {
assert_eq!(tx, 12.0);
assert_eq!(align, "ctr");
}
other => panic!("expected the tile to stay, got {other:?}"),
}
assert_eq!(undo_len(&s), n + 1, "ignored options are not an undo step");
s.execute("design.background", &json!({"pictureProps": {"tile": false, "stretch": [0.1, 0.2, 0.0, 0.0]}})).unwrap();
match picture(&s).mode {
PictureMode::Stretch { fill_rect } => assert_eq!(fill_rect, [0.1, 0.2, 0.0, 0.0]),
other => panic!("expected a stretch, got {other:?}"),
}
s.execute("slide.new", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.slides[1].background.is_none());
s.execute("slide.go", &json!({"index": 0})).unwrap();
let n = undo_len(&s);
s.execute("design.background", &json!({"copy": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.slides[1].background, s.doc().unwrap().doc.slides[0].background);
assert_eq!(undo_len(&s), n + 1);
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Format Background");
s.execute("design.background", &json!({"copy": true})).unwrap();
assert_eq!(undo_len(&s), n + 1, "copying an already shared background is not an undo step");
}
#[test]
fn background_all_applies_to_master_and_new_slides_inherit() {
let mut s = Session::with_new();
s.execute("file.new", &json!({"theme": "Nocturne"})).unwrap();
let s0 = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
assert_eq!(s0["background"], "#121826");
let n = undo_len(&s);
s.execute("design.background", &json!({"color": "#0D0D0D", "all": true})).unwrap();
assert_eq!(undo_len(&s), n + 1);
// Idempotency: re-applying the same background to all is a no-op (no extra undo step)
s.execute("design.background", &json!({"color": "#0D0D0D", "all": true})).unwrap();
assert_eq!(undo_len(&s), n + 1, "re-applying already applied background is not an undo step");
// Slide 0 has new background, master has new background, layouts cleared
let doc = &s.doc().unwrap().doc;
assert!(matches!(doc.slides[0].background, Some(Background::Fill { .. })));
assert_eq!(doc.masters[0].background, doc.slides[0].background);
for l in &doc.masters[0].layouts {
assert!(l.background.is_none());
}
// Newly added slides inherit the master background (fixes #891)
s.execute("slide.new", &json!({"layout": "titleAndContent", "title": "new"})).unwrap();
let s0_after = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
let s1_after = s.execute("slide.inspect", &json!({"index": 1})).unwrap();
assert_eq!(s0_after["background"], "#0D0D0D");
assert_eq!(s1_after["background"], "#0D0D0D");
// Undo restores previous slide and master backgrounds
s.execute("edit.undo", &json!({})).unwrap(); // undos slide.new
assert_eq!(s.doc().unwrap().doc.slides.len(), 1);
s.execute("edit.undo", &json!({})).unwrap(); // undos design.background
let s0_reverted = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
assert_eq!(s0_reverted["background"], "#121826");
}
#[test]
fn background_copy_from_slide_following_master_preserves_master_and_layout_backgrounds() {
let mut s = Session::with_new();
s.execute("file.new", &json!({"theme": "Nocturne"})).unwrap();
s.execute("slide.new", &json!({"layout": "titleAndContent"})).unwrap();
let custom_layout_bg = Background::Fill { fill: Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(0x22, 0x22, 0x22))) };
s.edit(|doc, _| {
let m = Arc::make_mut(&mut doc.masters[0]);
m.layouts[0].background = Some(custom_layout_bg.clone());
Ok(())
})
.unwrap();
// Slide 0 follows master (background: None)
assert!(s.doc().unwrap().doc.slides[0].background.is_none());
// Give Slide 1 an explicit override
s.execute("design.background", &json!({"color": "#FF0000", "index": 1})).unwrap();
assert!(s.doc().unwrap().doc.slides[1].background.is_some());
let orig_master_bg = s.doc().unwrap().doc.masters[0].background.clone();
assert!(orig_master_bg.is_some());
// Select slide 0 (which follows master) and apply copy to all
s.execute("slide.go", &json!({"index": 0})).unwrap();
let n = undo_len(&s);
s.execute("design.background", &json!({"copy": true})).unwrap();
assert_eq!(undo_len(&s), n + 1);
// Slide 1 has been reset to None (follows master), slide 0 remains None
let doc = &s.doc().unwrap().doc;
assert!(doc.slides[0].background.is_none());
assert!(doc.slides[1].background.is_none());
// Master and layout backgrounds survived!
assert_eq!(doc.masters[0].background, orig_master_bg);
assert_eq!(doc.masters[0].layouts[0].background, Some(custom_layout_bg));
// Idempotency: re-applying copy is a no-op
s.execute("design.background", &json!({"copy": true})).unwrap();
assert_eq!(undo_len(&s), n + 1, "re-copying when already matching is a no-op");
}
#[test]
fn background_reset_all_preserves_master_and_layout_backgrounds() {
let mut s = Session::with_new();
s.execute("file.new", &json!({"theme": "Nocturne"})).unwrap();
s.execute("slide.new", &json!({"layout": "titleAndContent"})).unwrap();
let custom_layout_bg = Background::Fill { fill: Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(0x33, 0x33, 0x33))) };
s.edit(|doc, _| {
let m = Arc::make_mut(&mut doc.masters[0]);
m.layouts[0].background = Some(custom_layout_bg.clone());
Ok(())
})
.unwrap();
let orig_master_bg = s.doc().unwrap().doc.masters[0].background.clone();
assert!(orig_master_bg.is_some());
// Set explicit backgrounds on both slides individually (master remains untouched)
s.execute("design.background", &json!({"color": "#0D0D0D", "index": 0})).unwrap();
s.execute("design.background", &json!({"color": "#0D0D0D", "index": 1})).unwrap();
assert!(s.doc().unwrap().doc.slides[0].background.is_some());
assert!(s.doc().unwrap().doc.slides[1].background.is_some());
// Now perform reset with all
let n = undo_len(&s);
s.execute("design.background", &json!({"reset": true, "all": true})).unwrap();
assert_eq!(undo_len(&s), n + 1);
// Slides reset to None to follow master
let doc = &s.doc().unwrap().doc;
assert!(doc.slides[0].background.is_none());
assert!(doc.slides[1].background.is_none());
// Master and layout backgrounds survived!
assert_eq!(doc.masters[0].background, orig_master_bg);
assert_eq!(doc.masters[0].layouts[0].background, Some(custom_layout_bg));
// Idempotency: re-running reset all is a no-op
s.execute("design.background", &json!({"reset": true, "all": true})).unwrap();
assert_eq!(undo_len(&s), n + 1, "re-resetting when already reset is a no-op");
}
#[test]
fn background_all_only_touches_used_masters() {
let mut s = Session::with_new();
s.execute("file.new", &json!({"theme": "Nocturne"})).unwrap();
// Add a second master to presentation
let second_master_bg = Background::Fill { fill: Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(0x55, 0x55, 0x55))) };
s.edit(|doc, _| {
let mut m2 = (*doc.masters[0]).clone();
m2.id = deckcraft_model::MasterId(999);
m2.background = Some(second_master_bg.clone());
doc.masters.push(Arc::new(m2));
Ok(())
})
.unwrap();
assert_eq!(s.doc().unwrap().doc.masters.len(), 2);
// Slides only use master 0 (default layout)
s.execute("design.background", &json!({"color": "#AA0000", "all": true})).unwrap();
let doc = &s.doc().unwrap().doc;
// Master 0 updated
assert_eq!(doc.masters[0].background, doc.slides[0].background);
// Master 1 preserved!
assert_eq!(doc.masters[1].background, Some(second_master_bg));
}
#[test]
fn background_all_clears_layout_overrides_even_if_slides_and_master_match() {
let mut s = Session::with_new();
s.execute("file.new", &json!({"theme": "Nocturne"})).unwrap();
// Set all slides and master to #AA0000
s.execute("design.background", &json!({"color": "#AA0000", "all": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.masters[0].background, s.doc().unwrap().doc.slides[0].background);
// Add a layout override on layout 0
let custom_bg = Background::Fill { fill: Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(0x12, 0x34, 0x56))) };
s.edit(|doc, _| {
let m = Arc::make_mut(&mut doc.masters[0]);
m.layouts[0].background = Some(custom_bg);
Ok(())
})
.unwrap();
// Re-run Apply to All with #AA0000. Must not be skipped as no-op; must clear layout override.
let n = undo_len(&s);
s.execute("design.background", &json!({"color": "#AA0000", "all": true})).unwrap();
assert_eq!(undo_len(&s), n + 1, "should execute and clear layout override, not treat as no-op");
let doc = &s.doc().unwrap().doc;
assert!(doc.masters[0].layouts[0].background.is_none());
// Now that layout override is cleared, repeating is an actual no-op
s.execute("design.background", &json!({"color": "#AA0000", "all": true})).unwrap();
assert_eq!(undo_len(&s), n + 1, "now it is truly a no-op");
}
#[test]
fn background_rejects_invalid_index() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({})).unwrap();
s.execute("slide.go", &json!({"index": 0})).unwrap();
let before = s.doc().unwrap().doc.slides[0].background.clone();
for bad in [json!(-1), json!(1.5)] {
assert!(s.execute("design.background", &json!({"color": "#0000C8", "index": bad})).is_err());
assert!(s.execute("design.background", &json!({"transparency": 0.5, "index": bad})).is_err());
assert_eq!(s.doc().unwrap().doc.slides[0].background, before);
}
}
+62 -439
View File
@@ -1,65 +1,38 @@
//! Edit menu: undo/redo, clipboard, duplicate, delete, select all.
use std::collections::HashMap;
use std::sync::Arc;
use deckcraft_model::text::TextBody;
use deckcraft_model::{MediaId, Shape, ShapeId, Slide, SlideId};
use serde_json::{Value, json};
use super::{
CommandSpec, NO_ID_SPACE, bad, base64_encode, bool_or, can_redo, can_undo, cmd, has_doc, has_selection, has_slide, id_param, ids_param, ok,
richclip, str_param, targets, xfrm_of,
};
use super::*;
use crate::{HistoryEntry, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, undo),
cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Y"), "{}", can_redo, redo),
cmd!("edit.cut", "Cut", ["Home", "Clipboard"], Some("Cmd+X"), "{scope?: slides} → {text, html?}", has_doc, cut),
cmd!(noundo "edit.copy", "Copy", ["Home", "Clipboard"], Some("Cmd+C"), "{scope?: slides} → {text, html?}", has_doc, copy),
cmd!(
"edit.paste",
"Paste",
["Home", "Clipboard"],
Some("Cmd+V"),
"{text?: plain text to paste, html?: rich text from another app, scope?: slides}",
has_doc,
paste
),
cmd!(
"edit.pasteSpecial",
"Paste Special",
["Home", "Clipboard"],
None,
"{as: destinationTheme|keepSource|picture|text} — Use Destination Theme, Keep Source Formatting, Picture (PNG), Keep Text Only",
has_doc,
paste_special
),
cmd!("edit.cut", "Cut", ["Home", "Clipboard"], Some("Cmd+X"), "{scope?: slides}", has_doc, cut),
cmd!(noundo "edit.copy", "Copy", ["Home", "Clipboard"], Some("Cmd+C"), "{scope?: slides} → {text}", has_doc, copy),
cmd!("edit.paste", "Paste", ["Home", "Clipboard"], Some("Cmd+V"), "{text?: plain text to paste, scope?: slides}", has_doc, paste),
cmd!("edit.pasteText", "Paste and Match Formatting", ["Edit"], Some("Cmd+Shift+V"), "{text?}", has_doc, paste_text),
cmd!("edit.duplicate", "Duplicate", ["Edit"], Some("Cmd+D"), "{ids?}", has_selection, duplicate),
cmd!("edit.delete", "Delete", ["Edit"], Some("Delete"), "{ids?, scope?: slides}", has_doc, delete),
cmd!(noundo "edit.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{scope?: slides}", has_slide, select_all),
cmd!(noundo "edit.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{}", has_slide, select_all),
cmd!(noundo "edit.deselect", "Deselect", [], Some("Escape"), "{}", has_doc, deselect),
cmd!(noundo "edit.select", "Select Objects", [], None, "{ids: [id], add?: bool, toggle?: bool}", has_slide, select),
]
}
fn restore(s: &mut Session, redo: bool) -> Result<Value> {
let vertex_kind = s.tool.vertex_kind.clone();
let st = s.doc_mut()?;
let (from, to) = if redo { (&mut st.history.redo, &mut st.history.undo) } else { (&mut st.history.undo, &mut st.history.redo) };
let Some(e) = from.pop() else { return ok() };
to.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone(), vertex_kind });
to.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
st.doc = e.doc;
st.selection = e.selection;
st.interaction = None;
// A later shape can get an undone copy's id: Duplicate starts over with the usual offset.
st.last_duplicate = None;
st.revision += 1;
// The point type Edit Points remembered with the restored document: handle drags follow it.
s.tool.vertex_kind = e.vertex_kind;
Ok(json!({"label": e.label}))
}
@@ -75,6 +48,24 @@ fn slides_scope(s: &Session, p: &Value) -> bool {
|| s.active().is_some_and(|d| d.selection.shapes.is_empty() && d.selection.text.is_none() && !d.selection.slides.is_empty())
}
fn media_of_shapes(shapes: &[Shape], out: &mut Vec<MediaId>) {
deckcraft_model::walk(shapes, &mut |s, _| {
match &s.kind {
deckcraft_model::ShapeKind::Picture { fill } => out.push(fill.media),
deckcraft_model::ShapeKind::Media(m) => {
out.push(m.media);
if let Some(p) = m.poster {
out.push(p);
}
}
_ => {}
}
if let Some(deckcraft_model::Fill::Picture(pf)) = &s.fill {
out.push(pf.media);
}
});
}
fn copy_inner(s: &mut Session, p: &Value) -> Result<String> {
let st = s.doc()?;
// Text selection.
@@ -95,19 +86,14 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result<String> {
let slides: Vec<Slide> = ids.iter().filter_map(|id| st.doc.slide(*id).cloned()).collect();
let mut mids = vec![];
for sl in &slides {
mids.extend(crate::media_refs::slide_media(sl));
media_of_shapes(&sl.shapes, &mut mids);
}
let media = st.doc.media.iter().filter(|m| mids.contains(&m.id)).cloned().collect();
let plain = slides.iter().map(|x| x.title()).collect::<Vec<_>>().join("\n");
s.clipboard = crate::Clipboard { slides, media, plain: plain.clone(), ..Default::default() };
return Ok(plain);
}
// Selected table cells copy as their text: a tab between cells and a paragraph per row.
if let Some(plain) = super::table::selected_cells_text(st).filter(|_| p.get("id").is_none() && p.get("ids").is_none()) {
s.clipboard = crate::Clipboard { text: Some(TextBody::from_text(&plain)), plain: plain.clone(), ..Default::default() };
return Ok(plain);
}
let mut shapes: Vec<Shape> = st
let shapes: Vec<Shape> = st
.selection
.shapes
.iter()
@@ -120,180 +106,60 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result<String> {
})
})
.collect();
// Copying is the last chance to read what a placeholder inherits: a cut removes it, and the
// paste can be in another deck. Slide Master view pastes the originals instead.
let placeholders: Vec<Shape> = shapes.iter().filter(|x| x.ph.is_some()).cloned().collect();
detach_on_slide(&st.doc, &st.selection, &mut shapes);
let mids = crate::media_refs::shapes_media(&shapes);
let mut mids = vec![];
media_of_shapes(&shapes, &mut mids);
let media = st.doc.media.iter().filter(|m| mids.contains(&m.id)).cloned().collect();
let plain = shapes.iter().filter_map(|x| x.text.as_ref().map(|t| t.text())).collect::<Vec<_>>().join("\n");
// The theme of what is being edited: a slide's or layout's colour map, else the master's.
let source_theme = super::text::ctx_for(&st.doc, &st.selection).map(|ctx| crate::SourceTheme {
colors: ctx.master.theme.colors.clone(),
color_map: ctx.color_map.clone(),
fonts: ctx.master.theme.fonts.clone(),
});
s.clipboard = crate::Clipboard { shapes, placeholders, media, plain: plain.clone(), source_theme, ..Default::default() };
s.clipboard = crate::Clipboard { shapes, media, plain: plain.clone(), ..Default::default() };
Ok(plain)
}
/// On a slide, a copy of a placeholder is a regular shape: give `shapes` the look they inherit
/// there. In Slide Master view a copy stays a placeholder, so this changes nothing.
pub(crate) fn detach_on_slide(doc: &deckcraft_model::Presentation, sel: &crate::Selection, shapes: &mut [Shape]) {
if sel.target == crate::Target::Slides
&& let Some(ctx) = super::text::ctx_for(doc, sel)
{
shapes.iter_mut().for_each(|sh| deckcraft_model::resolve::detach_placeholder(&ctx, sh));
}
}
fn copying_caret(s: &Session) -> bool {
s.active().is_some_and(|d| d.selection.text.as_ref().is_some_and(|t| !t.is_range()))
}
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
// A caret copies nothing; the previous clipboard must not leak into this answer.
let caret = copying_caret(s);
let t = copy_inner(s, p)?;
let html = if caret { String::new() } else { copied_html(s) };
Ok(json!({"text": t, "html": html}))
}
/// HTML for what was just copied, when it is text (a selection, or the text on the copied shapes).
fn copied_html(s: &Session) -> String {
if let Some(body) = &s.clipboard.text {
return richclip::body_to_html(body);
}
let mut paragraphs = Vec::new();
for sh in &s.clipboard.shapes {
if let Some(t) = &sh.text {
paragraphs.extend(t.paragraphs.clone());
}
}
if paragraphs.is_empty() {
return String::new();
}
richclip::body_to_html(&TextBody { paragraphs, ..Default::default() })
Ok(json!({"text": t}))
}
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
let caret = copying_caret(s);
let t = copy_inner(s, p)?;
if caret {
// Nothing is selected, so there is nothing to cut; `delete` would remove the next character.
return Ok(json!({"text": t, "html": ""}));
}
let html = copied_html(s);
delete(s, p)?;
Ok(json!({"text": t, "html": html}))
Ok(json!({"text": t}))
}
/// Give pasted shapes fresh ids (groups included) and return the old-to-new map. Connector ends
/// attached to a shape that was copied too follow its copy; ends attached to a shape outside the
/// copied set are detached (the connector keeps its geometry), so a copy never stays glued to
/// the original or to an unrelated shape that happens to share an id in another deck.
pub(crate) fn reid(cmd: &str, doc: &mut deckcraft_model::Presentation, shapes: &mut [Shape]) -> Result<HashMap<ShapeId, ShapeId>> {
fn rec(
cmd: &str,
doc: &mut deckcraft_model::Presentation,
shapes: &mut [Shape],
map: &mut HashMap<ShapeId, ShapeId>,
depth: usize,
) -> Result<()> {
if depth > 64 {
return Ok(());
}
for s in shapes {
let id = ShapeId(doc.alloc_id().ok_or_else(|| bad(cmd, NO_ID_SPACE))?);
map.insert(s.id, id);
s.id = id;
if let Some(ch) = s.children_mut() {
rec(cmd, doc, ch, map, depth + 1)?;
}
}
Ok(())
}
let mut map = HashMap::new();
rec(cmd, doc, shapes, &mut map, 0)?;
walk_mut(shapes, &mut |s| {
if let deckcraft_model::ShapeKind::Connector { start, end } = &mut s.kind {
for e in [start, end] {
*e = e.and_then(|(id, site)| map.get(&id).map(|n| (*n, site)));
}
}
});
Ok(map)
}
/// Point copied animations at the copies: targets and triggers in `map` follow it; an animation
/// whose target wasn't copied is dropped, and a trigger that wasn't copied is cleared.
pub(crate) fn remap_animations(anims: &mut Vec<deckcraft_model::Animation>, map: &HashMap<ShapeId, ShapeId>) {
anims.retain_mut(|a| {
let Some(n) = map.get(&a.shape) else { return false };
a.shape = *n;
a.trigger = a.trigger.and_then(|t| map.get(&t).copied());
true
});
}
/// Visit every shape mutably, depth-first (groups included, depth-bounded like `walk`).
fn walk_mut(shapes: &mut [Shape], f: &mut dyn FnMut(&mut Shape)) {
fn rec(shapes: &mut [Shape], f: &mut dyn FnMut(&mut Shape), depth: usize) {
/// Give pasted shapes fresh ids (groups included) and map connector ends.
pub(crate) fn reid(doc: &mut deckcraft_model::Presentation, shapes: &mut [Shape]) {
fn rec(doc: &mut deckcraft_model::Presentation, shapes: &mut [Shape], depth: usize) {
if depth > 64 {
return;
}
for s in shapes {
f(s);
s.id = ShapeId(doc.alloc_id());
if let Some(ch) = s.children_mut() {
rec(ch, f, depth + 1);
rec(doc, ch, depth + 1);
}
}
}
rec(shapes, f, 0);
rec(doc, shapes, 0);
}
/// Rewrite a media id the clipboard used (`map`: clipboard id to destination id).
fn remap_media(map: &HashMap<MediaId, MediaId>) -> impl FnMut(&mut MediaId) + '_ {
move |id: &mut MediaId| {
if let Some(n) = map.get(id) {
*id = *n;
}
}
}
/// Add the clipboard's media to `doc` and return the ids that changed: an id already used in
/// `doc` by other bytes (another deck) gets a fresh id, and the pasted shapes must use it.
fn bring_media(cmd: &str, doc: &mut deckcraft_model::Presentation, media: &[deckcraft_model::MediaItem]) -> Result<HashMap<MediaId, MediaId>> {
let mut map = HashMap::new();
fn bring_media(doc: &mut deckcraft_model::Presentation, media: &[deckcraft_model::MediaItem]) {
for m in media {
match doc.media(m.id) {
None => {
// Keeps the foreign id, so later ids must start past it.
if doc.media(m.id).is_none_or(|x| x.data != m.data) {
if doc.media(m.id).is_none() {
doc.media.push(m.clone());
doc.next_id = doc.next_id.max(m.id.0);
}
Some(x) if x.data == m.data => {}
Some(_) => {
let id = doc.add_media(&m.name, &m.content_type, m.data.as_ref().clone()).ok_or_else(|| bad(cmd, NO_ID_SPACE))?;
map.insert(m.id, id);
} else {
// Id clash with different bytes: unusual (other deck); keep ours, add theirs as new.
let id = doc.add_media(&m.name, &m.content_type, m.data.as_ref().clone());
let _ = id;
}
}
}
Ok(map)
}
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
// External plain text (from the system clipboard) wins when given and differs from ours.
// HTML from Pages or Keynote keeps bold, italic and underline when it says the same words.
if let Some(t) = str_param(p, "text")
&& t != s.clipboard.plain
{
if let Some(html) = str_param(p, "html")
&& let Some(body) = richclip::html_to_body(html)
&& richclip::same_words(&body.text(), t)
{
return paste_external_body(s, &body);
}
return paste_plain(s, t);
}
let editing = s.doc()?.selection.text.is_some();
@@ -308,14 +174,12 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
if !clip.slides.is_empty() {
let at = s.doc()?.selection.slide + 1;
return s.edit(|doc, sel| {
let media = bring_media("edit.paste", doc, &clip.media)?;
bring_media(doc, &clip.media);
let mut new_ids = vec![];
for (k, sl) in clip.slides.iter().enumerate() {
let mut sl = sl.clone();
sl.id = SlideId(doc.alloc_id().ok_or_else(|| bad("edit.paste", NO_ID_SPACE))?);
let map = reid("edit.paste", doc, &mut sl.shapes)?;
remap_animations(&mut sl.animations, &map);
crate::media_refs::visit_mut::slide(&mut sl, &mut remap_media(&media));
sl.id = SlideId(doc.alloc_id());
reid(doc, &mut sl.shapes);
if doc.layout(sl.layout).is_none() {
sl.layout = doc.masters.first().and_then(|m| m.layouts.first()).map(|l| l.id).unwrap_or_default();
}
@@ -336,38 +200,15 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
let same_slide = s.doc().ok().is_some_and(|d| clip.shapes.iter().any(|c| d.shape(c.id).is_some()));
let off = if same_slide { off } else { 0.0 };
return s.edit(|doc, sel| {
let media = bring_media("edit.paste", doc, &clip.media)?;
bring_media(doc, &clip.media);
let mut shapes = clip.shapes.clone();
if sel.target != crate::Target::Slides {
for sh in &mut shapes {
if let Some(original) = clip.placeholders.iter().find(|p| p.id == sh.id) {
sh.clone_from(original);
}
}
}
reid("edit.paste", doc, &mut shapes)?;
crate::media_refs::visit_mut::shapes(&mut shapes, &mut remap_media(&media));
let (mut taken, mut count) = super::current_names(doc, sel);
reid(doc, &mut shapes);
for sh in &mut shapes {
// Only a name already on the slide is changed (two shapes with one name are what the
// issue is about); otherwise it stays, as Morph pairs shapes across slides by name.
if taken.contains(&sh.name)
&& let Some((base, n)) = sh.name.rsplit_once(' ')
&& !n.is_empty()
&& n.bytes().all(|b| b.is_ascii_digit())
{
sh.name = super::insert::first_free_name(base, &taken, count);
}
deckcraft_model::walk(std::slice::from_ref(sh), &mut |m, _| {
taken.insert(m.name.clone());
count += 1;
});
if let Some(x) = sh.xfrm.as_mut() {
x.x += off;
x.y += off;
}
// A placeholder pasted on a slide becomes a regular shape. One copied from a slide
// already has its look; see `copy_inner`.
// A pasted placeholder becomes a regular shape keeping its look.
if sh.ph.is_some() && sel.target == crate::Target::Slides {
sh.ph = None;
}
@@ -387,33 +228,6 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
fn paste_external_body(s: &mut Session, body: &TextBody) -> Result<Value> {
if s.doc()?.selection.text.is_some() {
return super::text::paste_body(s, body);
}
let plain = body.text();
let st = s.doc()?;
let size = st.doc.slide_size;
let rect = [size.width * 0.25, size.height * 0.4, size.width * 0.5, 40.0];
let made = s.execute("insert.textBox", &json!({"rect": rect, "text": plain}))?;
let raw = made.get("id").and_then(Value::as_u64).ok_or_else(|| bad("edit.paste", "no text box"))?;
let id = u32::try_from(raw).map_err(|_| bad("edit.paste", "no text box"))?;
let body = body.clone();
s.edit(|doc, sel| {
let list = crate::shapes_mut(doc, sel).ok_or_else(|| bad("edit.paste", "no slide"))?;
let sh = deckcraft_model::find_shape_mut(list, ShapeId(id)).ok_or_else(|| bad("edit.paste", "no text box"))?;
if let Some(t) = sh.text.as_mut() {
let (wrap, autofit) = (t.body.wrap, t.body.autofit);
*t = body.clone();
t.body.wrap = wrap;
t.body.autofit = autofit;
}
sel.shapes = vec![ShapeId(id)];
sel.text = None;
Ok(json!({"id": id}))
})
}
fn paste_plain(s: &mut Session, text: &str) -> Result<Value> {
if s.doc()?.selection.text.is_some() {
return super::text::insert_text(s, text, None);
@@ -425,187 +239,37 @@ fn paste_plain(s: &mut Session, text: &str) -> Result<Value> {
s.execute("insert.textBox", &json!({"rect": rect, "text": text}))
}
fn paste_special(s: &mut Session, p: &Value) -> Result<Value> {
match str_param(p, "as").unwrap_or("destinationTheme") {
"destinationTheme" | "useDestinationTheme" => paste(s, &json!({})),
"text" | "keepTextOnly" => paste_text(s, &json!({})),
"keepSource" | "keepSourceFormatting" => {
let saved = s.clipboard.clone();
if let Some(theme) = &saved.source_theme {
bake_theme(&mut s.clipboard.shapes, theme);
bake_theme(&mut s.clipboard.placeholders, theme);
}
let r = paste(s, &json!({}));
let pastes = s.clipboard.pastes;
s.clipboard = saved;
s.clipboard.pastes = pastes;
r
}
"picture" => paste_picture(s),
other => Err(bad("edit.pasteSpecial", format!("unknown `as`: {other} (destinationTheme, keepSource, picture, text)"))),
}
}
/// Replace theme colours and theme fonts with the values they have in `scheme` / `fonts`, so the
/// shapes keep their look under another theme.
pub(crate) fn bake_theme(shapes: &mut [Shape], theme: &crate::SourceTheme) {
fn rec(v: &mut Value, theme: &crate::SourceTheme, depth: usize) {
if depth > 256 {
return;
}
match v {
Value::Object(o) => {
if o.get("kind").and_then(Value::as_str) == Some("scheme")
&& let Some(slot) = o.get("slot").and_then(|x| serde_json::from_value::<deckcraft_color::SchemeSlot>(x.clone()).ok())
&& slot != deckcraft_color::SchemeSlot::PhClr
&& let Ok(rgb) = serde_json::to_value(theme.colors.get(deckcraft_model::map_slot(&theme.color_map, slot)))
{
o.clear();
o.insert("kind".into(), json!("rgb"));
o.insert("rgb".into(), rgb);
return;
}
for x in o.values_mut() {
rec(x, theme, depth + 1);
}
}
Value::Array(a) => a.iter_mut().for_each(|x| rec(x, theme, depth + 1)),
Value::String(t) if t.starts_with('+') => {
let set = match t.get(1..3) {
Some("mj") => &theme.fonts.major,
Some("mn") => &theme.fonts.minor,
_ => return,
};
let face = match t.get(3..) {
Some("-lt") => &set.latin,
Some("-ea") => &set.ea,
Some("-cs") => &set.cs,
_ => return,
};
if !face.is_empty() {
*t = face.clone();
}
}
_ => {}
}
}
for sh in shapes.iter_mut() {
let Ok(mut v) = serde_json::to_value(&*sh) else { continue };
rec(&mut v, theme, 0);
if let Ok(baked) = serde_json::from_value::<Shape>(v) {
*sh = baked;
}
}
}
/// Paste Special › Picture: the copied shapes drawn into one PNG picture.
fn paste_picture(s: &mut Session) -> Result<Value> {
let mut clip = s.clipboard.clone();
if clip.shapes.is_empty() {
return Err(bad("edit.pasteSpecial", "copy shapes first to paste them as a picture"));
}
if let Some(theme) = &clip.source_theme {
bake_theme(&mut clip.shapes, theme);
}
let st = s.doc()?;
let mut doc = (*st.doc).clone();
let media = bring_media("edit.pasteSpecial", &mut doc, &clip.media)?;
crate::media_refs::visit_mut::shapes(&mut clip.shapes, &mut remap_media(&media));
let mut slide = st.current_slide().cloned().ok_or_else(|| bad("edit.pasteSpecial", "no slide"))?;
let xs: Vec<deckcraft_geom::Xfrm> = clip.shapes.iter().filter_map(|x| x.xfrm).collect();
let b = super::arrange::union_bounds(&xs).ok_or_else(|| bad("edit.pasteSpecial", "nothing to draw"))?;
let gx = deckcraft_geom::Xfrm::new(b.x0, b.y0, b.width(), b.height());
let gid = ShapeId(u32::MAX - 1);
let one = if clip.shapes.len() == 1 {
let mut sh = clip.shapes[0].clone();
sh.id = gid;
sh
} else {
Shape { id: gid, xfrm: Some(gx), kind: deckcraft_model::ShapeKind::Group { children: clip.shapes.clone(), child: gx }, ..Default::default() }
};
slide.shapes = vec![one];
const SCALE: f64 = 2.0;
let img = deckcraft_render::render_shape(&doc, &slide, gid, SCALE).ok_or_else(|| bad("edit.pasteSpecial", "the shapes could not be drawn"))?;
// render_shape draws the bounds plus an 8 pt margin (room for shadows and outlines).
let (w, h) = (img.width as f64 / SCALE, img.height as f64 / SCALE);
let same_slide = clip.shapes.iter().any(|c| st.shape(c.id).is_some());
let off = if same_slide { s.prefs.duplicate_offset } else { 0.0 };
let png = img.to_png();
s.execute("insert.picture", &json!({"data": base64_encode(&png), "name": "Picture.png", "rect": [b.x0 - 8.0 + off, b.y0 - 8.0 + off, w, h]}))
}
fn paste_text(s: &mut Session, p: &Value) -> Result<Value> {
let t = str_param(p, "text").map(String::from).unwrap_or_else(|| s.clipboard.plain.clone());
paste_plain(s, &t)
}
/// Duplicate gives a copy the next automatic name ("Rectangle 4" after "Rectangle 1"), as
/// PowerPoint does, and keeps a name the user chose. PowerPoint tells the two apart by comparing
/// the number with the shape's id; ids here are numbered across the deck, so any "{kind} {n}"
/// counts as automatic.
fn rename_automatic(sh: &mut Shape, taken: &mut std::collections::HashSet<String>, count: usize) {
let base = if sh.is_group() { "Group".to_string() } else { super::insert::auto_name_base(sh) };
let n = sh.name.strip_prefix(&base).and_then(|r| r.strip_prefix(' '));
if n.is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) {
sh.name = super::insert::first_free_name(&base, taken, count);
taken.insert(sh.name.clone());
}
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let ids = targets(s, p)?;
let off = s.prefs.duplicate_offset;
let last = s.doc()?.last_duplicate.clone();
let (new_ids, made) = s.edit(|doc, sel| {
s.edit(|doc, sel| {
let list = super::current_shapes(doc, sel).cloned().unwrap_or_default();
let mut copies: Vec<Shape> = list.iter().filter(|x| ids.contains(&x.id)).cloned().collect();
let sources: Vec<ShapeId> = copies.iter().map(|c| c.id).collect();
let boxes: Vec<_> = copies.iter().map(|c| xfrm_of(doc, sel, c)).collect();
detach_on_slide(doc, sel, &mut copies);
// Duplicating the copies of the last Duplicate again repeats how far they were moved
// since (#966); anything else gets the usual offset.
let (dx, dy) = last
.filter(|(slide, target, pairs)| {
*slide == sel.slide && *target == sel.target && pairs.len() == sources.len() && pairs.iter().all(|(_, c)| sources.contains(c))
})
.and_then(|(_, _, pairs)| {
let (src, copy) = pairs.first()?;
let a = xfrm_of(doc, sel, list.iter().find(|x| x.id == *src)?);
let b = xfrm_of(doc, sel, list.iter().find(|x| x.id == *copy)?);
let d = (b.x - a.x, b.y - a.y);
(d.0.is_finite() && d.1.is_finite()).then_some(d)
})
.unwrap_or((off, off));
reid("edit.duplicate", doc, &mut copies)?;
// Every name on the slide, group members included, so a copy never repeats one.
let mut taken = std::collections::HashSet::new();
let mut count = 0;
deckcraft_model::walk(&list, &mut |sh, _| {
taken.insert(sh.name.clone());
count += 1;
});
walk_mut(&mut copies, &mut |c| {
rename_automatic(c, &mut taken, count);
count += 1;
});
reid(doc, &mut copies);
for (c, b) in copies.iter_mut().zip(boxes) {
let mut x = b;
x.x += dx;
x.y += dy;
x.x += off;
x.y += off;
c.xfrm = Some(x);
if sel.target == crate::Target::Slides {
c.ph = None;
}
if !c.name.is_empty() {
c.name = format!("{} copy", c.name.trim_end_matches(" copy"));
}
}
let new_ids: Vec<ShapeId> = copies.iter().map(|c| c.id).collect();
let shapes = crate::shapes_mut(doc, sel).ok_or_else(|| bad("edit.duplicate", "no slide"))?;
shapes.extend(copies);
sel.shapes = new_ids.clone();
let made = (sel.slide, sel.target, sources.into_iter().zip(new_ids.iter().copied()).collect());
Ok((new_ids, made))
})?;
s.doc_mut()?.last_duplicate = Some(made);
Ok(json!({"ids": new_ids}))
Ok(json!({"ids": new_ids}))
})
}
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
@@ -615,35 +279,18 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
if slides_scope(s, p) && ids_param(p, "ids").is_none() {
return s.execute("slide.delete", &json!({}));
}
// With table cells selected, Delete clears their text and keeps the table, as in PowerPoint.
let sel = &s.doc()?.selection;
if ids_param(p, "ids").is_none() && p.get("id").is_none() && sel.cells.is_some_and(|c| sel.shapes == [c.0]) {
return super::table::clear_selected_cells(s);
}
let ids = targets(s, p)?;
if ids.is_empty() {
return ok();
}
s.edit(|doc, sel| {
let shapes = crate::shapes_mut(doc, sel).ok_or_else(|| bad("edit.delete", "no slide"))?;
let mut before = Vec::new();
deckcraft_model::walk(shapes, &mut |s, _| before.push(s.id));
let n = remove_shapes(shapes, &ids);
// Everything that is gone: the given ids plus group descendants and emptied groups.
let mut left = Vec::new();
deckcraft_model::walk(shapes, &mut |s, _| left.push(s.id));
let mut gone = ids.clone();
gone.extend(before.into_iter().filter(|i| !left.contains(i)));
// Animations of deleted shapes go too.
if sel.target == crate::Target::Slides
&& let Some(sl) = doc.slides.get_mut(sel.slide)
{
let sl = Arc::make_mut(sl);
sl.animations.retain(|a| !gone.contains(&a.shape));
// Effects triggered by a deleted shape fall back to the main sequence.
for a in sl.animations.iter_mut().filter(|a| a.trigger.is_some_and(|t| gone.contains(&t))) {
a.trigger = None;
}
Arc::make_mut(sl).animations.retain(|a| !ids.contains(&a.shape));
}
sel.shapes.retain(|i| !ids.contains(i));
sel.text = None;
@@ -676,12 +323,7 @@ fn count(v: &[Shape]) -> usize {
n
}
fn select_all(s: &mut Session, p: &Value) -> Result<Value> {
match p.get("scope") {
None | Some(Value::Null) => {}
Some(Value::String(v)) if v == "slides" => return select_all_slides(s),
Some(_) => return Err(bad("edit.selectAll", "scope must be \"slides\"")),
}
fn select_all(s: &mut Session, _p: &Value) -> Result<Value> {
if s.doc()?.selection.text.is_some() {
return s.execute("text.selectAll", &json!({}));
}
@@ -693,22 +335,6 @@ fn select_all(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"ids": ids}))
}
/// Thumbnail-pane / sorter select all: every slide, hidden ones included. The current
/// slide stays where it is (the canvas must not jump), so this is not `slide.selectSlides`.
fn select_all_slides(s: &mut Session) -> Result<Value> {
if s.doc()?.selection.target != crate::Target::Slides {
return Err(bad("edit.selectAll", "the slide list is not shown while editing a master"));
}
let ids: Vec<SlideId> = s.doc()?.doc.slides.iter().map(|x| x.id).collect();
s.select(|_, sel| {
sel.slides = ids.clone();
sel.shapes.clear();
sel.text = None;
sel.cells = None;
})?;
Ok(json!({"selected": ids}))
}
fn deselect(s: &mut Session, _p: &Value) -> Result<Value> {
s.painter = None;
s.anim_painter = None;
@@ -727,10 +353,7 @@ fn deselect(s: &mut Session, _p: &Value) -> Result<Value> {
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let ids = match ids_param(p, "ids") {
Some(v) => v,
None => id_param(p, "id", "edit.select")?.map(|i| vec![i]).unwrap_or_default(),
};
let ids = ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])).unwrap_or_default();
let add = bool_or(p, "add", false);
let toggle = bool_or(p, "toggle", false);
let valid: Vec<ShapeId> = ids.into_iter().filter(|i| s.active().is_some_and(|d| d.shape(*i).is_some())).collect();
+63 -533
View File
@@ -1,62 +1,22 @@
//! File menu: new, open, save, export, close, properties.
use std::collections::HashMap;
use std::sync::Arc;
use deckcraft_media::MediaInfo;
use deckcraft_model::{MediaId, MediaItem, Presentation, Shape, ShapeKind, defaults};
use deckcraft_model::{Presentation, defaults};
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, base64_decode, base64_encode, bool_or, cmd, f64_or, has_doc, ok, opt_usize_param, str_param, usize_param};
use super::*;
use crate::{DocState, EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
noundo "file.new",
"New Presentation",
["File"],
Some("Cmd+N"),
"{theme?: name, template?: starter name, size?: [w,h] pt, blank?: bool}",
always,
new
),
cmd!(query "file.templates", "Starter Templates", [], None, "{} → [{name, summary, theme, slides}]", always, templates),
cmd!(noundo "file.new", "New Presentation", ["File"], Some("Cmd+N"), "{theme?: name, size?: [w,h] pt, blank?: bool}", always, new),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path}", always, open),
cmd!(
noundo "file.adopt",
"Open",
[],
None,
"{path, token?} (a presentation the host read in the background and staged with Session::stage_loaded; without one, reads path like file.open)",
always,
adopt
),
cmd!(noundo "file.openBytes", "Open Data", [], None, "{name, data: base64}", always, open_bytes),
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?, format?: deckcraft|pptx}", has_doc, save),
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path, format?}", has_doc, save_as),
cmd!(noundo "file.saveTemplate", "Save as Template…", ["File"], None, "{path}", has_doc, save_as),
cmd!(query "file.saveBytes", "Save to Data", [], None, "{format?: deckcraft|pptx} → {data: base64}", has_doc, save_bytes_cmd),
cmd!(noundo "file.export", "Export…", ["File"], None, "{path, format?: png|jpeg|pptx|deckcraft|outline|rtf|pdf|gif (else by path), slide?: index, all?: bool, scale?: px per pt, layout?: slides|notes|handouts (pdf), perPage?: 1|2|3|4|6|9, paper?: letter|a4|legal|a3 (pdf), orientation?: portrait|landscape (pdf), dpi?, slides?: [index]|range (\"1-3,5\"), includeHidden?, textLayer?, frame?, transparentBackground?: bool (png: leave the slide background out), width?: px 16-3840|small|medium|large|extraLarge (gif), secondsPerSlide?: 0.1-600 (gif; 5), loop?: bool (gif; true: forever)} → {path, bytes} or {files} (png, jpeg); gif adds frames, width, height, secondsPerSlide", has_doc, export),
cmd!(
query "file.info",
"Info",
["File"],
None,
"{} → {title, path, format, dirty, slides, hiddenSlides, sections, bytes?, properties}",
has_doc,
info
),
cmd!(query "file.render", "Render Slide", [], None, "{slide?: index, scale?, edit?: bool, transparentBackground?: bool} → {png: base64, width, height}", has_doc, render),
cmd!(
query "slide.colorAt",
"Color At",
[],
None,
"{slide?: index, x, y (slide units), scale?: px per unit (2)} → {color: \"RRGGBB\", alpha: 0..255, x, y}: the colour drawn at a point of the slide (the Eyedropper)",
has_doc,
color_at
),
cmd!(noundo "file.export", "Export…", ["File"], None, "{path, format: png|jpeg|pptx|deckcraft|outline|pdf, slide?: index, all?: bool, scale?: px per pt; pdf: layout?: slides|notes|handouts, perPage?: 1|2|3|4|6|9, dpi?, slides?: [index], includeHidden?, textLayer?, frame?}", has_doc, export),
cmd!(query "file.render", "Render Slide", [], None, "{slide?: index, scale?, edit?: bool} → {png: base64, width, height}", has_doc, render),
cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{}", has_doc, close),
cmd!(
"file.properties",
@@ -70,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(noundo "file.recovery.save", "Save AutoRecover Information", [], None, "{} → {written}", has_doc, recovery_save),
cmd!(query "file.recovery.list", "Recovered Presentations", [], None, "{} → [{uid, path, title, saved}]", always, recovery_list),
cmd!(noundo "file.recovery.open", "Open Recovered Presentations", [], None, "{} → {opened: [document index]}", always, recovery_open),
cmd!(noundo "file.recovery.discard", "Discard Recovered Presentations", [], None, "{uid?: one entry (else all)}", always, recovery_discard),
cmd!(noundo "file.recovery.discard", "Discard Recovered Presentations", [], None, "{uid?: one entry, else all}", always, recovery_discard),
cmd!(noundo "file.revert", "Revert", [], None, "{}", has_doc, revert),
cmd!(noundo "window.next", "Next Window", ["Window"], Some("Cmd+`"), "{index?}", has_doc, next_window),
]
@@ -80,225 +40,60 @@ fn theme_named(name: &str) -> Option<deckcraft_model::Theme> {
deckcraft_model::theme::builtin_themes().into_iter().find(|t| t.name.eq_ignore_ascii_case(name))
}
fn slide_size(p: &Value) -> deckcraft_geom::Size {
p.get("size")
fn new(s: &mut Session, p: &Value) -> Result<Value> {
let theme = str_param(p, "theme").and_then(theme_named).unwrap_or_default();
let size = p
.get("size")
.and_then(Value::as_array)
.and_then(|a| Some(deckcraft_geom::Size::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?)))
.filter(|s| s.width >= 1.0 && s.height >= 1.0 && s.width < 5000.0 && s.height < 5000.0)
.unwrap_or(defaults::WIDE)
}
fn templates(_s: &mut Session, _p: &Value) -> Result<Value> {
Ok(json!({
"templates": crate::templates::starters().iter().map(|t| json!({
"name": t.name,
"summary": t.summary,
"theme": t.theme,
"slides": t.slides.len(),
})).collect::<Vec<_>>(),
}))
}
fn new(s: &mut Session, p: &Value) -> Result<Value> {
let template = str_param(p, "template").filter(|t| !t.is_empty());
let theme_name = str_param(p, "theme").filter(|t| !t.is_empty());
if template.is_some() && theme_name.is_some() {
return Err(bad("file.new", "pass `theme` or `template`, not both"));
}
if template.is_some() && bool_or(p, "blank", false) {
return Err(bad("file.new", "a template is not a blank presentation"));
}
let size = slide_size(p);
let (doc, template_name) = if let Some(name) = template {
let doc = crate::templates::build(name, size)?;
let chosen = crate::templates::find(name).map(|t| t.name);
(doc, chosen)
} else {
let theme = theme_name.and_then(theme_named).unwrap_or_default();
(defaults::blank_presentation(size, theme, !bool_or(p, "blank", false)), None)
};
let slides = doc.slides.len();
.unwrap_or(defaults::WIDE);
let doc = defaults::blank_presentation(size, theme, !bool_or(p, "blank", false));
let title = s.next_untitled();
let i = s.add_document(DocState::new(doc, None, title));
let mut out = json!({"document": i, "slides": slides});
if let Some(name) = template_name {
out["template"] = json!(name);
}
Ok(out)
Ok(json!({"document": i}))
}
/// Recognise and read presentation bytes (native, PPTX).
pub fn open_presentation(name: &str, bytes: &[u8]) -> Result<Presentation> {
open_checked(name, bytes).map(|(p, _)| p)
}
/// What a file lost on opening.
#[derive(Debug, Default, Clone)]
pub struct Damage {
/// Pictures and media a `.deckcraft` file had lost or damaged.
pub media: Vec<String>,
/// Slides a `.pptx` lists but that couldn't be read, so they are not in the presentation.
pub slides: Vec<String>,
}
impl Damage {
pub fn is_empty(&self) -> bool {
self.media.is_empty() && self.slides.is_empty()
}
}
/// [`open_presentation`], plus what the file had lost or damaged.
pub fn open_checked(name: &str, bytes: &[u8]) -> Result<(Presentation, Damage)> {
if deckcraft_format::sniff(bytes) {
let (p, media) = deckcraft_format::load_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
return Ok((p, Damage { media, slides: vec![] }));
return deckcraft_format::load(bytes).map_err(|e| EngineError::Other(e.to_string()));
}
open_other(name, bytes).map(|(p, slides)| (p, Damage { media: vec![], slides }))
}
fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec<String>)> {
if deckcraft_pptx::sniff(bytes) {
let (mut p, lost_slides) = deckcraft_pptx::import_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let mut p = deckcraft_pptx::import(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
deckcraft_format::repair(&mut p);
probe_clips(&mut p);
return Ok((p, lost_slides));
}
if deckcraft_pptx::is_encrypted(bytes) {
return Err(EngineError::Other(format!("{name} is password-protected. DeckCraft can't open password-protected presentations yet.")));
return Ok(p);
}
let lower = name.to_ascii_lowercase();
let rtf = deckcraft_format::rtf::sniff_rtf(bytes);
if rtf || lower.ends_with(".txt") || lower.ends_with(".md") {
if lower.ends_with(".txt") || lower.ends_with(".md") {
let text = String::from_utf8_lossy(bytes);
let text = if rtf { std::borrow::Cow::Owned(deckcraft_format::rtf::rtf_to_outline(&text)) } else { text };
let mut p = defaults::blank_presentation(defaults::WIDE, Default::default(), false);
if lower.ends_with(".md") {
deckcraft_format::markdown_to_slides(&mut p, &text);
} else {
deckcraft_format::outline_to_slides(&mut p, &text);
}
deckcraft_format::outline_to_slides(&mut p, &text);
if p.slides.is_empty() {
p = defaults::new_presentation(None);
}
return Ok((p, vec![]));
return Ok(p);
}
Err(EngineError::Other(format!("{name}: not a presentation DeckCraft can read")))
}
/// Fill in each audio and video clip's length and picture size from its bytes: a `.pptx` doesn't
/// store them. Headers only, so opening never decodes a whole audio file.
fn probe_clips(p: &mut Presentation) {
fn rec(shapes: &mut [Shape], media: &[MediaItem], probed: &mut HashMap<MediaId, Option<MediaInfo>>, depth: usize) {
if depth > 64 {
return;
}
for s in shapes {
if let ShapeKind::Media(m) = &mut s.kind
&& (m.duration_ms == 0 || m.width == 0 && m.height == 0)
&& let Some(info) = probed
.entry(m.media)
.or_insert_with(|| media.iter().find(|i| i.id == m.media).and_then(|i| deckcraft_media::probe_headers(&i.data).ok()))
{
if m.duration_ms == 0 {
m.duration_ms = info.duration_ms.min(u32::MAX as u64) as u32;
}
if m.width == 0
&& m.height == 0
&& let Some(v) = &info.video
{
(m.width, m.height) = (v.width, v.height);
}
}
if let Some(children) = s.children_mut() {
rec(children, media, probed, depth + 1);
}
}
}
let mut probed = HashMap::new();
// Just read, so no slide is shared yet and `make_mut` doesn't copy.
for slide in &mut p.slides {
rec(&mut Arc::make_mut(slide).shapes, &p.media, &mut probed, 0);
}
}
/// An outline file's text: RTF is read into the tab-indented outline, anything else as UTF-8.
pub fn outline_text(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
if deckcraft_format::rtf::sniff_rtf(bytes) { deckcraft_format::rtf::rtf_to_outline(&text) } else { text.into_owned() }
}
pub fn add_opened(s: &mut Session, name: &str, path: Option<String>, p: Presentation) -> usize {
let title = std::path::Path::new(name).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string());
crate::fonts::install_embedded_fonts(&p);
let missing_fonts = crate::fonts::missing_fonts(&p);
let mut st = DocState::new(p, path, title);
st.missing_fonts = missing_fonts;
s.add_document(st)
}
/// A presentation read from disk, not yet added to a session: [`read_presentation_file`] needs no
/// session, so a host can run it on a background thread, hand the result to
/// [`Session::stage_loaded`] and add it with `file.adopt`.
#[derive(Debug)]
pub struct LoadedFile {
pub path: String,
pub doc: Presentation,
/// A native or PPTX file (saving goes back to it); an outline import has no file to save to.
pub native: bool,
/// What the file had lost or damaged.
pub damaged: Damage,
}
/// Read and parse the presentation at `path`.
#[cfg(not(target_arch = "wasm32"))]
pub fn read_presentation_file(path: &str) -> Result<LoadedFile> {
let bytes = crate::io::read_file(path).map_err(EngineError::Other)?;
loaded_file(path, &bytes)
}
/// Parse `bytes` as the presentation file `path`, as [`read_presentation_file`] does after
/// reading it. The web host bridge uses it for a file its page sent, which then saves back to
/// that name like a file opened on the desktop.
pub fn loaded_file(path: &str, bytes: &[u8]) -> Result<LoadedFile> {
let (doc, damaged) = open_checked(path, bytes)?;
let native = deckcraft_format::sniff(bytes) || deckcraft_pptx::sniff(bytes);
Ok(LoadedFile { path: path.to_string(), doc, native, damaged })
}
/// Add a loaded presentation as the active document: the shared end of `file.open` and
/// `file.adopt`. A damaged file opens as an untitled repaired copy, so Save can't overwrite the
/// original with the empty media.
fn adopt_loaded(s: &mut Session, f: LoadedFile) -> Result<Value> {
let LoadedFile { path, doc, native, damaged } = f;
let keep_path = native && damaged.is_empty();
let i = add_opened(s, &path, keep_path.then(|| path.clone()), doc);
report_damage(s, &damaged)?;
let st = s.doc()?;
Ok(json!({
"document": i, "slides": st.doc.slides.len(), "missingFonts": st.missing_fonts,
"damagedMedia": damaged.media, "lostSlides": damaged.slides,
}))
}
#[cfg(not(target_arch = "wasm32"))]
fn open(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;
adopt_loaded(s, read_presentation_file(path)?)
}
/// `file.adopt {path, token?}`: add the presentation a host read in the background and staged
/// with [`Session::stage_loaded`]. Without that staged file (a replayed journal, a stale token)
/// it reads `path` like `file.open`, so the journal entry stays replayable.
fn adopt(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("file.adopt", "missing `path`"))?;
let staged = p.get("token").and_then(Value::as_u64).and_then(|t| s.take_loaded(t)).filter(|f| f.path == path);
match staged {
Some(f) => adopt_loaded(s, f),
#[cfg(not(target_arch = "wasm32"))]
None => adopt_loaded(s, read_presentation_file(path)?),
#[cfg(target_arch = "wasm32")]
None => Err(bad("file.adopt", format!("{path} was not loaded"))),
}
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let doc = open_presentation(path, &bytes)?;
let native = deckcraft_format::sniff(&bytes) || deckcraft_pptx::sniff(&bytes);
let i = add_opened(s, path, native.then(|| path.to_string()), doc);
let st = s.doc()?;
Ok(json!({"document": i, "slides": st.doc.slides.len(), "missingFonts": st.missing_fonts}))
}
#[cfg(target_arch = "wasm32")]
fn open(_s: &mut Session, _p: &Value) -> Result<Value> {
@@ -308,179 +103,61 @@ fn open(_s: &mut Session, _p: &Value) -> Result<Value> {
fn open_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").unwrap_or("Presentation");
let data = str_param(p, "data").and_then(base64_decode).ok_or_else(|| bad("file.openBytes", "missing or invalid base64 `data`"))?;
let (doc, damaged) = open_checked(name, &data)?;
let doc = open_presentation(name, &data)?;
let i = add_opened(s, name, None, doc);
report_damage(s, &damaged)?;
Ok(json!({"document": i, "missingFonts": s.doc()?.missing_fonts, "damagedMedia": damaged.media, "lostSlides": damaged.slides}))
Ok(json!({"document": i, "missingFonts": s.doc()?.missing_fonts}))
}
/// Tell the user which pictures, media and slides a damaged file lost, and mark the copy repaired.
fn report_damage(s: &mut Session, damaged: &Damage) -> Result<()> {
if damaged.is_empty() {
return Ok(());
}
let st = s.doc_mut()?;
st.title = format!("{} (Repaired)", st.title);
let mut text = String::new();
let n = damaged.media.len();
if n > 0 {
text = format!(
"{n} picture{} or media file{} in this presentation couldn't be read and {} empty. ",
if n == 1 { "" } else { "s" },
if n == 1 { "" } else { "s" },
if n == 1 { "is" } else { "are" },
);
}
let n = damaged.slides.len();
if n > 0 {
text.push_str(&format!(
"{n} slide{} in this file couldn't be read and {} left out. ",
if n == 1 { "" } else { "s" },
if n == 1 { "was" } else { "were" },
));
}
text.push_str("It was opened as a repaired copy; save it under a new name to keep the original file.");
s.ui_requests.push(crate::UiRequest::Message { text });
Ok(())
}
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `potx`, `ppsx`, `outline`, `pdf`, `gif`).
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `outline`).
pub fn save_bytes(doc: &Presentation, format: &str) -> Result<Vec<u8>> {
match format {
f @ ("pptx" | "potx" | "ppsx") => deckcraft_pptx::export_as(doc, f).map_err(|e| EngineError::Other(e.to_string())),
"pptx" | "potx" | "ppsx" => deckcraft_pptx::export(doc).map_err(|e| EngineError::Other(e.to_string())),
"outline" | "txt" => Ok(deckcraft_format::slides_to_outline(doc).into_bytes()),
"rtf" => Ok(deckcraft_format::rtf::slides_to_rtf(doc).into_bytes()),
"pdf" => deckcraft_pdf::export(doc, &Default::default()).map_err(|e| EngineError::Other(e.to_string())),
"gif" => gif_bytes(doc, &Value::Null),
"png" | "jpeg" | "jpg" => Err(EngineError::Other("saving a presentation as a single image isn't supported; use file.export".into())),
_ => deckcraft_format::save(doc).map_err(|e| EngineError::Other(e.to_string())),
}
}
/// Paper sizes for notes and handouts, for the UI's Print page.
pub use deckcraft_pdf::{PAPERS, paper_size};
/// PDF options from command params: `{layout: slides|notes|handouts, perPage, dpi, slides,
/// includeHidden, textLayer, frame, paper: letter|a4|legal|a3, orientation: portrait|landscape}` for a presentation of `count` slides. `slides` is a list of
/// 0-based indices or a range as typed in PowerPoint's Print page (`"1-3, 5"`, 1-based).
pub fn pdf_options(p: &Value, count: usize) -> Result<deckcraft_pdf::PdfOptions> {
/// PDF options from command params: `{layout: slides|notes|handouts, perPage, dpi, slides: [i],
/// includeHidden, textLayer, frame}`.
pub fn pdf_options(p: &Value) -> deckcraft_pdf::PdfOptions {
let mut o = deckcraft_pdf::PdfOptions { layout: deckcraft_pdf::PageLayout::Slides, ..Default::default() };
o.layout = match str_param(p, "layout").unwrap_or("slides") {
"notes" => deckcraft_pdf::PageLayout::Notes,
"handouts" => {
let per_page = opt_usize_param(p, "perPage", "file.export")?.unwrap_or(6);
if ![1, 2, 3, 4, 6, 9].contains(&per_page) {
return Err(bad("file.export", format!("perPage {per_page} isn't one of 1, 2, 3, 4, 6, 9")));
}
deckcraft_pdf::PageLayout::Handouts { per_page: per_page as u8 }
}
"handouts" => deckcraft_pdf::PageLayout::Handouts { per_page: usize_param(p, "perPage").unwrap_or(6).min(9) as u8 },
_ => deckcraft_pdf::PageLayout::Slides,
};
o.dpi = f64_or(p, "dpi", o.dpi).clamp(36.0, 600.0);
o.slides = match p.get("slides") {
Some(Value::Array(a)) => Some(a.iter().filter_map(|v| v.as_u64().map(|x| x as usize)).filter(|i| *i < count).collect()),
Some(Value::String(text)) if !text.trim().is_empty() => Some(parse_slide_range(text, count)?),
_ => None,
};
o.slides = p.get("slides").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_u64().map(|x| x as usize)).collect());
o.include_hidden = bool_or(p, "includeHidden", false);
o.text_layer = bool_or(p, "textLayer", true);
o.frame_slides = bool_or(p, "frame", true);
let landscape = match str_param(p, "orientation").unwrap_or("portrait") {
"portrait" => false,
"landscape" => true,
other => return Err(bad("file.export", format!("orientation “{other}” isn't portrait or landscape"))),
};
let paper = str_param(p, "paper").unwrap_or("letter");
o.paper = deckcraft_pdf::paper_size(paper, landscape).ok_or_else(|| {
let ids: Vec<&str> = deckcraft_pdf::PAPERS.iter().map(|p| p.0).collect();
bad("file.export", format!("paper “{paper}” isn't one of {}", ids.join(", ")))
})?;
Ok(o)
}
/// A slide range as typed in the Print page's Slides box (`"1-3, 5"`; 1-based, either separator
/// `,` or `;`, ranges either way round) → 0-based indices in order, without repeats. Numbers past
/// the last slide or a range that isn't numbers is an error, as in PowerPoint.
pub fn parse_slide_range(text: &str, count: usize) -> Result<Vec<usize>> {
let invalid = || bad("file.export", format!("“{text}” isn't a valid slide range: use numbers and ranges such as 1-3, 5"));
let mut out: Vec<usize> = vec![];
let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) {
let (a, b) = match part.split_once('-') {
Some((a, b)) => (a.trim(), b.trim()),
None => (part, part),
};
let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
if !digits(a) || !digits(b) {
return Err(invalid());
}
let (a, b) = (a.parse::<usize>().map_err(|_| invalid())?, b.parse::<usize>().map_err(|_| invalid())?);
let (lo, hi) = (a.min(b), a.max(b));
if lo == 0 || hi > count {
return Err(bad("file.export", format!("the presentation has {count} slides; “{part}” is outside them")));
}
for i in lo - 1..hi {
if seen.insert(i) {
out.push(i);
}
}
}
if out.is_empty() {
return Err(invalid());
}
Ok(out)
o
}
/// PDF bytes for `doc` with [`pdf_options`] from `p`.
pub fn pdf_bytes(doc: &Presentation, p: &Value) -> Result<Vec<u8>> {
deckcraft_pdf::export(doc, &pdf_options(p, doc.slides.len())?).map_err(|e| EngineError::Other(e.to_string()))
}
/// The output extensions [`format_for_path`] maps to a writer of that format.
pub const WRITABLE_EXTENSIONS: &[&str] = &["deckcraft", "pptx", "potx", "ppsx", "pdf", "png", "jpg", "jpeg", "gif", "txt", "md", "rtf"];
/// The format a file named `path` is written in, or `None` when its extension names no format
/// DeckCraft writes (`.odp`, `.svg`, no extension …): [`format_for_path`] would save
/// those as native `.deckcraft` bytes under the wrong name.
pub fn writable_format_for_path(path: &str) -> Option<&'static str> {
let ext = std::path::Path::new(path).extension()?.to_str()?.to_ascii_lowercase();
WRITABLE_EXTENSIONS.contains(&ext.as_str()).then(|| format_for_path(path))
}
/// Animated GIF bytes for `doc` with the options in `p` (see [`crate::gif_export::GifOptions::from_params`]).
pub fn gif_bytes(doc: &Presentation, p: &Value) -> Result<Vec<u8>> {
Ok(crate::gif_export::encode(doc, &crate::gif_export::GifOptions::from_params(p)?)?.bytes)
deckcraft_pdf::export(doc, &pdf_options(p)).map_err(|e| EngineError::Other(e.to_string()))
}
pub fn format_for_path(path: &str) -> &'static str {
let l = path.to_ascii_lowercase();
if l.ends_with(".pptx") {
if l.ends_with(".pptx") || l.ends_with(".potx") || l.ends_with(".ppsx") {
"pptx"
} else if l.ends_with(".potx") {
"potx"
} else if l.ends_with(".ppsx") {
"ppsx"
} else if l.ends_with(".png") {
"png"
} else if l.ends_with(".jpg") || l.ends_with(".jpeg") {
"jpeg"
} else if l.ends_with(".pdf") {
"pdf"
} else if l.ends_with(".gif") {
"gif"
} else if l.ends_with(".txt") || l.ends_with(".md") {
"outline"
} else if l.ends_with(".rtf") {
"rtf"
} else {
"deckcraft"
}
}
/// The active presentation is saved as it is now: no unsaved changes, and `path` (when given)
/// becomes its file. `file.save` calls it after writing; the web host bridge calls it once the
/// page has the bytes.
pub fn mark_saved(s: &mut Session, path: Option<String>) -> Result<()> {
fn mark_saved(s: &mut Session, path: Option<String>) -> Result<()> {
let st = s.doc_mut()?;
st.saved_doc = st.doc.clone();
if path.is_some() {
@@ -494,8 +171,16 @@ pub fn mark_saved(s: &mut Session, path: Option<String>) -> Result<()> {
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
crate::io::write_file(path, bytes).map_err(EngineError::Other)
// Write to a temporary sibling then rename, so a failed save never truncates the old file.
let tmp = format!("{path}.saving");
std::fs::write(&tmp, bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
std::fs::rename(&tmp, path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
#[cfg(target_arch = "wasm32")]
fn write_file(_path: &str, _bytes: &[u8]) -> Result<()> {
Err(EngineError::Other("saving to a path is not available in the browser".into()))
}
fn save(s: &mut Session, p: &Value) -> Result<Value> {
@@ -525,99 +210,46 @@ fn save_bytes_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"data": base64_encode(&bytes), "bytes": bytes.len()}))
}
/// `scale` for rendering `doc`'s slides to an image: within 0.01–16, and small enough that the
/// slide fits the renderer's largest picture ([`deckcraft_render::MAX_SIDE`]). Past that the
/// renderer clips, so a 4× export of a 4032 pt slide came out cropped to its first 16,000 pixels.
pub fn image_scale(doc: &Presentation, scale: f64) -> f64 {
let scale = if scale.is_finite() { scale.clamp(0.01, 16.0) } else { 1.0 };
let longest = doc.slide_size.width.max(doc.slide_size.height).max(1.0);
scale.min(f64::from(deckcraft_render::MAX_SIDE) / longest)
}
/// Render slide `index` (current when absent) to PNG bytes.
pub fn render_png(doc: &Presentation, index: usize, scale: f64, edit: bool) -> (Vec<u8>, u32, u32) {
render_png_with(doc, index, scale, edit, false)
}
/// [`render_png`]; `transparent` leaves the slide background out (#784).
pub fn render_png_with(doc: &Presentation, index: usize, scale: f64, edit: bool, transparent: bool) -> (Vec<u8>, u32, u32) {
let scale = image_scale(doc, scale);
let opts = deckcraft_render::RenderOpts { scale, edit, transparent_background: transparent, ..Default::default() };
let img = deckcraft_render::render_slide(doc, index, &opts);
(img.to_png_at(deckcraft_render::dpi_for_scale(scale)), img.width, img.height)
}
fn finite_scale(scale: f64) -> f64 {
if scale.is_finite() { scale.clamp(0.01, 16.0) } else { 1.0 }
}
fn picture_bytes(img: &deckcraft_render::Image, format: &str, scale: f64) -> Vec<u8> {
let dpi = deckcraft_render::dpi_for_scale(scale);
if format == "png" { img.to_png_at(dpi) } else { img.to_jpeg_at(92, Some(dpi)) }
let img =
deckcraft_render::render_slide(doc, index, &deckcraft_render::RenderOpts { scale: scale.clamp(0.01, 16.0), edit, ..Default::default() });
(img.to_png(), img.width, img.height)
}
fn render(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let i = opt_usize_param(p, "slide", "file.render")?.unwrap_or(st.selection.slide);
let i = usize_param(p, "slide").unwrap_or(st.selection.slide);
if i >= st.doc.slides.len() {
return Err(bad("file.render", format!("no slide {i}")));
}
let (png, w, h) = render_png_with(&st.doc, i, f64_or(p, "scale", 1.0), bool_or(p, "edit", false), bool_or(p, "transparentBackground", false));
let (png, w, h) = render_png(&st.doc, i, f64_or(p, "scale", 1.0), bool_or(p, "edit", false));
Ok(json!({"png": base64_encode(&png), "width": w, "height": h}))
}
/// The colour the slide is drawn with at one point: what the Eyedropper takes.
fn color_at(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let i = opt_usize_param(p, "slide", "slide.colorAt")?.unwrap_or(st.selection.slide);
if i >= st.doc.slides.len() {
return Err(bad("slide.colorAt", format!("no slide {i}")));
}
let coord = |key: &str| {
p.get(key)
.and_then(Value::as_f64)
.filter(|v| v.is_finite())
.ok_or_else(|| bad("slide.colorAt", format!("`{key}` (a number, in slide units) is required")))
};
let (x, y) = (coord("x")?, coord("y")?);
let scale = f64_or(p, "scale", 2.0).clamp(0.01, 16.0);
let img = deckcraft_render::render_slide(&st.doc, i, &deckcraft_render::RenderOpts { scale, ..Default::default() });
let (px, py) = (x * scale, y * scale);
let inside = px >= 0.0 && py >= 0.0 && px < f64::from(img.width) && py < f64::from(img.height);
let [r, g, b, a] =
img.straight_at(px as u32, py as u32).filter(|_| inside).ok_or_else(|| bad("slide.colorAt", "the point is outside the slide"))?;
Ok(json!({"color": format!("{r:02X}{g:02X}{b:02X}"), "alpha": a, "x": x, "y": y}))
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("file.export", "missing `path`"))?.to_string();
let format = str_param(p, "format").unwrap_or(format_for_path(&path)).to_string();
let st = s.doc()?;
let scale = finite_scale(f64_or(p, "scale", 2.0));
let transparent = bool_or(p, "transparentBackground", false);
if transparent && format != "png" {
return Err(bad("file.export", format!("a transparent background is for PNG export, not {format}")));
}
let scale = f64_or(p, "scale", 2.0);
match format.as_str() {
"png" | "jpeg" | "jpg" => {
let slides: Vec<usize> = match opt_usize_param(p, "slide", "file.export")? {
let slides: Vec<usize> = match usize_param(p, "slide") {
Some(i) => vec![i],
None if bool_or(p, "all", false) => (0..st.doc.slides.len()).collect(),
None => vec![st.selection.slide],
};
// Every slide checked before any file is written, so a bad index leaves nothing behind.
if let Some(i) = slides.iter().find(|i| **i >= st.doc.slides.len()) {
return Err(bad("file.export", format!("no slide {i}")));
}
let scale = image_scale(&st.doc, scale);
let mut written = vec![];
for (k, i) in slides.iter().enumerate() {
if *i >= st.doc.slides.len() {
return Err(bad("file.export", format!("no slide {i}")));
}
let img = deckcraft_render::render_slide(
&st.doc,
*i,
&deckcraft_render::RenderOpts { scale, transparent_background: transparent, ..Default::default() },
&deckcraft_render::RenderOpts { scale: scale.clamp(0.01, 16.0), ..Default::default() },
);
let bytes = picture_bytes(&img, &format, scale);
let bytes = if format == "png" { img.to_png() } else { img.to_jpeg(92) };
let out = if slides.len() == 1 {
path.clone()
} else {
@@ -626,65 +258,24 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
let ext = pth.extension().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| format.clone());
pth.with_file_name(format!("{stem}{}.{ext}", k + 1)).to_string_lossy().to_string()
};
// Say which slides made it when one can't be written (disk full part-way).
write_file(&out, &bytes)
.map_err(|e| if written.is_empty() { e } else { EngineError::Other(format!("{e} (slides 1–{k} were written)")) })?;
write_file(&out, &bytes)?;
written.push(out);
}
Ok(json!({"files": written}))
}
"pdf" => {
let bytes = pdf_bytes(&st.doc, p)?;
let bytes = deckcraft_pdf::export(&st.doc, &pdf_options(p)).map_err(|e| EngineError::Other(e.to_string()))?;
write_file(&path, &bytes)?;
Ok(json!({"path": path, "bytes": bytes.len()}))
}
"gif" => {
// `slides` may be a range, as for PDF ("1-3,5").
let mut gp = p.clone();
if let Some(text) = p.get("slides").and_then(Value::as_str) {
gp["slides"] = json!(parse_slide_range(text, st.doc.slides.len())?);
}
let out = crate::gif_export::encode(&st.doc, &crate::gif_export::GifOptions::from_params(&gp)?)?;
write_file(&path, &out.bytes)?;
Ok(json!({
"path": path,
"bytes": out.bytes.len(),
"frames": out.frames,
"width": out.width,
"height": out.height,
"secondsPerSlide": f64::from(out.delay_cs) / 100.0,
}))
}
"pptx" | "potx" | "ppsx" | "deckcraft" | "outline" | "txt" | "rtf" => {
let bytes = save_bytes(&st.doc, &format)?;
other => {
let bytes = save_bytes(&st.doc, other)?;
write_file(&path, &bytes)?;
Ok(json!({"path": path, "bytes": bytes.len()}))
}
other => Err(bad("file.export", format!("unknown format `{other}`"))),
}
}
/// File › Info: what the Info page shows about the active presentation.
fn info(s: &mut Session, _p: &Value) -> Result<Value> {
let st = s.doc()?;
let doc = &st.doc;
#[cfg(not(target_arch = "wasm32"))]
let bytes = st.path.as_deref().and_then(crate::io::file_len);
#[cfg(target_arch = "wasm32")]
let bytes: Option<u64> = None;
Ok(json!({
"title": st.title(),
"path": st.path,
"format": st.path.as_deref().map(format_for_path),
"dirty": st.is_dirty(),
"slides": doc.slides.len(),
"hiddenSlides": doc.slides.iter().filter(|sl| sl.hidden).count(),
"sections": doc.sections.len(),
"bytes": bytes,
"properties": serde_json::to_value(&doc.props).unwrap_or_default(),
}))
}
fn close(s: &mut Session, _p: &Value) -> Result<Value> {
if let Some(i) = s.active_index() {
s.close_document(i);
@@ -776,64 +367,3 @@ fn recovery_discard(s: &mut Session, p: &Value) -> Result<Value> {
}
ok()
}
#[cfg(test)]
#[path = "color_at_tests.rs"]
mod color_at_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::{parse_slide_range, write_file};
#[test]
fn broad_and_repeated_slide_ranges_expand_once() {
// 200 copies of a 100,000-slide range: each index once, in order, without a scan per index.
let text = vec!["1-100000"; 200].join(",");
let v = parse_slide_range(&text, 100_000).unwrap();
assert_eq!(v.len(), 100_000);
assert!(v.windows(2).all(|w| w[0] < w[1]));
assert_eq!(parse_slide_range("3, 1-3, 2", 3).unwrap(), vec![2, 0, 1]);
}
#[test]
fn slide_range_rejects_plus_sign() {
assert!(parse_slide_range("+2", 3).is_err());
assert!(parse_slide_range("+1-+3", 3).is_err());
assert_eq!(parse_slide_range("1-3", 3).unwrap(), vec![0, 1, 2]);
}
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("deckcraft-write-file-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn write_file_does_not_touch_a_predictable_saving_sibling() {
let dir = scratch("sibling");
let dest = dir.join("deck.deckcraft");
let dest_str = dest.to_str().unwrap();
std::fs::write(&dest, b"old").unwrap();
std::fs::write(dir.join("deck.deckcraft.saving"), b"precious").unwrap();
write_file(dest_str, b"new").unwrap();
assert_eq!(std::fs::read(&dest).unwrap(), b"new");
assert_eq!(std::fs::read(dir.join("deck.deckcraft.saving")).unwrap(), b"precious");
let names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(names.len(), 2, "no temporary file may be left behind: {names:?}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn write_file_failed_rename_keeps_destination_and_cleans_up() {
let dir = scratch("failed");
let dest = dir.join("target");
std::fs::create_dir(&dest).unwrap();
assert!(write_file(dest.to_str().unwrap(), b"new").is_err());
assert!(dest.is_dir());
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
}
-268
View File
@@ -1,268 +0,0 @@
//! Home › Editing: Find and Replace across slide text, table cells and speaker notes.
use std::sync::Arc;
use deckcraft_model::text::RunKind;
use deckcraft_model::{Paragraph, Shape, ShapeKind, Slide, TextBody};
use serde_json::{Value, json};
use super::{CommandSpec, bad, bool_or, cmd, has_doc, str_param};
use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "text.find",
"Find",
["Home", "Editing"],
None,
"{text, matchCase?: bool, wholeWords?: bool} → [{slide, shape (null = notes), cell?: [row, col], para, start, end}] (char offsets in the paragraph)",
has_doc,
find
),
cmd!(
"text.replace",
"Replace",
["Home", "Editing"],
None,
"{text, with, matchCase?, wholeWords?, at?: a text.find match (replace just that one; default: replace all)} → {replaced}",
has_doc,
replace
),
]
}
/// Where a text body lives on a slide.
#[derive(Clone, Copy, PartialEq, Debug)]
struct Loc {
shape: Option<u64>,
cell: Option<(usize, usize)>,
}
/// Visit every text body on a slide: shapes depth-first (groups, table cells), then the notes.
fn bodies(slide: &mut Slide, f: &mut dyn FnMut(Loc, &mut TextBody)) {
fn rec(shapes: &mut [Shape], depth: usize, f: &mut dyn FnMut(Loc, &mut TextBody)) {
if depth > 64 {
return;
}
for sh in shapes {
let id = Some(u64::from(sh.id.0));
if let Some(t) = &mut sh.text {
f(Loc { shape: id, cell: None }, t);
}
match &mut sh.kind {
ShapeKind::Table(t) => {
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
f(Loc { shape: id, cell: Some((r, c)) }, &mut cell.text);
}
}
}
ShapeKind::Group { children, .. } => rec(children, depth + 1, f),
_ => {}
}
}
}
rec(&mut slide.shapes, 0, f);
f(Loc { shape: None, cell: None }, &mut slide.notes);
}
struct Opts {
pat: Vec<char>,
case: bool,
whole: bool,
}
impl Opts {
fn from(p: &Value, cmd: &str) -> Result<Self> {
let pat: Vec<char> = str_param(p, "text").unwrap_or("").chars().collect();
if pat.is_empty() {
return Err(bad(cmd, "missing `text`"));
}
Ok(Opts { pat, case: bool_or(p, "matchCase", false), whole: bool_or(p, "wholeWords", false) })
}
fn eq(&self, a: char, b: char) -> bool {
a == b || (!self.case && a.to_lowercase().eq(b.to_lowercase()))
}
/// Non-overlapping matches as char ranges.
fn matches(&self, text: &[char]) -> Vec<(usize, usize)> {
let n = self.pat.len();
let word = |c: Option<&char>| c.is_some_and(|c| c.is_alphanumeric() || *c == '_');
let mut out = vec![];
let mut i = 0;
while i + n <= text.len() {
let hit = text[i..i + n].iter().zip(&self.pat).all(|(a, b)| self.eq(*a, *b))
&& (!self.whole || (!word(i.checked_sub(1).and_then(|j| text.get(j))) && !word(text.get(i + n))));
if hit {
out.push((i, i + n));
i += n;
} else {
i += 1;
}
}
out
}
}
fn para_chars(p: &Paragraph) -> Vec<char> {
p.runs.iter().flat_map(|r| r.content().chars()).collect()
}
/// Matches that lie wholly in plain text runs (never inside a field, equation or break).
fn para_matches(p: &Paragraph, o: &Opts) -> Vec<(usize, usize)> {
let mut spans = vec![];
let mut off = 0;
for r in &p.runs {
let n = r.char_len();
spans.push((off, off + n, matches!(r.kind, RunKind::Text)));
off += n;
}
o.matches(&para_chars(p)).into_iter().filter(|&(a, b)| spans.iter().all(|&(s, e, text)| text || e <= a || s >= b || s == e)).collect()
}
/// Replace chars `a..b` of the paragraph; the replacement takes the first run's formatting.
fn splice(p: &mut Paragraph, a: usize, b: usize, with: &str) {
let mut off = 0;
let mut placed = false;
for r in &mut p.runs {
let chars: Vec<char> = r.content().chars().collect();
let (s, e) = (off, off + chars.len());
off = e;
if e <= a || s >= b {
continue;
}
let keep_head: String = chars[..a.saturating_sub(s)].iter().collect();
let keep_tail: String = chars[b.saturating_sub(s).min(chars.len())..].iter().collect();
r.text = if placed { keep_tail } else { format!("{keep_head}{with}{keep_tail}") };
placed = true;
}
if p.runs.len() > 1 {
p.runs.retain(|r| !(r.text.is_empty() && matches!(r.kind, RunKind::Text)));
}
}
fn find(s: &mut Session, p: &Value) -> Result<Value> {
let o = Opts::from(p, "text.find")?;
let st = s.doc()?;
let mut out = vec![];
for (i, sl) in st.doc.slides.iter().enumerate() {
let mut sl = (**sl).clone();
bodies(&mut sl, &mut |loc, t| {
for (pi, para) in t.paragraphs.iter().enumerate() {
for (a, b) in para_matches(para, &o) {
out.push(json!({"slide": i, "shape": loc.shape, "cell": loc.cell.map(|(r, c)| [r, c]), "para": pi, "start": a, "end": b}));
}
}
});
}
Ok(Value::Array(out))
}
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
let o = Opts::from(p, "text.replace")?;
let with = str_param(p, "with").unwrap_or("").to_string();
let at = p.get("at").filter(|v| v.is_object()).map(|v| -> Result<(usize, Loc, usize, usize)> {
let n = |k: &str| v.get(k).and_then(Value::as_u64).map(|x| x as usize).ok_or_else(|| bad("text.replace", format!("`at` needs `{k}`")));
let cell = v.get("cell").and_then(Value::as_array).and_then(|c| Some((c.first()?.as_u64()? as usize, c.get(1)?.as_u64()? as usize)));
Ok((n("slide")?, Loc { shape: v.get("shape").and_then(Value::as_u64), cell }, n("para")?, n("start")?))
});
let at = at.transpose()?;
let count = s.edit(|doc, _| {
let mut count = 0;
for (i, slp) in doc.slides.iter_mut().enumerate() {
if at.is_some_and(|a| a.0 != i) {
continue;
}
let mut sl = (**slp).clone();
let mut changed = 0;
bodies(&mut sl, &mut |loc, t| {
if at.is_some_and(|a| a.1 != loc) {
return;
}
for (pi, para) in t.paragraphs.iter_mut().enumerate() {
if at.is_some_and(|a| a.2 != pi) {
continue;
}
for (a, b) in para_matches(para, &o).into_iter().rev() {
if at.is_some_and(|x| x.3 != a) {
continue;
}
splice(para, a, b, &with);
changed += 1;
}
}
});
if changed > 0 {
*slp = Arc::new(sl);
count += changed;
}
}
if count == 0 {
return Err(bad("text.replace", "no matches"));
}
Ok(count)
})?;
Ok(json!({"replaced": count}))
}
#[cfg(test)]
mod tests {
use super::*;
use deckcraft_model::{Run, RunProps};
fn opts(t: &str, case: bool, whole: bool) -> Opts {
Opts { pat: t.chars().collect(), case, whole }
}
#[test]
fn matching_honours_case_and_whole_words() {
let t: Vec<char> = "Cat cat category".chars().collect();
assert_eq!(opts("cat", false, false).matches(&t).len(), 3);
assert_eq!(opts("cat", true, false).matches(&t).len(), 2);
assert_eq!(opts("cat", false, true).matches(&t), vec![(0, 3), (4, 7)]);
}
fn text_run(t: &str) -> Run {
Run { text: t.into(), props: RunProps::default(), kind: RunKind::Text }
}
fn br() -> Run {
Run { text: String::new(), props: RunProps::default(), kind: RunKind::Break }
}
#[test]
fn a_match_never_spans_a_line_break() {
let p = Paragraph { runs: vec![text_run("a"), br(), text_run("b")], ..Default::default() };
assert!(para_matches(&p, &opts("ab", true, false)).is_empty());
}
#[test]
fn offsets_count_a_line_break_as_one_char() {
let p = Paragraph { runs: vec![text_run("ab"), br(), text_run("cd")], ..Default::default() };
assert_eq!(para_matches(&p, &opts("cd", true, false)), vec![(3, 5)]);
}
#[test]
fn splice_after_a_line_break_keeps_the_break() {
let mut p = Paragraph { runs: vec![text_run("ab"), br(), text_run("cd")], ..Default::default() };
splice(&mut p, 3, 5, "X");
assert_eq!(p.text(), "ab\u{b}X");
assert_eq!(p.runs[1].kind, RunKind::Break);
}
#[test]
fn splice_across_runs_keeps_the_first_runs_format() {
let bold = RunProps { bold: Some(true), ..Default::default() };
let mut p = Paragraph {
runs: vec![
Run { text: "Hel".into(), props: bold.clone(), kind: RunKind::Text },
Run { text: "lo world".into(), props: RunProps::default(), kind: RunKind::Text },
],
..Default::default()
};
splice(&mut p, 1, 5, "ola");
assert_eq!(para_chars(&p).iter().collect::<String>(), "Hola world");
assert_eq!(p.runs[0].text, "Hola");
assert_eq!(p.runs[0].props, bold);
}
}

Some files were not shown because too many files have changed in this diff Show More