Compare commits

..
177 changed files with 968 additions and 9072 deletions
-12
View File
@@ -1,12 +0,0 @@
# Custom runner labels actionlint can't know about.
self-hosted-runner:
labels:
- macos-release # org larger runner (M2 Pro), used by release.yml
# actionlint 1.7.12 predates GitHub's queue key, which the signer caller may use when it needs
# serialization. Only this exact false positive is suppressed; Packaging lint's independent
# source-contract job enforces the values.
paths:
.github/workflows/nightly-sign.yml:
ignore:
- '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$'
-16
View File
@@ -1,16 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
-112
View File
@@ -1,112 +0,0 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/deckcraft",
"repository_id": 1408294296,
"producer_workflow_id": 429734568,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "deckcraft-nightly-20261124-initial",
"repository": "storytold/deckcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 377160704,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "font-pin",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_deckcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_deckcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
-6
View File
@@ -11,13 +11,7 @@ workflows:
'.github/workflows/lockfile.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]'
'.github/workflows/nightly-macos.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]'
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/notify-services.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]'
-84
View File
@@ -1,84 +0,0 @@
# Builds the unsigned Apple-silicon DeckCraft Nightly (packaging/macos/nightly.sh) on a hosted
# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version
# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the
# real Nightly is signed and notarized by the shared release-ref signer (craft-common-actions),
# which calls packaging/macos/nightly-sign.sh.
name: Nightly macOS build
on:
# macOS runners are shared with release builds: pull requests run this only with the `full-ci`
# label, never by changed paths. `labeled` so adding the label starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/[email protected]
with:
egress-policy: audit
- uses: actions/[email protected]
with:
persist-credentials: false
# The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build.
- name: Check out craft-fonts
uses: actions/[email protected]
with:
repository: storytold/craft-fonts
ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
path: craft-fonts
- name: Check out craft-i18n
uses: actions/[email protected]
with:
repository: storytold/craft-i18n
path: craft-i18n
# The hosted image ships rustup: install the current stable plus the macOS target, with no new
# action pin for one job. Cargo enforces [workspace.package] rust-version.
- name: Install the Rust toolchain
run: rustup toolchain install stable --profile minimal --target aarch64-apple-darwin
# A version of the prepared Nightly form for this commit; the real one comes from the feed's
# identity job. Only nightly.sh's input checks read it.
- name: Prepare a Nightly identity for this commit
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "DECKCRAFT_BUILD_SHA=$sha"
echo "DECKCRAFT_BUILD_DATE=$date"
echo "DECKCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
env:
DECKCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle's version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/deckcraft-$DECKCRAFT_VERSION-macos-aarch64-nightly.zip"
-45
View File
@@ -1,45 +0,0 @@
name: DeckCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: deckcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/deckcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: deckcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
-34
View File
@@ -1,34 +0,0 @@
name: DeckCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/deckcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: deckcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
-20
View File
@@ -1,20 +0,0 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+2 -19
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
pull_request:
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
workflow_dispatch:
permissions:
@@ -49,20 +49,3 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/[email protected]
with:
egress-policy: audit
- uses: actions/[email protected]
with:
persist-credentials: false
- name: Enforce nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
-1
View File
@@ -59,4 +59,3 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
-6
View File
@@ -12,9 +12,3 @@ packaging/env.sh
/packaging/linux/flatpak/cargo-sources.json
/build-flatpak/
/.flatpak-builder/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
-2
View File
@@ -23,8 +23,6 @@ artwork. The ribbon and menu icons stay original drawings.
| `packaging/macos/dmg/background.svg` | @XusBadia | DeckCraft macOS DMG window background, original work for this repository (2026-10-08), derived from the DeckCraft app icon `assets/app-icon/deckcraft-1024.png` (referenced via `<image>`, not copied); text is outlined Inter / JetBrains Mono glyph paths | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | Finder window of the macOS DMG; `packaging/macos/dmg/generate.py` renders it to `background.tiff` |
| `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
| `assets/app-icon/deckcraft.icns`, `assets/app-icon/deckcraft.ico` | DeckCraft contributors | generated from the PNGs above by `packaging/icons.sh` (sips/iconutil, `cargo xtask ico`) | MIT OR Apache-2.0 | macOS and Windows app icons |
| `assets/app-icon/deckcraft-nightly*` (`deckcraft-nightly.png`, `deckcraft-nightly-1024.png`, `deckcraft-nightly.ico`, `deckcraft-nightly.icns`) | @skylartaylor | derivative of `assets/app-icon/deckcraft-1024.png` and `assets/app-icon/icon-source.deckcraft`, recoloured in code (background `#f26b1d` → `#a6420c`; foreground, padding and accent bars unchanged; native-size frames area-averaged from the 1024 master); recorded in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | DeckCraft Nightly app icon: window/desktop icon, macOS `CFBundleIconFile`, Windows resources and `.ico` |
| `assets/app-icon/nightly-provenance.json` | @skylartaylor | written alongside the nightly icons above; names their inputs, the recolour method and every output SHA-256 | MIT OR Apache-2.0 | Provenance of the DeckCraft Nightly icons |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.deckcraft.svg` | DeckCraft contributors | the shapes of `assets/app-icon/icon-source.deckcraft` written out as SVG (same coordinates, colours and corner radii) | MIT OR Apache-2.0 | Scalable app icon for Linux desktops (hicolor theme) |
| `assets/app-icon/icon-source.deckcraft` | DeckCraft contributors | made with `deckcraft-cli run` (see git history) | MIT OR Apache-2.0 | Source of the placeholder icon |
| `docs/images/editor.png`, `docs/images/shape-format.png`, `docs/images/format-pane.png`, `docs/images/slide-sorter.png`, `docs/images/dark-mode.png`, `docs/images/sample-deck.png` | DeckCraft contributors | Screenshots of DeckCraft and slides rendered by `deckcraft-cli` from the built-in sample deck (original content; Inter font, OFL-1.1) | MIT OR Apache-2.0 | README screenshots |
Generated
+103 -1402
View File
File diff suppressed because it is too large Load Diff
+31 -37
View File
@@ -12,17 +12,17 @@ repository = "https://github.com/storytold/deckcraft"
[workspace.dependencies]
# OPC part-name primitives and package reader/writer.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
# Compound File Binary directory reads (password-protected deck detection).
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
# Bounded XML reader and writer primitives.
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
# DrawingML colours, themes, charts, tables and text (craft-libs#778, #792).
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
# PresentationML PPTX/POTX/PPSX reader and writer (craft-libs#778).
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" }
# Shared MCP stdio framing and protocol constants (craft-libs#778).
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "bc186ca719958fcce3b6ee24794277eabed14609", version = "0.1.0" }
# internal
deckcraft-geom = { path = "crates/geom" }
deckcraft-color = { path = "crates/color" }
@@ -62,27 +62,21 @@ 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"] }
# Base64 for command payloads (engine); base64_compat keeps the legacy lenient decoder. Same rev as craft-deckcraft-format.
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "254e9a409b410dc93c0e06ff66cd1e767893ac32", version = "=0.1.0" }
# craft-media, craft-audio and craft-video share types and stay on one rev.
# The .deckcraft package layer (identity, manifest, member names, bounded reads); crates/format maps the presentation onto it.
craft-deckcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false }
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false, features = ["opus-decode"] }
craft-deckcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "254e9a409b410dc93c0e06ff66cd1e767893ac32", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d0193d7e94b5ec180ecc2a152ea72047d39ac632", version = "=0.1.0" }
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0", default-features = false }
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0", default-features = false, features = ["opus-decode"] }
# H.264, HEVC, VP9 and AV1 decoders.
craft-video = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false, features = ["h264-decode", "hevc-decode", "vp9-decode", "av1-decode", "threads"] }
craft-video = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0", default-features = false, features = ["h264-decode", "hevc-decode", "vp9-decode", "av1-decode", "threads"] }
# WMF, EMF and EMF+ reader.
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
# The framework runtime's host: the app's identity, its window services, its key overrides and the theme mode
# the framework's components draw in.
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "63196e66f3033a6623eb629af95a104d26986725", features = ["egui"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" }
i_overlay = "9"
quick-xml = "0.41"
zip = { version = "3", default-features = false, features = ["deflate"] }
@@ -129,19 +123,19 @@ codegen-units = 16
debug = 0
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.8.2" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", 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" }
-26
View File
@@ -173,32 +173,6 @@ See [ROADMAP.md](ROADMAP.md) for the stage, numbers by dimension and what's next
[docs/gaps.md](docs/gaps.md) for every known shortfall and
[docs/parity-checklist.md](docs/parity-checklist.md) for the feature-by-feature checklist.
## Nightly builds (not released yet)
DeckCraft has a separate **DeckCraft Nightly** channel for Launcher-managed nightly builds beside
the stable app: its own application ID, package identity, data folder, taskbar entry and window
class, so it never reads or writes stable DeckCraft's settings, recovery autosaves, logs, user
dictionary or single window state. The Nightly app is started only by ArtCraft Launcher
(`--launch-profile nightly-v1 --profile-root <dir> -- <files>`); the profile root is validated and
fenced against every stable data and install folder, so a Nightly window cannot fall back to
stable state. Nightly is managed by the Launcher and does not self-update.
On Linux, the plain nightly `.tar.gz` starts through the canonical shared launcher template
(`packaging/linux/nightly-launch.sh`, rendered from `craft-common-actions`'s
`scripts/nightly-launcher.sh.in`): `deckcraft` starts `deckcraft-bin` beside it on the nightly-v1
profile under the Nightly package identity. The distro formats keep their own launcher
(`packaging/linux/nightly-package-launch.sh`) and their own profile folder; the AppImage, the deb/rpm
package, the Flatpak and the Arch handoff all pass `--launch-profile nightly-v1 --profile-root <dir>
-- <files>` to the GUI, so an unpacked or distro-installed copy is isolated without the Launcher.
The channel's packaging lives in `packaging/nightly-common.sh`, `packaging/{linux,macos,windows}/nightly*`
and `.github/workflows/nightly*.yml`. The producer and signer workflows are registered and can be
dispatched by the reviewed release managers only; there is no schedule or automatic dispatch yet.
Read [`docs/nightly-release-preparation.md`](docs/nightly-release-preparation.md) before the first
supervised run. The channel is compiled with `DECKCRAFT_BUILD_CHANNEL=nightly-v1`, which also
selects the deeper-background icons recorded in
[`assets/app-icon/nightly-provenance.json`](assets/app-icon/nightly-provenance.json).
## Downloads
**Download DeckCraft** from GitHub: the [latest release](https://github.com/storytold/deckcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/deckcraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
-6
View File
@@ -2,9 +2,7 @@
**Stage: alpha** · next: beta, ~20 points and ~120–210 h away
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-20 · **Change:** trivial (progress log: WMF scale and offset mapping records place sub-pictures, #2069; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-16 · **Change:** trivial (progress log: every slide as PNG or JPEG from File › Export › Change File Type and Save As, #2019; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-15 · **Change:** trivial (DeckCraft v0.19.0 version preparation (#2134); the SmartArt and WordArt display names become Diagram and Decorative Text (#1981) in DeckCraft's own feature labels — commands, contextual tab labels and messages — with the neutral labels guarded by tests (the PowerPoint-matching empty-diagram placeholder prompt still reads "Click icon to add SmartArt graphic", and saved control-channel identifiers such as the tab id "SmartArt Design" keep their keys); the wasm32 build no longer refers to the native-only opening generation (#1954); the control-protocol method reference is corrected (#2132); parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-14 · **Change:** minor (a slide the show advances to again plays its animations again, #2090; slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; empty notes slides are kept through PPTX and native saves, #2025; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-09 · **Change:** minor (progress log: PowerPoint 97–2003 `.ppt`/`.pot`/`.pps` import, #239) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-07 · **Change:** trivial (progress log: text in a group whose child coordinates scale its shapes is placed for export where the slide draws it; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
@@ -160,9 +158,7 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | What landed |
|---|---|
| 2026-11-20 | WMF pictures that draw sub-pictures through the scale and offset mapping records (charts and clip art from older Office versions) place each one in its part of the frame (#2069) |
| 2026-11-16 | Export: every slide as its own PNG or JPEG picture from File › Export › Change File Type and File › Save As; the Export… dialog adds JPEG images (all slides) (#2019) |
| 2026-11-15 | DeckCraft v0.19.0 version preparation (#2134); the SmartArt and WordArt display names become Diagram and Decorative Text in DeckCraft's own feature labels — commands, contextual tab labels and messages — with the neutral labels guarded by tests; the wasm32 build no longer refers to the native-only opening generation (#1954); the control-protocol method reference is corrected (#2132) |
| 2026-11-14 | Slide show: a slide the show advances to again (click, →, Space, automatic advance or a loop) starts over, so its animations play again, as in PowerPoint. Back and links still show it as it was left (#2090) |
| 2026-11-11 | PPTX: a slide whose notes slide has empty text retains its notesSlide part and relationship on save and reopen (#2025); empty notes slides survive native round trips |
| 2026-11-11 | Media: the Opus decoder and the Ogg, MP4/MOV and Matroska demuxers are craft-audio and craft-media from craft-libs; DeckCraft's own copies and re-export crates are removed |
@@ -355,9 +351,7 @@ app's JSON control channel (`deckcraft --control PORT`).
| Date | Change | Summary |
|---|---|---|
| 2026-11-20 | trivial | Progress log: WMF scale and offset mapping records (#2069); scores unchanged |
| 2026-11-16 | trivial | Progress log: export all slides as PNG or JPEG from the File tab (#2019); scores unchanged |
| 2026-11-15 | trivial | v0.19.0 version preparation; Diagram and Decorative Text naming (#1981) scoped to DeckCraft's own labels — the PowerPoint-matching empty-placeholder prompt still reads "Click icon to add SmartArt graphic" and saved control-channel identifiers keep their keys; wasm32 fix (#1954); control-protocol reference fix (#2132); parity scores unchanged |
| 2026-11-14 | trivial | Progress log: a slide the show advances to again plays its animations again (#2090); parity scores unchanged |
| 2026-11-11 | minor | Progress log: empty notes slides preserved on PPTX/native save (#2025); parity scores unchanged |
| 2026-11-11 | trivial | Opus and container code moved to craft-libs crates; parity scores unchanged |
-10
View File
@@ -41,16 +41,6 @@ fn stdout_line(args: std::fmt::Arguments<'_>) -> std::io::Result<()> {
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
// nightly-v1 is a desktop-only launcher protocol. Never let GUI profile arguments fall through
// to stable CLI/MCP directory discovery.
if args
.iter()
.take_while(|arg| arg.as_str() != "--")
.any(|arg| arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root="))
{
eprintln!("nightly-v1 is supported only by the DeckCraft desktop launcher protocol");
return ExitCode::from(2);
}
let rest = args.get(1..).unwrap_or(&[]);
let asks_help = rest.iter().any(|a| a == "--help" || a == "-h");
if let Some(page) = args.first().filter(|_| asks_help).and_then(|n| help::page(n)) {
-19
View File
@@ -287,22 +287,3 @@ fn commands_lists_one_line_per_command() {
assert_eq!(stdout(&cli(&["commands", "slide.next"])), "slide.next — Next Slide\n");
assert_eq!(stdout(&cli(&["commands", "shape.presets"])), "shape.presets — Shape Gallery → [{name, label, category}]\n");
}
/// The desktop-only Nightly launcher protocol never falls through to the CLI's stable directory
/// discovery: every spelling leaves with exit 2 and says so.
#[test]
fn the_desktop_launcher_protocol_is_refused() {
for args in [
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly-data/profiles/deckcraft", "--", "deck.pptx"][..],
&["--launch-profile", "nightly-v1", "info"][..],
&["--profile-root=/nightly-data/profiles/deckcraft", "info"][..],
] {
let o = cli(args);
assert_eq!(o.status.code(), Some(2), "{args:?}");
let err = String::from_utf8_lossy(&o.stderr);
assert!(err.contains("desktop launcher protocol"), "{args:?}: {err}");
}
// Everything after the delimiter is a file name, so the flags there are not the protocol.
let o = cli(&["--", "--launch-profile"]);
assert_eq!(o.status.code(), Some(1), "`--` is an unknown subcommand, not a profile");
}
+2 -2
View File
@@ -17,9 +17,9 @@ path = "src/main.rs"
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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
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 }
-5
View File
@@ -49,13 +49,10 @@ pub fn start() {
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);
// The presenter popup draws DeckCraft's presenter view only, with no framework component, so
// it runs without the framework runtime.
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>);
}
deckcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let inbox: Inbox = Inbox::default();
let mut services = services(inbox.clone(), cc.egui_ctx.clone());
if let Some(bridge) = &app_bridge {
@@ -134,7 +131,6 @@ impl eframe::App for WebShell {
bridge.open_files(&mut self.app);
}
self.app.logic(ctx);
self.app.close_path(ctx);
if let Some(bridge) = &self.bridge {
bridge.report_dirty(&self.app);
}
@@ -170,7 +166,6 @@ impl eframe::App for WebShell {
});
}
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
-5
View File
@@ -21,7 +21,6 @@ egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
chrono = { workspace = true }
thiserror = { workspace = true }
[build-dependencies]
# Icon + VERSIONINFO for deckcraft.exe; build.rs only uses it when the target is Windows.
@@ -34,10 +33,6 @@ arboard = { workspace = true, features = ["image-data"] }
image = { workspace = true }
cpal = "0.16"
[target.'cfg(windows)'.dependencies]
# An explicit AppUserModelID for DeckCraft Nightly, so its taskbar group and toasts are not stable's.
winsafe = { version = "0.0.29", features = ["user", "shell"] }
[target.'cfg(target_os = "macos")'.dependencies]
# Finder double-click, Open With, Dock drops and `open -a DeckCraft deck.pptx` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This audited crate (also used by
+3 -43
View File
@@ -4,62 +4,22 @@
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `DECKCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
//!
//! `DECKCRAFT_BUILD_CHANNEL=nightly-v1` selects the Nightly flavor: `cfg(deckcraft_nightly_v1)`,
//! the deeper nightly icon, `ProductName "DeckCraft Nightly"` and the exact prepared
//! `DECKCRAFT_VERSION` as ProductVersion (the Launcher checks ProductVersion, not FileVersion).
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=DECKCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(deckcraft_nightly_v1)");
let nightly = match std::env::var("DECKCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=deckcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported DECKCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/deckcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/deckcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=DECKCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=DECKCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("DECKCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit DECKCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=DECKCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "DeckCraft Nightly" } else { "DeckCraft" })
.set("FileDescription", if nightly { "DeckCraft Nightly presentations" } else { "DeckCraft presentations" })
res.set_icon("../../assets/app-icon/deckcraft.ico")
.set("ProductName", "DeckCraft")
.set("FileDescription", "DeckCraft presentations")
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the DeckCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "deckcraft.exe")
.set("InternalName", "deckcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("DECKCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
-189
View File
@@ -1,189 +0,0 @@
//! Where the desktop app keeps its per-user data: `ui.json`, `prefs.json`, `logs/`, the crash
//! recovery folder and the user dictionary all live under the directory [`config_dir`] returns.
//!
//! In order:
//! 1. A selected Nightly profile root ([`crate::launch_profile`]): everything lives under it, and
//! nothing is read from or written to a stable folder.
//! 2. The platform convention: macOS `~/Library/Application Support/DeckCraft`, Windows
//! `%APPDATA%\DeckCraft`, Linux `$XDG_CONFIG_HOME/deckcraft` or `~/.config/deckcraft`.
//!
//! DeckCraft has no portable mode and no `DECKCRAFT_CONFIG_DIR` override, so the stable resolution
//! is exactly the one `main.rs` used before the Nightly channel; the fence module
//! ([`crate::profile_root`]) still refuses a `DeckCraftData` folder or a `portable.txt` beside a
//! DeckCraft executable, which a hand-made portable copy could carry.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
/// The portable data folder name a hand-made portable copy could use. No DeckCraft package
/// writes it, but the fence refuses a profile inside one (see [`crate::profile_root`]).
pub const PORTABLE_DATA_DIR: &str = "DeckCraftData";
/// The marker file of a portable copy, beside its executable.
pub const PORTABLE_MARKERS: [&str; 1] = ["portable.txt"];
/// The portable marker in `dir`, when it is a regular file.
pub fn portable_marker(dir: &Path) -> Option<PathBuf> {
PORTABLE_MARKERS.iter().map(|name| dir.join(name)).find(|path| path.is_file())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// The profile root chosen by the Launcher (`--launch-profile nightly-v1`).
Override,
/// The platform convention (stable).
Platform,
}
#[derive(Clone, Debug)]
pub struct DataDir {
pub dir: Option<PathBuf>,
pub mode: Mode,
}
/// The data directory for this process, resolved once.
pub fn current() -> &'static DataDir {
static DIR: OnceLock<DataDir> = OnceLock::new();
DIR.get_or_init(|| match crate::launch_profile::current().root() {
Some(root) => DataDir { dir: Some(root.to_path_buf()), mode: Mode::Override },
None => DataDir { dir: platform_dir(|key| std::env::var_os(key)), mode: Mode::Platform },
})
}
/// The per-user settings directory (see the module docs).
pub fn config_dir() -> Option<PathBuf> {
current().dir.clone()
}
/// The platform's settings directory. Read from the environment every call, so tests can vary it.
pub fn platform_dir(env: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/DeckCraft"))
} else if cfg!(windows) {
env("APPDATA").map(|a| PathBuf::from(a).join("DeckCraft"))
} else {
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("deckcraft"))
}
}
/// The crash-recovery folder: inside the profile for Nightly, the platform's own folder for stable
/// (`deckcraft_engine::recovery::default_dir`, which keeps autosaves out of the synced config).
fn recovery_dir_for(current: &DataDir) -> Option<PathBuf> {
match current {
DataDir { dir: Some(root), mode: Mode::Override } => Some(root.join("Recovery")),
_ => deckcraft_engine::recovery::default_dir(),
}
}
/// [`recovery_dir_for`] for this process.
pub fn recovery_dir() -> Option<PathBuf> {
recovery_dir_for(current())
}
/// The user dictionary (`user.dic`, the words "Add to dictionary" keeps): inside the profile for
/// Nightly, the platform's dictionary folder for stable.
fn user_dictionary_for(current: &DataDir) -> Option<PathBuf> {
match current {
DataDir { dir: Some(root), mode: Mode::Override } => Some(root.join("Dictionaries").join("user.dic")),
_ => None,
}
}
/// [`user_dictionary_for`] for this process.
pub fn user_dictionary() -> Option<PathBuf> {
user_dictionary_for(current())
}
/// The app's exclusive write probe: a new file created in `dir` and removed again. It never falls
/// back to another directory, so the Nightly validator can refuse a root it cannot write.
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
// A probe left behind by an interrupted launch must not make a writable profile look
// unwritable, so each attempt uses a fresh name and a collision tries the next one.
// `create_new` still guarantees a create rather than a truncation.
for attempt in 0..8u32 {
let probe = dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id()));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(file) => {
drop(file);
return std::fs::remove_file(probe);
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name in the profile"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn env(pairs: &[(&str, &str)]) -> BTreeMap<String, OsString> {
pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
}
#[test]
fn platform_dirs_follow_the_platform_convention() {
let home = if cfg!(windows) { r"C:\Users\me" } else { "/home/me" };
let env = env(&[("HOME", home), ("APPDATA", r"C:\Users\me\AppData\Roaming"), ("XDG_CONFIG_HOME", "/xdg/config")]);
let dir = platform_dir(|k| env.get(k).cloned()).expect("a platform directory");
if cfg!(target_os = "macos") {
assert_eq!(dir, PathBuf::from(home).join("Library/Application Support/DeckCraft"));
} else if cfg!(windows) {
assert_eq!(dir, PathBuf::from(r"C:\Users\me\AppData\Roaming").join("DeckCraft"));
} else {
assert_eq!(dir, PathBuf::from("/xdg/config").join("deckcraft"));
}
}
/// Recovery and the dictionary follow the profile; stable keeps the engine's own folders and
/// writes no per-profile dictionary.
#[test]
fn the_nightly_profile_owns_recovery_and_the_dictionary() {
let root = PathBuf::from("/nightly-data/profiles/deckcraft");
let profile = DataDir { dir: Some(root.clone()), mode: Mode::Override };
assert_eq!(recovery_dir_for(&profile), Some(root.join("Recovery")));
assert_eq!(user_dictionary_for(&profile), Some(root.join("Dictionaries").join("user.dic")));
let stable = DataDir { dir: None, mode: Mode::Platform };
assert_eq!(user_dictionary_for(&stable), None);
assert_eq!(recovery_dir_for(&stable), deckcraft_engine::recovery::default_dir());
}
/// The process resolves its data directory once; every caller must get that same decision.
#[test]
fn the_data_directory_is_resolved_once() {
let resolved = current();
assert!(std::ptr::eq(resolved, current()));
assert_eq!(resolved.dir, config_dir());
}
#[test]
fn permanent_probe_does_not_replace_an_existing_entry() {
let dir = std::env::temp_dir().join(format!("deckcraft-writable-{}-{}", std::process::id(), line!()));
std::fs::create_dir_all(&dir).unwrap();
let probe = |attempt: u32| dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id()));
// An entry already at the probe's name must never be truncated: the probe takes the next
// free name, and it removes only the file it created.
std::fs::write(probe(0), b"someone else's file").unwrap();
ensure_writable(&dir).unwrap();
assert_eq!(std::fs::read(probe(0)).unwrap(), b"someone else's file");
assert!(!probe(1).exists());
// Every name taken is an error, not a truncation of any of them.
for attempt in 0..8 {
std::fs::write(probe(attempt), b"someone else's file").unwrap();
}
assert!(ensure_writable(&dir).is_err(), "no free probe name is reported, not truncated");
for attempt in 0..8 {
assert_eq!(std::fs::read(probe(attempt)).unwrap(), b"someone else's file", "{attempt}");
}
for attempt in 0..8 {
std::fs::remove_file(probe(attempt)).unwrap();
}
// A folder whose stale probes were cleared is writable, and the probe leaves nothing behind.
ensure_writable(&dir).unwrap();
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
std::fs::remove_dir_all(&dir).unwrap();
}
}
-54
View File
@@ -1,54 +0,0 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/deckcraft-nightly.ico" } else { "../../assets/app-icon/deckcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/deckcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/deckcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.19.0-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.19.0",
"0.19.0-nightly",
"0.19.0-nightly.20261124",
"0.19.0-nightly.20261124.17.1.gABCDEF012345",
"0.19.0-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.19.0-nightly.20261124.1.1.gabcdef012345",
"0.19.0-nightly.20261124.1.1.gabcdef012345/other",
"0.19.0-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
-72
View File
@@ -1,72 +0,0 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(deckcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open DeckCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable DeckCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.19.0"), "0.19.0");
assert_eq!(version(BuildFlavor::NightlyV1, "0.19.0"), "0.19.0 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
-221
View File
@@ -1,221 +0,0 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::app_dirs::ensure_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
/// The process installs one profile; later answers are read-only and a second install fails.
#[test]
fn the_process_installs_its_profile_once() {
assert_eq!(current(), &Profile::Stable, "an unselected process is a stable launch");
assert!(install(Profile::Stable).is_ok());
assert_eq!(current(), &Profile::Stable);
assert!(install(Profile::Stable).is_err());
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--sample", "a.pptx"]), args(&["--", "--launch-profile", "file.pptx"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "talk with spaces.pptx"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "talk with spaces.pptx"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "4242", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "1", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+43 -235
View File
@@ -14,25 +14,17 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod app_dirs;
#[cfg(target_os = "macos")]
mod apple_events;
mod audio;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
#[cfg(all(unix, not(target_os = "macos")))]
mod display;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod launch_profile;
mod logging;
mod nightly_session;
#[cfg(not(target_arch = "wasm32"))]
mod pasteboard;
mod process_identity;
mod profile_root;
use deckcraft_engine::Session;
use deckcraft_ui_egui::{Services, SlideApp};
@@ -49,23 +41,15 @@ impl eframe::App for App {
#[cfg(target_os = "macos")]
apple_events::poll(&self.1, &mut self.0, ctx);
self.0.logic(ctx);
self.0.close_path(ctx);
}
/// Forward native raw input to the wrapped application once per frame, then hand the framework
/// runtime this frame's root values.
/// 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);
self.0.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
deckcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.ui(ui);
}
fn on_exit(&mut self) {
// The one exit path macOS has: run the hook exactly once (the Nightly session record).
if let Some(hook) = self.0.services.at_exit.take() {
hook();
}
save_prefs(&self.0);
// The window is closing for good: a ready update's helper starts now and installs it once
// the process has exited.
@@ -85,11 +69,25 @@ impl eframe::App for App {
}
}
/// The per-user settings directory: `ui.json`, `prefs.json` and `logs/` live here.
fn config_dir() -> Option<std::path::PathBuf> {
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/DeckCraft"))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("DeckCraft"))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join("deckcraft"))
}
}
fn load_prefs(app: &mut SlideApp) {
if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() {
return;
}
let Some(dir) = app_dirs::config_dir() else { return };
let Some(dir) = config_dir() else { return };
let (ui, prefs) = deckcraft_ui_egui::settings::load(&dir);
if let Some(ui) = ui {
app.ui = ui;
@@ -103,7 +101,7 @@ fn save_prefs(app: &SlideApp) {
if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() {
return;
}
if let Some(dir) = app_dirs::config_dir() {
if let Some(dir) = config_dir() {
deckcraft_ui_egui::settings::save(&dir, &app.ui, &app.session.prefs);
}
}
@@ -157,6 +155,8 @@ fn display_count(window: &winit::window::Window) -> Option<usize> {
(n > 0).then_some(n)
}
const APP_ID: &str = "ai.storyteller.deckcraft";
const USAGE: &str = "\
Usage: deckcraft [--control PORT] [--sample] [--show] [FILE...]
@@ -183,11 +183,6 @@ fn startup(mut control_port: Option<u16>, args: impl IntoIterator<Item = String>
let mut args = args.into_iter();
while let Some(a) = args.next() {
match a.as_str() {
// The Nightly Launcher form: everything after the delimiter is a file.
"--" => {
files.extend(args.by_ref());
break;
}
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--sample" => sample = true,
"--show" => show = true,
@@ -202,142 +197,40 @@ fn startup(mut control_port: Option<u16>, args: impl IntoIterator<Item = String>
}
fn app_icon() -> Option<egui::IconData> {
// The window icon follows the compiled channel, so a Nightly window is not the stable icon.
#[cfg(deckcraft_nightly_v1)]
let png: &[u8] = include_bytes!("../../../assets/app-icon/deckcraft-nightly.png");
#[cfg(not(deckcraft_nightly_v1))]
let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png");
eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok()
}
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before logger/crash/update/font/prefs access.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version()));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() {
deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
} else {
deckcraft_ui_egui::os_window::LaunchIdentity::Stable
};
if let Err(error) = launch_profile::install(early.profile).and_then(|()| deckcraft_ui_egui::os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
deckcraft_ui_egui::os_window::id_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
fn report_launch_profile_error(error: &str) {
eprintln!("DeckCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("DeckCraft launch profile: {error}");
return;
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
let _ = rfd::MessageDialog::new()
.set_title("DeckCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Install logging, parse startup arguments and environment, launch the native app, and
/// propagate an eframe startup failure.
fn main() -> eframe::Result {
let Some(arguments) = prepare_launch() else { return Ok(()) };
let nightly = launch_profile::current().is_nightly();
// Nightly session health: the record names this window's owner and survives an abnormal end.
let (watch, session_unavailable) = nightly_session::Session::begin_with_health(
launch_profile::current().root(),
deckcraft_ui_egui::flavor::version(),
option_env!("DECKCRAFT_BUILD_SHA"),
)
.unwrap_or_else(|error| {
eprintln!("DeckCraft Nightly session state: {error}");
(None, false)
});
let previous_unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean);
let session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(watch));
let notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let exit_session = session.clone();
let exit_notice = notice_shown.clone();
// First, so every start-up record (and the engine's panic hook, installed with the first
// Session) is captured; see `logging`.
let logger = logging::install();
// Nightly is managed by ArtCraft Launcher: no stable self-update helper runs in it.
if !nightly
&& let Some(done) = craft_update::self_update::finish(&deckcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
if let 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(
if nightly { None } else { std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()) },
arguments.into_iter().map(|a| a.to_string_lossy().into_owned()),
) {
Startup::Help => {
print!("{USAGE}");
return Ok(());
}
Startup::Version => {
println!("deckcraft {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show),
};
log::info!("DeckCraft {} ({} {})", deckcraft_ui_egui::flavor::version(), std::env::consts::OS, std::env::consts::ARCH);
let (control_port, files, sample, show) =
match startup(std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()), std::env::args().skip(1)) {
Startup::Help => {
print!("{USAGE}");
return Ok(());
}
Startup::Version => {
println!("deckcraft {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show),
};
log::info!("DeckCraft {} ({} {})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH);
// The log file lives under the settings directory; opened after the arguments, so `--help` and
// `--version` leave no file behind. Records logged until now are written to it first.
if let Some(logger) = logger {
match app_dirs::config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
match config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
Some(Ok(path)) => log::info!("log file {}", path.display()),
Some(Err(e)) => log::warn!("no log file: {e}"),
None => {
@@ -348,7 +241,7 @@ fn main() -> eframe::Result {
}
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()))
.with_title("DeckCraft")
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([900.0, 560.0])
.with_drag_and_drop(true)
@@ -357,7 +250,7 @@ fn main() -> eframe::Result {
.with_title_shown(false),
..Default::default()
};
options.viewport = options.viewport.with_app_id(deckcraft_ui_egui::os_window::app_id());
options.viewport = options.viewport.with_app_id(APP_ID);
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
}
@@ -373,8 +266,6 @@ fn main() -> eframe::Result {
}
};
// `Default` lets winit choose, and winit takes Wayland whenever `WAYLAND_DISPLAY` is set.
#[cfg(not(all(unix, not(target_os = "macos"))))]
let x11 = false;
#[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"))))]
@@ -395,47 +286,28 @@ fn main() -> eframe::Result {
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
let creator_notice = notice_shown.clone();
let mut services = services(native_wayland);
// The Nightly session record is finished exactly once, on the clean exit path macOS has.
services.at_exit = Some(Box::new(move || {
nightly_session::finish_once(&exit_session, exit_notice.load(std::sync::atomic::Ordering::Relaxed));
}));
let result = eframe::run_native(
deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()),
eframe::run_native(
"DeckCraft",
options,
Box::new(move |cc| {
deckcraft_ui_egui::framework::install(&cc.egui_ctx, x11)?;
deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx);
let mut app = SlideApp::new(Session::new(), services);
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)));
}
load_prefs(&mut app);
if !nightly {
// Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed.
app.enable_update_checks();
}
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 = app_dirs::recovery_dir();
app.session.recovery_dir = deckcraft_engine::recovery::default_dir();
if let Ok(v) = app.session.execute("file.recovery.open", &serde_json::json!({}))
&& let Some(n) = v.get("opened").and_then(|o| o.as_array()).map(Vec::len).filter(|n| *n > 0)
{
app.set_status(format!("Recovered {n} unsaved presentation{} from the last session", if n == 1 { "" } else { "s" }));
}
}
if let Some(dictionary) = app_dirs::user_dictionary() {
deckcraft_engine::spell::set_user_dictionary_path(dictionary);
}
if session_unavailable {
app.set_status("Another DeckCraft Nightly window owns this profile: its session health is unavailable here.");
} else if previous_unclean {
app.set_status("DeckCraft Nightly closed unexpectedly last time.");
creator_notice.store(true, std::sync::atomic::Ordering::Relaxed);
}
app.integrated_titlebar = cfg!(target_os = "macos");
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
@@ -457,10 +329,7 @@ fn main() -> eframe::Result {
apple_events.connect(&cc.egui_ctx),
)))
}),
);
// The exit hook normally finished it already; this covers a start that never created a window.
nightly_session::finish_once(&session, notice_shown.load(std::sync::atomic::Ordering::Relaxed));
result
)
}
#[cfg(test)]
@@ -530,53 +399,6 @@ mod tests {
}
}
/// The delimiter is the Nightly Launcher's file list, never a file name of its own.
#[test]
fn the_delimiter_ends_the_flags_and_leaves_only_files() {
let launch = startup(None, ["--", "--control", "deck.pptx"].map(str::to_string));
assert!(matches!(launch, Startup::Run { control_port: None, .. }));
if let Startup::Run { files, .. } = launch {
assert_eq!(files, ["--control".to_string(), "deck.pptx".to_string()]);
}
}
/// The desktop crate's build script and the UI crate's read the same channel switch.
#[test]
fn both_crates_agree_on_the_compiled_channel() {
assert_eq!(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, deckcraft_ui_egui::flavor::is_nightly());
assert_eq!(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1), "DeckCraft Nightly");
}
/// The exit hook (the Nightly session record) runs once, on the one exit path macOS has.
/// The check runs in a child with `DECKCRAFT_NO_PREFS=1`: `on_exit` saves the preferences
/// otherwise, and this test never loads the ones already on the machine. Not on macOS
/// itself: there `on_exit` ends the process, which is the behaviour the test above checks.
#[cfg(not(target_os = "macos"))]
#[test]
fn leaving_runs_the_exit_hook_once() {
if std::env::var_os("DECKCRAFT_TEST_EXIT_HOOK").is_some() {
let runs = std::rc::Rc::new(std::cell::Cell::new(0));
let counted = runs.clone();
let services = Services { at_exit: Some(Box::new(move || counted.set(counted.get() + 1))), ..Default::default() };
let mut app = App(SlideApp::new(Session::new(), services));
eframe::App::on_exit(&mut app);
assert_eq!(runs.get(), 1);
eframe::App::on_exit(&mut app);
assert_eq!(runs.get(), 1, "a second exit must not run the hook again");
println!("exit hook ran once");
return;
}
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::leaving_runs_the_exit_hook_once", "--nocapture"])
.env("DECKCRAFT_TEST_EXIT_HOOK", "1")
.env("DECKCRAFT_NO_PREFS", "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{stdout}");
assert!(stdout.contains("exit hook ran once"), "the child didn't run the test: {stdout}");
}
#[test]
fn finder_process_serial_number_is_not_a_file() {
let launch = startup(None, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]);
@@ -687,17 +509,3 @@ mod tests {
assert!(script.contains("has no embedded icon"), "package.ps1 does not reject an iconless exe");
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
-277
View File
@@ -1,277 +0,0 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Write `bytes` to `path` through a new file in the same directory, then rename it into place.
/// The rename replaces a symlink rather than following it, so a raced alias never reaches another
/// file; the created file is mode 0600 and is synced before the rename.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let directory = path.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the session record has no directory"))?;
let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the session record has no file name"))?;
let temporary = directory.join(format!(".{}.{}.{}.tmp", name.to_string_lossy(), std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o600);
}
let mut file = options.open(&temporary)?;
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
match std::fs::rename(&temporary, path) {
Ok(()) => Ok(()),
Err(error) => {
let _ = std::fs::remove_file(&temporary);
Err(error)
}
}
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet (a renderer failure before the app callback), the record is left for the next owner
/// to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("deckcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The next start still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
// Without an earlier interruption, a handled failure still clears normally.
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
-70
View File
@@ -1,70 +0,0 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
-622
View File
@@ -1,622 +0,0 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use crate::app_dirs::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
/// The DeckCraft Nightly Flatpak app id (`packaging/linux/flatpak-bundle.sh`), the one Flatpak
/// instance a Nightly profile may inherit.
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.deckcraft.nightly";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("DeckCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
// install folder is not known here; the executable's own folder is fenced below.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DeckCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("DeckCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("deckcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/deckcraft", "/usr/local/bin/deckcraft", "/opt/deckcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.deckcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/DeckCraft"),
library.join("Caches/DeckCraft"),
library.join("Caches/ai.storyteller.deckcraft"),
library.join("Preferences/DeckCraft"),
library.join("Preferences/ai.storyteller.deckcraft.plist"),
library.join("Saved Application State/ai.storyteller.deckcraft.savedState"),
home.join("Applications/DeckCraft.app"),
PathBuf::from("/Applications/DeckCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (Dictionaries, logs, settings and so on) must
/// resolve inside it, so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
// The one nested file Nightly writes itself: a link at Dictionaries/user.dic would append
// "add to dictionary" words to the stable app's file instead of this profile's.
private_subdirectory(root, std::path::Path::new("Dictionaries").join("user.dic"), "user dictionary")?;
Ok(())
}
/// Recognise a portable data namespace in both the supplied and resolved path. DeckCraft ships no
/// portable package, so this only refuses a hand-made copy; it is not an inventory of arbitrary
/// custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// Above the chosen folder itself, a marker only counts beside a DeckCraft executable, so an
// unrelated portable.txt higher up (in a user folder or at a drive root) does not refuse it.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["deckcraft.exe", "deckcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
/// boundary tests exercise the real policy without starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) {
// The native tar and app-bundle rows are not Flatpak packages: inheriting a Flatpak
// runtime could point another profile at the stable app's data. DeckCraft Nightly's own
// Flatpak (packaging/linux/flatpak-bundle.sh) is the one allowed instance, matched by its
// exact id; the stable id and any other app are refused.
if platform == Platform::Windows || id != NIGHTLY_FLATPAK_ID {
return Err("nightly-v1 accepts only the DeckCraft Nightly Flatpak instance; launch through the native Launcher".into());
}
}
let chosen = canonical_future(root)?;
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable DeckCraft copy or its DeckCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this
// private profile, including toward a Stable portable directory not in our known roots.
private_subdirectory(&chosen, "Recovery", "recovery folder")?;
private_subdirectory(&chosen, "Dictionaries", "dictionary folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "Recovery", "recovery folder")?;
private_subdirectory(&confirmed, "Dictionaries", "dictionary folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("deckcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/deckcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
}
}
let private = fixture.root.join("DeckCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/share/deckcraft/recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery);
}
/// The public entry point reads the host platform and refuses a relative root before probing.
#[cfg(target_os = "linux")]
#[test]
fn the_public_validator_uses_the_host_platform_and_creates_only_the_profile() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/deckcraft");
let created = validate(&root, |key| fixture.get(key), Some(&fixture.exe), crate::app_dirs::ensure_writable)
.expect("a private profile under HOME is valid on Linux");
assert_eq!(created, root);
assert!(created.is_dir());
let probed = std::cell::Cell::new(false);
let refused = validate(
Path::new("relative/profile"),
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(refused.is_err());
assert!(!probed.get(), "a relative root is refused before the write probe");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/deckcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Recovery"), platform));
assert!(overlaps(&root.join("Recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("deckcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("deckcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/deckcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/DeckCraft Nightly.app/Contents/MacOS/DeckCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/DeckCraft",
"Caches/DeckCraft",
"Caches/ai.storyteller.deckcraft",
"Preferences/DeckCraft",
"Saved Application State/ai.storyteller.deckcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/deckcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_and_install_fences_remain_active() {
let fixture = Fixture::new();
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("DeckCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/deckcraft")).is_ok());
}
#[test]
fn windows_default_msi_install_folders_are_fenced() {
let mut fixture = Fixture::new();
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("DeckCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("DeckCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("deckcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not DeckCraft's install");
}
#[test]
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
let fixture = Fixture::new();
let portable = fixture.root.join("D/DC");
std::fs::create_dir_all(&portable).unwrap();
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
std::fs::write(portable.join("deckcraft.exe"), b"stable portable executable, never run").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.unwrap_err().contains("portable"));
assert!(!probed.get());
assert!(!candidate.exists());
}
}
// A portable.txt that no DeckCraft executable sits beside is someone else's file.
let unrelated = fixture.root.join("user folder");
std::fs::create_dir_all(&unrelated).unwrap();
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/deckcraft")).is_ok());
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.deckcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
}
#[cfg(unix)]
#[test]
fn any_profile_entry_alias_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/deckcraft/logs");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-log"), b"stable log bytes").unwrap();
for name in ["Dictionaries", "logs", "ui.json"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-dictionaries")).unwrap();
std::fs::write(private.join("ui.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-dictionaries"), private.join("Dictionaries")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("stable-log")).unwrap(), b"stable log bytes");
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/deckcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
// The stable Flatpak instance, or any other app's, is not a Nightly launch.
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.deckcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.insert("FLATPAK_ID".into(), "org.example.other".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
// DeckCraft Nightly's own Flatpak is the one allowed instance.
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
assert!(fixture.check(Platform::Linux, &candidate).is_ok());
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"regular file").unwrap();
assert!(fixture.check(Platform::Linux, &file.join("nightly")).is_err());
let candidate = fixture.home().join("nightly/profiles/deckcraft");
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "read-only")),
);
assert!(result.unwrap_err().contains("not writable"));
assert!(!candidate.join("Recovery").exists(), "a failed probe leaves no stable fallback behind");
}
#[test]
fn relative_roots_and_parent_traversal_are_refused() {
let fixture = Fixture::new();
for candidate in [PathBuf::from("relative/nightly"), fixture.home().join("nightly/../escape")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

-61
View File
@@ -1,61 +0,0 @@
{
"title": "DeckCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"inputs": [
{
"path": "assets/app-icon/deckcraft-1024.png",
"sha256": "457cb046a1a4f2e13f06cf7e2e071cb48f6011633ed629b99ff348be4ca91ce0",
"purpose": "native padded Mac 1024 master; not upscaled from 256"
},
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png",
"sha256": "66343901b993332bceadf13277e6a028b80b2fb3a1e215b841c855be731e5130",
"purpose": "stable 256 window icon the nightly icon replaces"
}
],
"method": {
"kind": "original code-generated derivative of the project-owned icon",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#f26b1d"
},
"nightly_background": "#a6420c",
"transform": "Solve each pixel's background contribution a in p = a*F + (1-a)*background for the ink and paper foregrounds, then recolour only the background region reached by a flush inward from the icon's transparent padding, so the accent bars that share the background colour keep their brightness behind the ink outlines. Preserve alpha, padding, foreground and detail RGBA. Derive native-size frames separately by area-averaging from the 1024 master (not upscaled from 256) and pack them into ICO/ICNS. No crescent, letter or badge.",
"generator": "pure-Python stdlib script (zlib/struct), run once by the porting agent; not committed, matching PhotoCraft's provenance-only record",
"generator_sha256": "0f90e2d49fe8fc3f2c75c442e730f49652e9b47b0bf9b8ee83c0a9214088569e"
},
"outputs": {
"assets/app-icon/deckcraft-nightly.png": "560b27431cba6bc8658bf654c34981687c2061499139a03ba8b15a6ffed0bc9b",
"assets/app-icon/deckcraft-nightly.ico": "8c66648b036da025b29e1f3d981c959f5d3aab818ddea5049a49706eee800a3a",
"assets/app-icon/deckcraft-nightly-1024.png": "b64ef900d0997d7fe99d75b1f5471276cca75029902841d02f045a4f3f8a7f09",
"assets/app-icon/deckcraft-nightly.icns": "3eb88330c1fffb8e7a27667ac7d53deea62d4c99f43e6bf878a0b89d43934b8d"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"ic11": 32,
"icp6": 64,
"ic12": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024
},
"validation": "Input/output hashes, PNG CRC/dimensions and exact container members checked; the source master is unchanged. Native Explorer/Finder/iconutil/app-package qualification remains unrun.",
"ico_frame_format": "16-128 are 32bpp BGRA DIB frames with AND masks (rc.exe/Explorer); 256 is a PNG frame"
}
+3
View File
@@ -2,4 +2,7 @@ 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
-8
View File
@@ -293,14 +293,6 @@ impl Session {
Ok(true)
}
/// Whether Tab has something to do here: text is being edited (it indents, types a tab or goes to the next table
/// cell), or the slide has an object after the selected one. Past the last object it has nothing left to select.
pub fn tab_has_work(&self) -> bool {
let Some(st) = self.active() else { return false };
let last = st.shapes().iter().rev().find(|s| !s.hidden).map(|s| s.id);
st.selection.text.is_some() || (last.is_some() && st.selection.shapes.first().copied() != last)
}
fn cycle_selection(&mut self, forward: bool) -> Result<()> {
let st = self.doc()?;
let ids: Vec<_> = st.shapes().iter().filter(|s| !s.hidden).map(|s| s.id).collect();
+2 -3
View File
@@ -1181,8 +1181,7 @@ mod tests {
c.y_format = Some(r#"_-* #\ ##0\ "₽"_-;\-* #\ ##0\ "₽"_-;_-* "-"??\ "₽"_-;_-@_-"#.into());
c.lang = Some("ru-RU".into());
assert_eq!(c.axis_label(false, 800_000.0), "800\u{a0}000 ₽");
// Excel shows each `?` of the zero section as a space.
assert_eq!(c.axis_label(false, 0.0), "- ₽");
assert_eq!(c.axis_label(false, 0.0), "- ₽");
// No format: General.
assert_eq!(c.axis_label(true, 2.5), "2,5");
c.lang = None;
@@ -1191,7 +1190,7 @@ mod tests {
c.lang = Some("ru-RU".into());
c.series[0].number_format = Some(r#"#,##0\ "₽""#.into());
assert_eq!(c.data_label(&c.series[0], 516_600_000.0), "516\u{a0}600\u{a0}000 ₽");
assert_eq!(c.data_label(&c.series[1], 0.0), "- ₽");
assert_eq!(c.data_label(&c.series[1], 0.0), "- ₽");
}
#[test]
-10
View File
@@ -254,16 +254,6 @@ pub struct MediaClip {
pub height: u32,
}
impl MediaClip {
/// Whether the clip's frame (an audio icon, or a video's poster) stays out of the
/// show picture. `playing` is true while the voice exists and has not ended.
/// Audio with "Hide During Show" set stays hidden even while it plays; video with
/// "Hide While Not Playing" set shows its frame while it plays.
pub fn hidden_during_show(&self, playing: bool) -> bool {
self.hide_while_not_playing && (!self.video || !playing)
}
}
/// One ink stroke (Draw tab): points in slide coordinates with pressure (`0..=1`,
/// where `1` is [`InkStroke::width`]).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+3 -19
View File
@@ -1,7 +1,7 @@
use super::{
ColorRef, Fill, LayoutType, MediaClip, Paragraph, PhType, Placeholder, Presentation, Run, RunProps, SchemeSlot, Shape, ShapeId, ShapeKind,
ShapeStyle, Slide, Table, TextBody, Theme, Xfrm, defaults, ink_pressure_is_legacy, ink_sample_width, parent_of, resolve, sibling_list_mut, style,
text, theme, walk,
ColorRef, Fill, LayoutType, Paragraph, PhType, Placeholder, Presentation, Run, RunProps, SchemeSlot, Shape, ShapeId, ShapeKind, ShapeStyle,
Slide, Table, TextBody, Theme, Xfrm, defaults, ink_pressure_is_legacy, ink_sample_width, parent_of, resolve, sibling_list_mut, style, text,
theme, walk,
};
use crate::resolve::Ctx;
@@ -339,19 +339,3 @@ fn colour_alpha_follows_alpha_mod_and_off() {
let both = base().with(ColorTransform::Alpha(40000)).with(ColorTransform::AlphaMod(50000));
assert!((both.alpha() - 0.2).abs() < 1e-9, "{}", both.alpha());
}
#[test]
fn hide_during_show_keeps_audio_hidden_while_playing() {
let clip = |video: bool, hide_while_not_playing: bool| MediaClip { video, hide_while_not_playing, ..Default::default() };
// Audio with the flag set stays hidden both idle and playing (#1659).
assert!(clip(false, true).hidden_during_show(false), "audio, flagged, idle");
assert!(clip(false, true).hidden_during_show(true), "audio, flagged, playing");
// Video with the flag set hides only while not playing.
assert!(clip(true, true).hidden_during_show(false), "video, flagged, idle");
assert!(!clip(true, true).hidden_during_show(true), "video, flagged, playing");
// Without the flag nothing is hidden.
assert!(!clip(false, false).hidden_during_show(false), "audio, unflagged, idle");
assert!(!clip(false, false).hidden_during_show(true), "audio, unflagged, playing");
assert!(!clip(true, false).hidden_during_show(false), "video, unflagged, idle");
assert!(!clip(true, false).hidden_during_show(true), "video, unflagged, playing");
}
-3
View File
@@ -1298,9 +1298,6 @@ fn chart_to(c: &dm_chart::Chart) -> cd_chart::Chart {
gridlines: c.gridlines,
minor_gridlines: c.minor_gridlines,
axis_titles: c.axis_titles.clone(),
// DeckCraft's chart model keeps the raw category labels and the 1900 date system.
category_format: None,
date_1904: false,
style: c.style,
palette: c.palette.clone(),
plot_fill: c.plot_fill.as_ref().map(fill_to),
-12
View File
@@ -2374,15 +2374,6 @@ fn pptx_potx_ppsx_export_parity_preserves_masters_charts_themes_and_timing() {
..Default::default()
});
let edited_values = vec![Some(111.5), Some(222.25), Some(333.75), Some(444.0)];
let chart_slide_idx = p.slides.iter().position(|sl| sl.shapes.iter().any(|s| s.name == "Chart 0")).expect("chart slide");
{
let ch_shape = Arc::make_mut(&mut p.slides[chart_slide_idx]).shapes.iter_mut().find(|s| s.name == "Chart 0").expect("Chart 0");
ch_shape.name = "Revenue Chart".into();
let ShapeKind::Chart(ch) = &mut ch_shape.kind else { panic!("expected chart") };
ch.series[0].values = edited_values.clone();
}
for (ext, expected_ct) in [
("pptx", "presentationml.presentation.main+xml"),
("potx", "presentationml.template.main+xml"),
@@ -2401,8 +2392,5 @@ fn pptx_potx_ppsx_export_parity_preserves_masters_charts_themes_and_timing() {
let cue = reopened.slides[0].shapes.iter().find(|s| s.name == "Cue").expect("cue");
let ShapeKind::Media(clip) = &cue.kind else { panic!("expected media") };
assert!(clip.autoplay && clip.loop_play && (clip.volume - 0.5).abs() < 1e-3);
let chart_shape = reopened.slides[chart_slide_idx].shapes.iter().find(|s| s.name == "Revenue Chart").expect("named chart");
let ShapeKind::Chart(chart) = &chart_shape.kind else { panic!("expected chart") };
assert_eq!(chart.series[0].values, edited_values, "{ext}");
}
}
+8 -33
View File
@@ -49,8 +49,6 @@ enum Paint {
Pattern(String, Rgba, Rgba),
/// `a:noFill`: only the outline, if any, shows.
Nothing,
/// A line series' legend key: its colour and width, and whether it carries a marker.
Line(Rgba, f64, bool),
}
/// The paint of fill `f` as a bar or legend key draws it; the palette's `fallback` when the file
@@ -74,20 +72,6 @@ fn fill_with(ctx: &mut RenderContext, p: &Paint, r: Rect, m: Affine) {
}
Paint::Pattern(name, fg, bg) => crate::pattern::fill(ctx, name, *fg, *bg, 1.0, &r.to_path(0.1), m),
Paint::Nothing => {}
Paint::Line(c, width, marker) => {
// A short stretch of the series' line through the key's middle, with the marker on it.
let mid = (r.y0 + r.y1) / 2.0;
let mut p = BezPath::new();
p.move_to((r.x0, mid));
p.line_to((r.x1, mid));
ctx.set_transform(m);
ctx.set_paint(color(*c, 1.0));
ctx.set_stroke(kurbo::Stroke::new(width.min(r.height() * 0.4)));
ctx.stroke_path(&p);
if *marker {
ctx.fill_path(&kurbo::Circle::new(((r.x0 + r.x1) / 2.0, mid), r.height() * 0.3).to_path(0.1));
}
}
}
}
@@ -113,13 +97,6 @@ fn bar_paint(ctx: &Ctx, c: &Chart, si: usize, pi: usize, s: &deckcraft_model::ch
paint_of(ctx, s.fill.as_ref(), series_color(ctx, c, si))
}
/// Colour of pie slice `i`: its `<c:dPt>` solid fill, else the palette's. Slices and legend keys share it.
fn pie_slice_color(ctx: &Ctx, c: &Chart, s: Option<&deckcraft_model::chart::Series>, i: usize) -> Rgba {
s.and_then(|s| s.point_fills.iter().find(|(k, _)| *k == i))
.and_then(|(_, f)| if let Fill::Solid { color: cc } = f { Some(ctx.color(cc, None)) } else { None })
.unwrap_or_else(|| series_color(ctx, c, i))
}
fn polyline(pts: &[Point]) -> BezPath {
let mut p = BezPath::new();
for (k, q) in pts.iter().enumerate() {
@@ -636,7 +613,7 @@ fn build_legend_items(rctx: &Ctx, c: &Chart, pie: bool, waterfall: bool) -> Vec<
// A map draws its own colour scale.
vec![]
} else if pie {
c.categories.iter().enumerate().map(|(i, n)| (n.clone(), Paint::Color(pie_slice_color(rctx, c, c.series.first(), i)), None)).collect()
c.categories.iter().enumerate().map(|(i, n)| (n.clone(), Paint::Color(series_color(rctx, c, i)), None)).collect()
} else {
c.series
.iter()
@@ -644,14 +621,7 @@ fn build_legend_items(rctx: &Ctx, c: &Chart, pie: bool, waterfall: bool) -> Vec<
.map(|(i, s)| {
let k = c.series_kind(s);
let line = !k.is_bar_like() && !matches!(k, ChartType::Area | ChartType::StackedArea | ChartType::FilledRadar);
if matches!(k, ChartType::Line | ChartType::LineMarkers | ChartType::StackedLine | ChartType::Radar) {
let lw = s.line.as_ref().and_then(|l| l.width).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(2.25).clamp(0.25, 20.0);
(
s.name.clone(),
Paint::Line(series_line(rctx, c, i, s), lw, k == ChartType::LineMarkers || (k == ChartType::Radar && s.marker.is_some())),
None,
)
} else if line {
if line {
(s.name.clone(), Paint::Color(series_line(rctx, c, i, s)), None)
} else if k.is_bar_like() {
let paint = if c.vary_colors && c.series.len() == 1 && s.fill.is_none() {
@@ -1209,7 +1179,12 @@ fn draw_pie(ctx: &mut RenderContext, rctx: &Ctx, c: &Chart, m: Affine, area: Rec
p.extend(arc.append_iter(0.1));
p.close_path();
ctx.set_transform(m);
let col = pie_slice_color(rctx, c, Some(s), i);
let col = s
.point_fills
.iter()
.find(|(k, _)| *k == i)
.and_then(|(_, f)| if let Fill::Solid { color: cc } = f { Some(rctx.color(cc, None)) } else { None })
.unwrap_or_else(|| series_color(rctx, c, i));
ctx.set_paint(color(col, 1.0));
ctx.fill_path(&p);
ctx.set_paint(color(Rgba::WHITE, 1.0));
-62
View File
@@ -3404,65 +3404,3 @@ fn a_shape_whose_outline_is_not_finite_is_not_drawable() {
quad.paths[0].path = path;
assert!(!crate::geometry::drawable(&quad, m, 100.0, 50.0));
}
/// A WMF without a placeable header (the frame comes from its window records) holding `records`
/// (function, parameter bytes).
fn wmf_bare(records: &[(u16, Vec<u8>)]) -> Vec<u8> {
let mut body = Vec::new();
let mut max_words = 3u32;
for (func, params) in records {
let words = (6 + params.len() as u32).div_ceil(2);
max_words = max_words.max(words);
body.extend(words.to_le_bytes());
body.extend(func.to_le_bytes());
body.extend(params);
if params.len() % 2 == 1 {
body.push(0);
}
}
body.extend([3, 0, 0, 0, 0, 0]);
let mut f = Vec::new();
for v in [1u16, 9, 0x300] {
f.extend(v.to_le_bytes());
}
f.extend((((18 + body.len()) / 2) as u32).to_le_bytes());
f.extend(1u16.to_le_bytes());
f.extend(max_words.to_le_bytes());
f.extend(0u16.to_le_bytes());
f.extend(body);
f
}
#[test]
fn metafile_scaled_viewport_places_each_sub_picture_in_its_half() {
// #2069: an 800 × 400 frame drawn as two sub-pictures. Each saves the DC, halves the viewport
// width with SCALEVIEWPORTEXT, sets its own 400 × 400 window (the second shifted right by its
// window origin), draws a circle and restores the DC: red on the left, blue on the right.
let sub = |origin_x: i32, colorref: u32| {
let mut brush = 0u16.to_le_bytes().to_vec();
brush.extend(colorref.to_le_bytes());
brush.extend(0u16.to_le_bytes());
vec![
(0x001E, vec![]), // SAVEDC
(0x0103, i16s(&[8])), // SETMAPMODE MM_ANISOTROPIC
(0x0412, i16s(&[1, 1, 2, 1])), // SCALEVIEWPORTEXT y 1/1, x 1/2
(0x020B, i16s(&[0, origin_x])), // SETWINDOWORG
(0x020C, i16s(&[400, 400])), // SETWINDOWEXT
(0x02FC, brush), // CREATEBRUSHINDIRECT
(0x012D, i16s(&[0])), // SELECTOBJECT
(0x0418, i16s(&[380, 380, 20, 20])), // ELLIPSE
(0x0127, i16s(&[-1])), // RESTOREDC
(0x01F0, i16s(&[0])), // DELETEOBJECT
]
};
let mut recs = vec![(0x020B, i16s(&[0, 0])), (0x020C, i16s(&[400, 800]))];
recs.extend(sub(0, 0x0000_00FF));
recs.extend(sub(-400, 0x00FF_0000));
let img = crate::metafile::rasterize(&wmf_bare(&recs), 200).expect("raster");
assert_eq!(img.dimensions(), (200, 100));
let red = |p: &image::Rgba<u8>| p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200;
let blue = |p: &image::Rgba<u8>| p[2] > 200 && p[0] < 60 && p[1] < 60 && p[3] > 200;
assert!(red(img.get_pixel(50, 50)), "red circle in the left half: {:?}", img.get_pixel(50, 50));
assert!(blue(img.get_pixel(150, 50)), "blue circle in the right half: {:?}", img.get_pixel(150, 50));
assert!(img.get_pixel(100, 50)[3] < 128, "the circles don't meet in the middle: {:?}", img.get_pixel(100, 50));
}
@@ -1,20 +0,0 @@
use deckcraft_color::Rgba;
use deckcraft_model::chart::ChartType;
use deckcraft_model::style::{ColorRef, Fill};
use deckcraft_model::{Chart, Presentation, Shape, ShapeId, ShapeKind, Xfrm};
use deckcraft_render::{RenderOpts, render_slide};
#[test]
fn pie_legend_keys_take_the_point_colours() {
let mut c = Chart::sample(ChartType::Pie);
c.title = None;
c.legend = Some("r".into());
c.series[0].point_fills = vec![(0, Fill::solid(ColorRef::rgb(Rgba::rgb(255, 0, 255))))];
let sh = Shape { id: ShapeId(2028), xfrm: Some(Xfrm::new(0.0, 0.0, 960.0, 540.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
let mut p = Presentation::default();
std::sync::Arc::make_mut(&mut p.slides[0]).shapes = vec![sh];
let img = render_slide(&p, 0, &RenderOpts { scale: 1.0, ..Default::default() });
// The pie stays well left of x = 850; only the legend column lies beyond it.
let key = (850..img.width).flat_map(|x| (0..img.height).map(move |y| (x, y))).filter(|(x, y)| img.pixel(*x, *y)[..3] == [255, 0, 255]).count();
assert!(key > 20, "the legend key of the overridden slice is drawn in its colour: {key} px");
}
@@ -1,53 +0,0 @@
use deckcraft_model::chart::ChartType;
use deckcraft_model::style::Line;
use deckcraft_model::{Chart, ColorRef, Presentation, Rgba, Shape, ShapeId, ShapeKind, Xfrm};
use deckcraft_render::{RenderOpts, render_slide};
/// Rows and columns of the pixels matching `want` in the legend's key column, right of the plot.
fn key_extent(kind: ChartType, want: &dyn Fn([u8; 4]) -> bool) -> (usize, usize) {
let mut c = Chart::sample(kind);
c.title = None;
c.legend = Some("r".into());
c.series.truncate(2);
for (s, (name, rgb)) in c.series.iter_mut().zip([("A", Rgba::rgb(255, 0, 0)), ("B", Rgba::rgb(0, 0, 255))]) {
s.name = name.into();
s.line = Some(Line::solid(ColorRef::rgb(rgb), 3.0));
}
let sh = Shape { id: ShapeId(1), xfrm: Some(Xfrm::new(0.0, 0.0, 960.0, 540.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() };
let mut p = Presentation::default();
std::sync::Arc::make_mut(&mut p.slides[0]).shapes = vec![sh];
let img = render_slide(&p, 0, &RenderOpts { scale: 1.0, ..Default::default() });
let hits: Vec<(u32, u32)> =
(870..img.width).flat_map(|x| (0..img.height).map(move |y| (x, y))).filter(|(x, y)| want(img.pixel(*x, *y))).collect();
let rows = hits.iter().map(|h| h.1).collect::<std::collections::BTreeSet<_>>().len();
let cols = hits.iter().map(|h| h.0).collect::<std::collections::BTreeSet<_>>().len();
(rows, cols)
}
fn red(p: [u8; 4]) -> bool {
p[0] > 200 && p[1] < 60 && p[2] < 60
}
fn blue(p: [u8; 4]) -> bool {
p[0] < 60 && p[1] < 60 && p[2] > 200
}
#[test]
fn line_chart_legend_key_is_a_stretch_of_the_line() {
// A 3 pt line key is a few pixels tall; a filled square key is over ten.
for want in [&red as &dyn Fn([u8; 4]) -> bool, &blue] {
let (rows, cols) = key_extent(ChartType::Line, want);
assert!((2..=5).contains(&rows), "line key is {rows} rows tall");
assert!(cols >= 8, "line key is {cols} columns wide");
}
}
#[test]
fn line_with_markers_legend_key_has_a_marker_on_the_line() {
// The marker is wider than the line but smaller than a filled square.
for want in [&red as &dyn Fn([u8; 4]) -> bool, &blue] {
let (rows, cols) = key_extent(ChartType::LineMarkers, want);
assert!((6..=10).contains(&rows), "marker key is {rows} rows tall");
assert!(cols >= 8, "marker key is {cols} columns wide");
}
}
+6 -66
View File
@@ -150,13 +150,10 @@ pub(crate) struct BreakParams<'a> {
pub(crate) default_tab: f64,
pub(crate) x0_first: f64,
pub(crate) x0_rest: f64,
/// Absolute position of the hanging-indent implicit stop (`marL`), when the first
/// line starts left of the margin. [`tab_advance`] treats it as a left stop.
pub(crate) hang: Option<f64>,
}
pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine> {
let BreakParams { first_w, rest_w, wrap, tab_stops, default_tab, x0_first, x0_rest, hang: hang_stop } = *params;
let BreakParams { first_w, rest_w, wrap, tab_stops, default_tab, x0_first, x0_rest } = *params;
let text: String = p.cells.iter().map(|c| c.ch).collect();
let (allowed, _) = break_opportunities(&text, p.props.latin_line_break.unwrap_or(false));
let hang = p.props.hanging_punct.unwrap_or(false);
@@ -182,8 +179,7 @@ pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine>
break;
}
let adv = if c == '\t' {
// The implicit stop is for the first line only: later lines start at the margin.
tab_advance(x0 + x, tab_stops, default_tab, tab_segment(&p.cells, i), if lines.is_empty() { hang_stop } else { None }, x0 + avail)
tab_advance(x0 + x, tab_stops, default_tab, tab_segment(&p.cells, i))
} else {
p.cells.get(i).map(|c| c.adv).unwrap_or(0.0)
};
@@ -309,40 +305,11 @@ pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64) {
/// Advance of a tab at `x` (from the start edge) to the next stop, placing the text after it
/// (`seg`: its width, and its width before the decimal point) as the stop aligns it but never
/// moving back, as PowerPoint does; past the last stop, to the next default stop.
/// `hang` is the hanging-indent implicit stop (`marL`): the first tab on a first line that
/// starts left of the margin goes there instead, as PowerPoint does. The nearer of the
/// implicit and the regular stops wins; an explicit stop within 0.5 pt of it keeps its
/// own alignment.
///
/// `right` is the line's right edge in the same coordinate space as `x` (the text area's left
/// edge plus the line's start offset and width): a stop set past that edge acts as one at the
/// edge, as PowerPoint treats it (a right-aligned stop there ends the text at the margin).
pub(crate) fn tab_advance(x: f64, stops: &[Tab], default_tab: f64, seg: (f64, f64), hang: Option<f64>, right: f64) -> f64 {
pub(crate) fn tab_advance(x: f64, stops: &[Tab], default_tab: f64, seg: (f64, f64)) -> f64 {
// `stops` is in position order (`tabs_of`): the next stop is the first past x.
// A NaN `x` (a NaN spacing upstream) skips the lookup and takes the finite default-stop path.
if !x.is_nan()
&& let Some(h) = hang
&& h.is_finite()
&& x < h - 0.5
{
let explicit = stops.get(stops.partition_point(|s| s.pos <= x + 0.5));
let d = if default_tab > 1.0 { default_tab } else { 72.0 };
let default_next = ((x / d).floor() + 1.0) * d;
let explicit_wins = match explicit {
// Compared where the stop takes effect: one past the line's edge ends there (below).
Some(s) => {
let pos = if right.is_finite() && right > 0.0 { s.pos.min(right) } else { s.pos };
pos < h - 0.5 || (pos - h).abs() <= 0.5
}
None => h >= default_next - 0.5,
};
if !explicit_wins {
return (h - x).max(1.0);
}
}
if let Some(s) = stops.get(stops.partition_point(|s| s.pos <= x + 0.5)).filter(|_| !x.is_nan()) {
let pos = if right.is_finite() && right > 0.0 { s.pos.min(right) } else { s.pos };
let to = (pos - x).max(0.0);
let to = s.pos - x;
return match s.align {
TabAlign::Left => to,
TabAlign::Right => (to - seg.0).max(0.0),
@@ -362,34 +329,7 @@ mod tab_tests {
#[test]
fn a_nan_position_takes_the_finite_default_stop() {
let stops = [Tab { pos: 100.0, align: TabAlign::Left }];
assert!(tab_advance(f64::NAN, &stops, 72.0, (0.0, 0.0), None, 600.0).is_finite());
assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0), None, 600.0), 90.0);
}
#[test]
fn a_stop_past_the_edge_is_compared_with_the_hang_at_the_edge() {
// The 700 pt stop takes effect at the 60 pt edge, which comes before the 80 pt hang: it
// wins, and right-aligned text after it ends at the edge (60 - 20), not at the hang.
let stops = [Tab { pos: 700.0, align: TabAlign::Right }];
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.0, 20.0), Some(80.0), 60.0), 40.0);
}
#[test]
fn a_stop_past_the_line_ends_at_its_edge() {
let stops = [Tab { pos: 700.0, align: TabAlign::Right }];
// Right-aligned text after the tab ends at the line's right edge, not 700.
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0), None, 600.0), 500.0);
// A stop inside the line keeps its own position.
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0), None, 800.0), 600.0);
}
#[test]
fn an_offset_line_clamps_to_its_absolute_right_edge() {
// The stop and the edge are absolute coordinates: a 100 pt start offset does not move the
// edge in to 500 pt, so an inside stop at 550 stays there and one past 600 ends at 600.
let inside = [Tab { pos: 550.0, align: TabAlign::Right }];
assert_eq!(tab_advance(100.0, &inside, 72.0, (100.0, 100.0), None, 600.0), 350.0);
let past = [Tab { pos: 700.0, align: TabAlign::Right }];
assert_eq!(tab_advance(100.0, &past, 72.0, (100.0, 100.0), None, 600.0), 400.0);
assert!(tab_advance(f64::NAN, &stops, 72.0, (0.0, 0.0)).is_finite());
assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0)), 90.0);
}
}
+4 -15
View File
@@ -233,7 +233,6 @@ struct ParaEnv<'a> {
first_x: f64,
rest_x: f64,
tabs: &'a [Tab],
hang: Option<f64>,
}
impl ParaEnv<'_> {
@@ -313,12 +312,6 @@ fn place_paragraph(p: &ParaShaped, pi: usize, g: &BoxGeom, spacing: (f64, bool),
let first_x = first_line_start(p.bullet.is_some(), margin, indent, bullet_w);
let rest_x = margin;
let tabs = tabs_of(props);
// A hanging first line (marL > 0, indent < 0) treats the indent position (marL) as an
// implicit tab stop for its first tab; later lines already start there, so the stop
// only ever applies ahead of the first line's start.
// LTR only: the implicit stop is measured from the left margin, and RTL tab handling is
// out of this change's scope (its stops are not mirrored here yet).
let hang = (!p.rtl && margin - first_x > 0.5 && margin.is_finite()).then_some(margin);
let first_w = (g.col_w - first_x - mr).max(1.0);
let rest_w = (g.col_w - rest_x - mr).max(1.0);
let raw = break_lines(
@@ -331,14 +324,13 @@ fn place_paragraph(p: &ParaShaped, pi: usize, g: &BoxGeom, spacing: (f64, bool),
default_tab: props.default_tab.unwrap_or(72.0),
x0_first: first_x,
x0_rest: rest_x,
hang,
},
);
// The first paragraph's space before counts only when the body says so.
let before = if pi == 0 && !first_last { 0.0 } else { spacing_pts(props.space_before, p.lead_size) };
flow.y += before.max(0.0) + flow.prev_after;
let first_line_idx = flow.lines.len();
let env = ParaEnv { p, g, reduce, margin, indent, mr, bullet_w, first_x, rest_x, tabs: &tabs, hang };
let env = ParaEnv { p, g, reduce, margin, indent, mr, bullet_w, first_x, rest_x, tabs: &tabs };
for (li, rl) in raw.iter().enumerate() {
let is_last = li + 1 == raw.len();
let placed = place_line(&env, pi, rl, li, is_last, flow);
@@ -384,10 +376,7 @@ fn line_extent(p: &ParaShaped, rl: &RawLine) -> (f64, f64, f64) {
}
/// Logical advance of each cell on the line (tabs measure from the start edge) and their sum.
/// `hang` is the implicit first-line stop, or `None` on later lines: they already start at the
/// margin, and negative character spacing can dip `x` below it, which would wrongly re-trigger
/// the stop.
fn line_advances(env: &ParaEnv, rl: &RawLine, is_last: bool, x0: f64, hang: Option<f64>, avail: f64) -> (Vec<f64>, f64) {
fn line_advances(env: &ParaEnv, rl: &RawLine, is_last: bool, x0: f64) -> (Vec<f64>, f64) {
let p = env.p;
let line_cells = p.cells.get(rl.start..rl.end).unwrap_or(&[]);
let n = rl.end.saturating_sub(rl.start);
@@ -399,7 +388,7 @@ fn line_advances(env: &ParaEnv, rl: &RawLine, is_last: bool, x0: f64, hang: Opti
let a = if shy_end && k + 1 == n {
p.faces.get(c.face).zip(p.styles.get(c.style)).map(|(f, st)| measure_str(f, st.size, "-").0).unwrap_or(0.0)
} else if c.ch == '\t' {
tab_advance(x0 + x, env.tabs, p.props.default_tab.unwrap_or(72.0), tab_segment(&p.cells, rl.start + k), hang, x0 + avail)
tab_advance(x0 + x, env.tabs, p.props.default_tab.unwrap_or(72.0), tab_segment(&p.cells, rl.start + k))
} else {
c.adv
};
@@ -531,7 +520,7 @@ fn place_line(env: &ParaEnv, pi: usize, rl: &RawLine, li: usize, is_last: bool,
let avail = (g.col_w - x0 - env.mr).max(0.0);
let n = rl.end.saturating_sub(rl.start);
let line_cells = p.cells.get(rl.start..rl.end).unwrap_or(&[]);
let (mut adv, width) = line_advances(env, rl, is_last, x0, if li == 0 { env.hang } else { None }, avail);
let (mut adv, width) = line_advances(env, rl, is_last, x0);
let align = props.align.unwrap_or(Align::Left);
let slack = (avail - width).max(0.0);
let stretch = !is_last && g.wrap && slack > 0.0;
-112
View File
@@ -1419,54 +1419,6 @@ fn tab_stops_align_the_text_after_them() {
assert!((l.lines[0].edges[4].0 - x0(&l) - 72.0).abs() < 0.01);
}
#[test]
fn a_right_tab_stop_past_the_margin_ends_the_text_at_the_margin() {
// #1663: a layout may set a right tab stop a little past the text area's right edge.
// PowerPoint treats it as one at the margin: the text after it stays on one line and ends
// at the right edge. DeckCraft started it too far right and wrapped the rest.
let l = tabbed("x\tCorrie Ten Boom", &[(700.0, "r")], 600.0);
assert_eq!(l.lines.len(), 1, "{:?}", l.lines.iter().map(|x| (x.start, x.end, x.extent)).collect::<Vec<_>>());
let right = l.inner.x0 + l.inner.width();
assert!((l.lines[0].extent.1 - right).abs() < 0.01, "ends at {:?}, margin {right}", l.lines[0].extent);
}
#[test]
fn an_indented_paragraph_clamps_a_tab_stop_to_its_absolute_right_edge() {
// #1663: the stop and the edge are measured from the text area's left edge, so an indented
// first line does not pull the edge in by its margin. A stop inside it keeps its position;
// one past it ends the text at the margin.
let (p, mut sh) = setup("x\tCorrie Ten Boom", 600.0, 300.0);
let para = &mut sh.text.as_mut().unwrap().paragraphs[0];
for r in &mut para.runs {
r.props.size = Some(18.0);
}
let pp = &mut para.props;
pp.bullet = Some(Bullet::None);
pp.margin_left = Some(100.0);
pp.indent = Some(0.0);
pp.default_tab = Some(72.0);
pp.tabs = Some(vec![deckcraft_model::text::TabStop { pos: 550.0, align: "r".to_string() }]);
let l = lay(&p, &sh, 600.0, 300.0);
assert_eq!(l.lines.len(), 1, "{:?}", l.lines.iter().map(|x| (x.start, x.end, x.extent)).collect::<Vec<_>>());
assert!((l.lines[0].extent.1 - l.inner.x0 - 550.0).abs() < 0.01, "inside stop at {:?}", l.lines[0].extent);
let (p, mut sh) = setup("x\tCorrie Ten Boom", 600.0, 300.0);
let para = &mut sh.text.as_mut().unwrap().paragraphs[0];
for r in &mut para.runs {
r.props.size = Some(18.0);
}
let pp = &mut para.props;
pp.bullet = Some(Bullet::None);
pp.margin_left = Some(100.0);
pp.indent = Some(0.0);
pp.default_tab = Some(72.0);
pp.tabs = Some(vec![deckcraft_model::text::TabStop { pos: 700.0, align: "r".to_string() }]);
let l = lay(&p, &sh, 600.0, 300.0);
assert_eq!(l.lines.len(), 1, "{:?}", l.lines.iter().map(|x| (x.start, x.end, x.extent)).collect::<Vec<_>>());
let right = l.inner.x0 + l.inner.width();
assert!((l.lines[0].extent.1 - right).abs() < 0.01, "ends at {:?}, margin {right}", l.lines[0].extent);
}
#[test]
fn many_tabs_over_many_stops_lay_out_by_position() {
// 20,000 stops given out of order, and 2,000 tabs: each tab finds the next stop by position.
@@ -1487,70 +1439,6 @@ fn a_tab_past_the_end_moves_to_the_next_line() {
assert!((l.lines[1].edges[1].0 - l.inner.x0 - 72.0).abs() < 0.01);
}
/// One paragraph `text` with a hanging indent (`marL`/`indent`), no bullet or explicit stops.
fn hanging_tabbed(text: &str, margin: f64, indent: f64, w: f64) -> TextLayout {
let (p, mut sh) = setup(text, w, 300.0);
let para = &mut sh.text.as_mut().unwrap().paragraphs[0];
for r in &mut para.runs {
r.props.size = Some(18.0);
}
let pp = &mut para.props;
pp.bullet = Some(Bullet::None);
pp.margin_left = Some(margin);
pp.indent = Some(indent);
pp.default_tab = Some(72.0);
pp.tabs = None;
lay(&p, &sh, w, 300.0)
}
#[test]
fn hanging_indent_is_the_first_tab_stop() {
// PowerPoint: with a 0.375 in (27 pt) hanging indent, the first tab on the first line goes
// to marL; later tabs go to the normal default stops.
let l = hanging_tabbed("a\tb\tc", 27.0, -27.0, 600.0);
assert_eq!(l.lines.len(), 1);
let x0 = l.inner.x0;
assert!((l.lines[0].edges[2].0 - x0 - 27.0).abs() < 0.5, "the char after the first tab starts at marL: {:?}", l.lines[0].edges);
assert!((l.lines[0].edges[4].0 - x0 - 72.0).abs() < 0.5, "the char after the second tab starts at the default stop: {:?}", l.lines[0].edges);
// A third tab lands on the next default stop.
let l = hanging_tabbed("a\tb\tc\td", 27.0, -27.0, 600.0);
assert!((l.lines[0].edges[6].0 - l.inner.x0 - 144.0).abs() < 0.5, "{:?}", l.lines[0].edges);
}
#[test]
fn a_tab_on_a_wrapped_line_keeps_the_default_stop() {
// The implicit stop only applies ahead of the first line's start: a tab on the second
// line uses the normal default stop from the box grid (72 pt here), not marL + 27.
let l = hanging_tabbed("AAAA\u{b}\tB", 27.0, -27.0, 600.0);
assert_eq!(l.lines.len(), 2, "{:?}", l.lines.iter().map(|x| (x.start, x.end)).collect::<Vec<_>>());
let x = l.lines[1].edges[1].0 - l.inner.x0;
assert!((x - 72.0).abs() < 0.5, "the wrapped line's tab uses the default stop, got {x}");
assert!((x - 54.0).abs() > 5.0, "and not marL + 27");
}
#[test]
fn a_tab_after_negative_spacing_on_a_later_line_keeps_the_default_stop() {
// #1683 follow-up: the implicit stop is a first-line stop only. Negative character spacing
// can put a later line's cursor left of the margin; its tab must still take the default stop.
let (p, mut sh) = setup("A\u{b}X\tY", 600.0, 300.0);
let para = &mut sh.text.as_mut().unwrap().paragraphs[0];
for r in &mut para.runs {
r.props.size = Some(18.0);
r.props.spacing = Some(-20.0);
}
let pp = &mut para.props;
pp.bullet = Some(Bullet::None);
pp.margin_left = Some(27.0);
pp.indent = Some(-27.0);
pp.default_tab = Some(72.0);
pp.tabs = None;
let l = lay(&p, &sh, 600.0, 300.0);
assert_eq!(l.lines.len(), 2, "{:?}", l.lines.iter().map(|x| (x.start, x.end)).collect::<Vec<_>>());
let x = l.lines[1].edges[2].0 - l.inner.x0;
assert!((x - 72.0).abs() < 0.5, "the later line's tab uses the default stop, got {x}");
assert!((x - 27.0).abs() > 5.0, "and not the first line's margin stop");
}
/// Underline decorations of "ab cd" underlined `u` at 40 pt.
fn underline_decos(u: &str) -> (TextLayout, Vec<Deco>) {
let (p, mut sh) = setup("ab cd", 2000.0, 300.0);
-4
View File
@@ -21,10 +21,6 @@ deckcraft-media = { workspace = true }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
egui_extras = { workspace = true }
craft-ui = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true }
craft-theme = { workspace = true }
craft-window = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
-30
View File
@@ -12,36 +12,6 @@ use std::fmt::Write as _;
use serde_json::Value;
fn main() {
// The compiled channel and the version the binary was built as. The desktop crate's build
// script reads the same two variables, so the About dialog, the window name and the version
// query agree in one build.
println!("cargo::rerun-if-env-changed=DECKCRAFT_BUILD_CHANNEL");
println!("cargo::rerun-if-env-changed=DECKCRAFT_VERSION");
println!("cargo::rustc-check-cfg=cfg(deckcraft_nightly_v1)");
let nightly = match std::env::var("DECKCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo::rustc-cfg=deckcraft_nightly_v1");
true
}
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
println!("cargo::error=unsupported DECKCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
let version = if nightly {
match std::env::var("DECKCRAFT_VERSION") {
Ok(version) if version.contains("-nightly.") => version,
_ => {
println!("cargo::error=nightly-v1 requires an explicit DECKCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo::rustc-env=DECKCRAFT_BUILT_VERSION={version}");
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contributors");
let json = read(&dir.join("contributors.json"), "the About window shows no contributors", |t| {
serde_json::from_str::<Value>(t).map_err(|e| e.to_string())
+7 -11
View File
@@ -21,17 +21,13 @@ fn harness() -> Harness<'static, SlideApp> {
}
let mut app = SlideApp::new(s, Services::default());
app.ui.pane = Some("animation".into());
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
+9 -9
View File
@@ -13,7 +13,6 @@ use super::{
mod clipboard;
mod commands;
mod control;
mod document_focus;
pub(crate) mod files;
mod frame;
mod ime;
@@ -23,7 +22,6 @@ mod playback;
#[cfg(test)]
pub(crate) use clipboard::{OBJECTS_MARKER, system_clipboard_text};
pub(crate) use document_focus::DocumentFocus;
#[cfg(test)]
pub(crate) use files::web_image_files;
pub use keys::key_name;
@@ -71,7 +69,6 @@ impl SlideApp {
synthetic_generation: 0,
synthetic_target: None,
synthetic_focus: None,
document_focus: DocumentFocus::default(),
synthetic_injected_time: None,
ribbon_scroll: HashMap::new(),
show_instance: 0,
@@ -89,8 +86,6 @@ impl SlideApp {
print_previews: files::PrintPreviews::default(),
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: crate::framework::host(),
pending_copy: None,
capture: capture::Capture::default(),
styled: false,
@@ -145,7 +140,7 @@ impl SlideApp {
/// Start the helper of an update that is ready, so that it installs once the process has
/// exited. The desktop shell calls it in `on_exit`, which ends the process on macOS before the
/// app is dropped. Later calls do nothing, and a Nightly launch never starts a stable update.
/// app is dropped. Later calls do nothing.
#[cfg(not(target_arch = "wasm32"))]
pub fn start_pending_update(&mut self) {
updates_ui::start_pending_update(self);
@@ -252,6 +247,14 @@ impl SlideApp {
if !self.synthetic.is_empty() || !self.synthetic_next.is_empty() || self.synthetic_pending {
ctx.request_repaint();
}
// Closing the window with unsaved changes asks first.
if ctx.input(|i| i.viewport().close_requested()) && !self.quit_confirmed && self.session.documents().iter().any(|d| d.is_dirty()) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.show = None;
if self.dialog.as_ref().is_none_or(|d| d.id != "quit") {
self.dialog = Some(dialogs::Dialog::new("quit"));
}
}
self.autosave_if_due(ctx);
self.tick_media_clock(ctx);
self.note_settled_composition(ctx);
@@ -290,7 +293,6 @@ impl SlideApp {
let ctx = ui.ctx().clone();
self.ime_frame_viewport = Some(ctx.viewport_id());
self.ime_pending = None;
let document_before = self.document_focus.drawn.take();
if !self.ui_setup(&ctx) {
// This pass is discarded for the new fonts. The input events were already consumed
// by egui, so keep them queued for the next frame instead of silently losing them.
@@ -354,13 +356,11 @@ impl SlideApp {
}
}
});
self.finish_document(&ctx, document_before);
toast::note_missing_fonts(self);
toast::show(self, &ctx);
dialogs::show(self, &ctx);
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
self.framework_dialogs.run(ui);
menus::palette(self, &ctx);
for url in std::mem::take(&mut self.pending_urls) {
ctx.open_url(egui::OpenUrl::new_tab(url));
+1 -2
View File
@@ -227,9 +227,8 @@ impl SlideApp {
}
"app.about" => self.dialog = Some(dialogs::Dialog::new("about")),
"app.checkUpdates" => {
// Nightly is updated by ArtCraft Launcher; its stable updater must stay idle.
#[cfg(not(target_arch = "wasm32"))]
updates_ui::request_check(self)?;
updates_ui::request_check(self);
#[cfg(target_arch = "wasm32")]
return Err("updates are handled by the browser: reload the page".into());
}
-125
View File
@@ -1,125 +0,0 @@
//! The document window (the slide canvas, the slide sorter or the notes page) as the window's one document canvas: its
//! widget, its Tab stop and when it takes the keyboard focus.
use craft_ui::runtime::overlay::{self, OpenFilter};
use super::{SlideApp, ViewMode};
use crate::framework::{document_id, focus_document, focused_widget, host_canvas};
/// How many passes the document asks for the focus: egui names the widget of a closed palette, dialog or menu as
/// focused for one pass after it was last drawn.
const ASKING_PASSES: u8 = 2;
/// What the document window's focus depends on from pass to pass.
#[derive(Default)]
pub(crate) struct DocumentFocus {
/// The presentation (its uid) whose document window the pass drew; `None` on the start screen, the File tab and in
/// a slide show.
pub(super) drawn: Option<u64>,
/// The passes left in which a presentation that opened or became active asks for the focus.
opened: u8,
/// The passes left in which the document asks for the focus after a dialog, menu or popup closed.
uncovered: u8,
}
impl SlideApp {
/// Draws the document window's widget over `rect` and declares it as the window's canvas. A press in it gives it
/// the focus, unless a dialog is open. Real presses only: with the document focused, egui makes Enter and Space
/// clicks of it.
pub(crate) fn document_widget(&mut self, ui: &egui::Ui, rect: egui::Rect, sense: egui::Sense) -> egui::Response {
let resp = ui.interact(rect, document_id(), sense);
self.document_focus.drawn = self.session.active().map(|d| d.uid);
host_canvas(ui.ctx(), self.document_keeps_tab(ui.ctx()));
if resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.any_pressed()) && !self.dialog_open(ui.ctx()) {
focus_document(ui.ctx());
}
resp
}
/// [`Self::document_widget`] behind widgets that take the presses (the slide sorter's thumbnails): a press on any of
/// them gives the document the focus, unless a text field has it.
pub(crate) fn document_behind(&mut self, ui: &egui::Ui, rect: egui::Rect) {
self.document_widget(ui, rect, egui::Sense::focusable_noninteractive());
let pressed = ui.input(|i| i.pointer.any_pressed()) && ui.rect_contains_pointer(rect);
if pressed && !ui.ctx().text_edit_focused() && !self.overlay_open(ui.ctx()) {
focus_document(ui.ctx());
}
}
/// Whether the document window is the slide being edited, where Tab can have work.
fn editing_slide(&self) -> bool {
self.backstage.is_none() && matches!(self.ui.view, ViewMode::Normal | ViewMode::Outline | ViewMode::Reading)
}
/// Whether the focused document keeps Tab: on the slide, while the session has something for it to do. A modal
/// dialog, a menu or a popup that is up gets it instead.
fn document_keeps_tab(&self, ctx: &egui::Context) -> bool {
self.editing_slide() && self.session.tab_has_work() && !self.overlay_open(ctx)
}
/// Whether a dialog, DeckCraft's or a modal one of the framework's, the palette or the opening overlay is up.
fn dialog_open(&self, ctx: &egui::Context) -> bool {
self.dialog.as_ref().is_some_and(|d| d.modal())
|| self.palette.is_some()
|| self.opening.is_some()
|| overlay::any_open(ctx, OpenFilter::Modal)
}
/// Whether a dialog ([`Self::dialog_open`]), or an egui menu or popup, is up.
fn overlay_open(&self, ctx: &egui::Context) -> bool {
self.dialog_open(ctx) || ctx.any_popup_open() || egui::Popup::is_any_open(ctx)
}
/// Whether the document may take the focus: no text field and no widget of another layer (the framework's update
/// notice) has it.
fn focus_is_free(ctx: &egui::Context) -> bool {
let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id);
!ctx.text_edit_focused() && focused_widget(ctx).is_none_or(|id| layer(id) == layer(document_id()))
}
/// Ends the document window's pass, after the views; `before` is the presentation the last pass drew. The pass's
/// input has changed what Tab has to do, so the document is declared again. A presentation that opened or became
/// active asks for the focus. So does the document with nothing focused, when a dialog, menu or popup has closed, and
/// while Tab has work on the slide (a ribbon field committed with Enter leaves nothing focused). All wait for the
/// last dialog, menu or popup to close.
pub(super) fn finish_document(&mut self, ctx: &egui::Context, before: Option<u64>) {
let drawn = self.document_focus.drawn;
if drawn.is_none() {
self.document_focus.opened = 0;
self.document_focus.uncovered = 0;
return;
}
let keeps_tab = self.document_keeps_tab(ctx);
host_canvas(ctx, keeps_tab);
if drawn != before {
self.document_focus.opened = ASKING_PASSES;
}
if self.overlay_open(ctx) {
self.document_focus.uncovered = ASKING_PASSES;
return;
}
let unfocused = ctx.memory(|m| m.focused().is_none());
let DocumentFocus { opened, uncovered, .. } = &mut self.document_focus;
if *opened == 0 && *uncovered == 0 && !(unfocused && keeps_tab) {
return;
}
if unfocused || (*opened > 0 && Self::focus_is_free(ctx)) {
(*opened, *uncovered) = (0, 0);
focus_document(ctx);
} else {
(*opened, *uncovered) = (opened.saturating_sub(1), uncovered.saturating_sub(1));
ctx.request_repaint();
}
}
/// While slide text is being edited, the text owns the keyboard (#93). The focus on an ordinary widget (the ribbon
/// button whose Space inserted the text box) would swallow every later key and end text entry, and with nothing
/// focused (a ribbon field committed with Enter) Tab would leave the text. The document takes the focus; a text
/// field or an open menu keeps its keys.
pub(super) fn edited_text_takes_focus(&self, ctx: &egui::Context) {
let editing = self.editing_slide() && self.session.active().is_some_and(|d| d.selection.text.is_some());
if editing && !ctx.memory(|m| m.has_focus(document_id())) && !self.overlay_open(ctx) && Self::focus_is_free(ctx) {
focus_document(ctx);
}
}
}
+1 -1
View File
@@ -145,7 +145,7 @@ impl SlideApp {
&& ctx.input(|i| i.viewport().focused.unwrap_or(true))
&& ctx.input(|i| i.viewport().visible() != Some(false))
&& !ctx.input(|i| i.viewport().close_requested())
&& !crate::framework::widget_has_keyboard(ctx)
&& ctx.memory(|m| m.focused().is_none())
&& self.dialog.as_ref().is_none_or(|d| !d.modal())
&& self.palette.is_none()
&& self.backstage.is_none()
+2 -2
View File
@@ -140,7 +140,7 @@ impl SlideApp {
return;
}
let current = self.input_target();
let focus = crate::framework::focused_widget(ctx);
let focus = ctx.memory(|m| m.focused());
if self.synthetic_target == Some(current) && focus == self.synthetic_focus {
return;
}
@@ -210,7 +210,7 @@ impl SlideApp {
Err(e) => self.set_status(e),
}
}
let focus = crate::framework::focused_widget(ctx);
let focus = ctx.memory(|m| m.focused());
if self.synthetic_pending {
let current = self.input_target();
if self.synthetic_target != Some(current) || focus != self.synthetic_focus {
+22 -9
View File
@@ -1,6 +1,5 @@
use super::clipboard::OBJECTS_MARKER;
use super::{Mods, SlideApp, Value, backstage, json, menus};
use crate::framework::widget_has_keyboard;
impl SlideApp {
/// The app shortcuts that still make sense on the empty File/start screen: create, open,
@@ -48,12 +47,9 @@ impl SlideApp {
}
}
/// Keyboard and clipboard for the slide (with nothing or the document window focused).
/// Keyboard and clipboard for the slide (when no text field has focus).
pub(super) fn keyboard(&mut self, ctx: &egui::Context) {
let mut events = ctx.input(|i| i.events.clone());
if crate::framework::window_escape(ctx) {
events.push(crate::framework::ESCAPE_PRESS);
}
let events = ctx.input(|i| i.events.clone());
// Ctrl+V with only an image on the clipboard: egui-winit sends no Paste event and swallows the
// key press, so the release of a V press never seen is the paste. Tracked even while a text
// field has focus, so that a V typed there is not taken for one.
@@ -80,15 +76,26 @@ impl SlideApp {
// File-tab navigation and document-free shortcuts remain available.
self.suspend_ime_reset(viewport);
self.route_ime_controls_only(ctx, &events);
if self.palette.is_none() && self.dialog.as_ref().is_none_or(|d| !d.modal()) && !widget_has_keyboard(ctx) {
if self.palette.is_none() && self.dialog.as_ref().is_none_or(|d| !d.modal()) && ctx.memory(|m| m.focused().is_none()) {
self.route_backstage_keys(events);
}
self.drain_requests();
return;
}
let modal = self.dialog.as_ref().is_some_and(|d| d.modal()) || self.palette.is_some();
self.edited_text_takes_focus(ctx);
if widget_has_keyboard(ctx) || modal {
// While slide text is being edited, the text owns the keyboard (#93). Tab and the arrow
// keys move egui's keyboard focus onto ordinary widgets (the window's drag handle, ribbon
// buttons), and that stray focus would swallow every later key and end text entry. Let it
// go; a real text field or an open menu keeps its keys.
if !modal
&& self.session.active().is_some_and(|d| d.selection.text.is_some())
&& !ctx.text_edit_focused()
&& !ctx.any_popup_open()
&& let Some(id) = ctx.memory(|m| m.focused())
{
ctx.memory_mut(|m| m.surrender_focus(id));
}
if ctx.memory(|m| m.focused().is_some()) || modal {
// A stock field/modal/palette owns input now. Retire the custom fence, then visit
// controls in raw order; stock text/key events are left for the stock widgets.
self.suspend_ime_reset(viewport);
@@ -170,6 +177,12 @@ impl SlideApp {
}
}
egui::Event::Key { key, pressed: true, modifiers, .. } => {
if key == egui::Key::Tab {
// The slide has the keyboard, so Tab is ours (indent, tab character, next
// shape). Left to egui it would also focus the first ribbon widget, and
// every key after it would go there instead of the slide (#78).
ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
}
if key == egui::Key::Escape && self.anim_preview.is_some() && !modifiers.command && !modifiers.ctrl && !modifiers.alt {
self.anim_preview = None;
continue;
+2 -2
View File
@@ -156,7 +156,7 @@ pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, out:
ui.add_space(14.0);
let current = SAVE_TYPES.iter().find(|s| s.0 == bs.file_type).map_or(SAVE_TYPES[0].1, |s| s.1);
ui.horizontal(|ui| {
egui::ComboBox::from_id_salt("backstage_save_type")
craft_ui::ComboBox::from_id_salt("backstage_save_type")
.width(340.0)
// Every type in view: at the default height the last ones were behind a scroll.
.height(f32::INFINITY)
@@ -234,7 +234,7 @@ pub(super) fn about(app: &mut SlideApp, ui: &mut Ui) {
ui.set_width(340.0);
heading(ui, "Appearance");
let dark = app.ui.brightness == theme::Brightness::Dark;
egui::ComboBox::from_id_salt("backstage_appearance")
craft_ui::ComboBox::from_id_salt("backstage_appearance")
.width(260.0)
.selected_text(if dark { "Dark" } else { "Light" })
.show_ui(ui, |ui| {
+5 -5
View File
@@ -96,7 +96,7 @@ pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
PrintScope::Current => "Print Current Slide",
PrintScope::Custom => "Custom Range",
};
let combo = egui::ComboBox::from_id_salt("backstage_print_scope").width(240.0).selected_text(scope).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("backstage_print_scope").width(240.0).selected_text(scope).show_ui(ui, |ui| {
for (s, label) in
[(PrintScope::All, "Print All Slides"), (PrintScope::Current, "Print Current Slide"), (PrintScope::Custom, "Custom Range")]
{
@@ -119,7 +119,7 @@ pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
});
ui.add_space(4.0);
let layout = LAYOUTS.iter().find(|l| l.0 == bs.print_layout).map_or("Full Page Slides", |l| l.1);
let combo = egui::ComboBox::from_id_salt("backstage_print_layout").width(240.0).selected_text(layout).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("backstage_print_layout").width(240.0).selected_text(layout).show_ui(ui, |ui| {
for (id, label) in LAYOUTS {
if ui.selectable_label(bs.print_layout == id, label).clicked() {
bs.print_layout = id;
@@ -133,7 +133,7 @@ pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
// for notes pages and handouts.
ui.add_enabled_ui(bs.print_layout != "slides", |ui| {
let paper = deckcraft_engine::cmd::file::PAPERS.iter().find(|p| p.0 == bs.print_paper).map_or("Letter", |p| p.1);
egui::ComboBox::from_id_salt("backstage_print_paper")
craft_ui::ComboBox::from_id_salt("backstage_print_paper")
.width(240.0)
.selected_text(paper)
.show_ui(ui, |ui| {
@@ -147,7 +147,7 @@ pub(super) fn print(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, "Paper size"));
ui.add_space(4.0);
let orient = if bs.print_landscape { "Landscape Orientation" } else { "Portrait Orientation" };
egui::ComboBox::from_id_salt("backstage_print_orientation")
craft_ui::ComboBox::from_id_salt("backstage_print_orientation")
.width(240.0)
.selected_text(orient)
.show_ui(ui, |ui| {
@@ -321,7 +321,7 @@ pub(super) fn export(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) {
ExportTask::Handouts => {
ui.label(RichText::new("Create Handouts").font(theme::font(16.0)).color(t.text));
bullets(ui, &["Several slides on each page of a PDF", "Three a page leaves lines for notes", "Print them for your audience"]);
let combo = egui::ComboBox::from_id_salt("backstage_handouts")
let combo = craft_ui::ComboBox::from_id_salt("backstage_handouts")
.width(240.0)
.selected_text(format!("{} slides per page", bs.handouts_per_page))
.show_ui(ui, |ui| {
+3 -3
View File
@@ -16,7 +16,7 @@ use crate::backstage::{Backstage, NAV_W, Nav, Page, PrintScope, entries, format_
use crate::{Services, SlideApp};
fn harness(app: SlideApp) -> Harness<'static, SlideApp> {
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -184,7 +184,7 @@ fn every_page_renders() {
/// In a window narrower than the page's maximum width the New tiles stay inside the right margin (#1421).
#[test]
fn new_tiles_keep_the_right_margin_in_a_narrow_window() {
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1000.0, 900.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1000.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -847,7 +847,7 @@ fn about_has_product_links_and_credits_without_account_controls() {
/// At the 900-point minimum window width the About columns stack and Appearance stays on the page.
#[test]
fn about_appearance_stays_on_the_page_at_minimum_width() {
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(900.0, 900.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(900.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+7 -11
View File
@@ -33,17 +33,13 @@ fn browse_button_applies_the_picked_files_theme() {
s.execute("slide.new", &json!({"layout": "title", "title": "Hello"})).unwrap();
let mut app = SlideApp::new(s, services);
app.ui.tab = "Design".into();
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1600.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.get_by_label("Browse for Themes…").click();
h.run_steps(3);
+3 -6
View File
@@ -112,11 +112,9 @@ fn wheel_navigation(app: &mut SlideApp, ui: &mut Ui, carry_id: egui::Id, doc_uid
}
fn empty_deck_prompt(app: &mut SlideApp, ui: &mut Ui, avail: Rect, t: &Tokens) {
ui.advance_cursor_after_rect(avail);
let resp = app.document_widget(ui, avail, Sense::click());
let resp = ui.allocate_rect(avail, Sense::click());
ui.painter().text(avail.center(), Align2::CENTER_CENTER, "Click to add first slide", theme::font(22.0), t.text_dim);
// Enter on the focused document is the session's New Slide, not a click of the prompt.
if resp.clicked_by(egui::PointerButton::Primary) || ui.input(|i| i.has_accesskit_action_request(resp.id, egui::accesskit::Action::Click)) {
if resp.clicked() {
let _ = app.run("slide.new", json!({"layout": "title"}));
}
}
@@ -174,8 +172,7 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) {
let last_id = scroll_id.with("last");
let mut offset: egui::Vec2 = ui.data_mut(|d| d.get_temp(scroll_id).unwrap_or_default());
let last: Option<(Rect, f32)> = ui.data_mut(|d| d.get_temp(last_id));
ui.advance_cursor_after_rect(avail);
let resp = app.document_widget(ui, avail, Sense::click_and_drag());
let resp = ui.allocate_rect(avail, Sense::click_and_drag());
let (wheel, zoom_delta, hover) = ui.input(|i| (i.smooth_scroll_delta, i.zoom_delta(), i.pointer.hover_pos()));
let zooming = resp.hovered() && (zoom_delta - 1.0).abs() > 1e-3;
if zooming {
+1 -3
View File
@@ -7,9 +7,7 @@ pub(super) fn context_menu(app: &mut SlideApp, resp: &egui::Response) {
{
app.session.tool.edit_vertex = Some((path, index));
}
// Real clicks only: with the canvas focused, egui's own context menu would close on Enter and Space.
let open = if resp.secondary_clicked() { Some(true) } else { resp.clicked_by(egui::PointerButton::Primary).then_some(false) };
egui::Popup::context_menu(resp).open_memory(open.map(egui::SetOpenCommand::Bool)).show(|ui| {
resp.context_menu(|ui| {
let editing = app.session.active().and_then(|d| app.session.tool.editing_points(d).and_then(|id| d.shape(id).cloned()));
if let Some(sh) = editing {
edit_points_menu(app, ui, &sh);
+7 -11
View File
@@ -14,17 +14,13 @@ fn turn_guides_on_drag_one_and_drop_it_off_the_slide() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
let app = SlideApp::new(s, Services::default());
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.state_mut().run("view.guides", json!({"on": true})).unwrap();
h.run_steps(2);
+1 -1
View File
@@ -34,7 +34,7 @@ pub fn ime_area(app: &SlideApp, xf: Xf) -> Option<Rect> {
/// has settled.
pub(super) fn ime_output(app: &mut SlideApp, ui: &Ui, xf: Xf) {
let ctx = ui.ctx();
if crate::framework::widget_has_keyboard(ctx) || app.dialog.as_ref().is_some_and(|d| d.modal()) || app.palette.is_some() || app.backstage_open() {
if ctx.memory(|m| m.focused().is_some()) || app.dialog.as_ref().is_some_and(|d| d.modal()) || app.palette.is_some() || app.backstage_open() {
return;
}
let Some(r) = ime_area(app, xf) else { return };
+14 -22
View File
@@ -42,17 +42,13 @@ fn drag_indents_add_move_and_remove_tabs_on_the_ruler() {
s.execute("text.insert", &json!({"text": "Name\tRole\tTeam"})).unwrap();
let mut app = SlideApp::new(s, Services::default());
app.ui.ruler = true;
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale);
let x0 = ruler(&mut h)["x"].as_f64().unwrap() as f32;
@@ -97,17 +93,13 @@ fn editing_harness() -> Harness<'static, SlideApp> {
s.execute("text.insert", &json!({"text": "Item\t9.50"})).unwrap();
let mut app = SlideApp::new(s, Services::default());
app.ui.ruler = true;
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
+8 -9
View File
@@ -95,7 +95,7 @@ fn a_placeholder_that_inherits_its_box_has_a_resize_cursor() {
}
fn harness() -> Harness<'static, SlideApp> {
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -315,14 +315,13 @@ fn app_with_table() -> (egui_kittest::Harness<'static, SlideApp>, deckcraft_mode
let r = s.execute("insert.table", &json!({"rows": 2, "cols": 2, "rect": [100.0, 100.0, 400.0, 80.0], "data": data})).unwrap();
let id = deckcraft_model::ShapeId(r["id"].as_u64().unwrap() as u32);
s.execute("edit.deselect", &json!({})).unwrap();
let mut harness =
egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(s, Services::default()),
);
let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(s, Services::default()),
);
// The app keeps requesting repaints, so step frames instead of run().
harness.run_steps(2);
(harness, id)
+7 -11
View File
@@ -22,17 +22,13 @@ fn harness() -> (Harness<'static, SlideApp>, usize) {
s.set_active(0);
s.execute("review.compare", &json!({"name": "Q3 review.deckcraft", "data": rev})).unwrap();
let app = SlideApp::new(s, Services::default());
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
(h, n)
}
+1 -1
View File
@@ -12,7 +12,7 @@ use crate::{Services, SlideApp};
fn harness() -> Harness<'static, SlideApp> {
let mut app = SlideApp::new(Session::with_new(), Services::default());
app.ui.tab = "Insert".into();
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1800.0, 1100.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1800.0, 1100.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+2 -2
View File
@@ -109,7 +109,7 @@ pub fn show(app: &mut SlideApp, ctx: &egui::Context) {
}
close = body(app, ui, &mut d);
});
let escape = crate::framework::escape_pressed(ctx);
let escape = ctx.input(|i| i.key_pressed(egui::Key::Escape));
if open && !close && !escape {
app.dialog = Some(d);
} else if !close && d.id == "preferences" {
@@ -262,7 +262,7 @@ fn color_label(v: &Value) -> String {
fn choice(ui: &mut Ui, d: &mut Dialog, salt: &str, name: &str, key: &str, choices: &[(&str, &str)]) {
let cur = d.get(key, "");
let label = choices.iter().find(|(v, _)| *v == cur).map(|(_, l)| *l).unwrap_or(cur.as_str());
let combo = egui::ComboBox::from_id_salt(salt).selected_text(label).width(140.0).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt(salt).selected_text(label).width(140.0).show_ui(ui, |ui| {
for (v, l) in choices {
if ui.selectable_label(cur == *v, *l).clicked() {
d.fields.insert((*key).into(), (*v).into());
+9 -13
View File
@@ -20,7 +20,7 @@ pub fn about(_app: &mut SlideApp, ui: &mut Ui) {
ui.vertical_centered(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(64.0, 64.0), Sense::hover());
paint_logo(ui.painter(), r);
ui.label(egui::RichText::new(crate::flavor::app_name()).font(theme::bold(22.0)));
ui.label(egui::RichText::new("DeckCraft").font(theme::bold(22.0)));
ui.label(egui::RichText::new(version_line()).color(t.text_dim));
ui.add_space(6.0);
ui.label("Presentations and slide shows, rebuilt from scratch in pure Rust.");
@@ -38,7 +38,7 @@ pub fn about(_app: &mut SlideApp, ui: &mut Ui) {
/// from `[workspace.package] version` (the single source of truth, `cargo xtask version`); the
/// release workflow sets `DECKCRAFT_BUILD_SHA` / `DECKCRAFT_BUILD_DATE` at build time.
pub fn version_line() -> String {
let mut s = format!("Version {}", crate::flavor::version());
let mut s = format!("Version {}", env!("CARGO_PKG_VERSION"));
let sha = option_env!("DECKCRAFT_BUILD_SHA").map(|s| s.get(..9).unwrap_or(s)).filter(|s| !s.is_empty());
let date = option_env!("DECKCRAFT_BUILD_DATE").filter(|s| !s.is_empty());
match (sha, date) {
@@ -85,17 +85,13 @@ mod about_credits_tests {
fn about_dialog_tabs_keep_responding() {
let mut app = SlideApp::new(deckcraft_engine::Session::with_new(), Services::default());
app.dialog = Some(Dialog::new("about"));
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1440.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
assert_eq!(tab_of(&h), "about");
for label in ["Contributors", "Models", "About", "Models", "Contributors"] {
+7 -7
View File
@@ -101,7 +101,7 @@ fn dlg_slide_size(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
}
let label = ui.label("Slides sized for:");
let preset = d.get("preset", "");
let combo = egui::ComboBox::from_id_salt("sizes").selected_text(if preset.is_empty() { "Custom" } else { &preset }).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("sizes").selected_text(if preset.is_empty() { "Custom" } else { &preset }).show_ui(ui, |ui| {
for (label, w, h) in deckcraft_model::defaults::SLIDE_SIZES {
if ui.selectable_label(preset == *label, *label).clicked() {
d.fields.insert("preset".into(), label.to_string());
@@ -149,7 +149,7 @@ fn dlg_header_footer(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ui.add_enabled_ui(date && automatic, |ui| {
ui.horizontal(|ui| {
ui.label(" Format:");
egui::ComboBox::from_id_salt("hf-date-format").selected_text(label).width(200.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("hf-date-format").selected_text(label).width(200.0).show_ui(ui, |ui| {
for (kind, sample) in &rows {
if ui.selectable_label(fmt == *kind, sample).clicked() {
d.fields.insert("dateFormat".into(), (*kind).to_string());
@@ -264,7 +264,7 @@ fn dlg_setup_show(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
let chosen = d.fields.entry("custom".into()).or_insert_with(|| sh.custom_show.clone().unwrap_or_default()).clone();
let field = ui.label("Slides");
let label = if chosen.is_empty() { "All slides".to_string() } else { chosen.clone() };
let combo = egui::ComboBox::from_id_salt("setup_custom").selected_text(label).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("setup_custom").selected_text(label).show_ui(ui, |ui| {
if ui.selectable_label(chosen.is_empty(), "All slides").clicked() {
d.fields.insert("custom".into(), String::new());
}
@@ -428,7 +428,7 @@ fn dlg_bullets(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
let color = d.get("color", "");
ui.horizontal(|ui| {
let field = ui.add_sized(vec2(120.0, 20.0), egui::Label::new("Color:"));
let combo = egui::ComboBox::from_id_salt("bullet-color")
let combo = craft_ui::ComboBox::from_id_salt("bullet-color")
.selected_text(colors.iter().find(|c| c.0 == color).map_or("Automatic", |c| c.1))
.show_ui(ui, |ui| {
for (k, l) in colors {
@@ -535,7 +535,7 @@ fn dlg_action(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
];
let shown = targets.iter().find(|t| t.0 == kind).map_or("Next Slide", |t| t.1);
ui.add_enabled_ui(hyperlink, |ui| {
let combo = egui::ComboBox::from_id_salt("action-target").selected_text(shown).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("action-target").selected_text(shown).show_ui(ui, |ui| {
for (k, l) in targets {
if ui.selectable_label(kind == k, l).clicked() {
d.fields.insert("kind".into(), k.into());
@@ -733,7 +733,7 @@ fn dlg_export(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ui.add_space(4.0);
ui.horizontal(|ui| {
let field = ui.label("Print layout:");
let combo = egui::ComboBox::from_id_salt("pdf_layout")
let combo = craft_ui::ComboBox::from_id_salt("pdf_layout")
.selected_text(match pdf_layout.as_str() {
"notes" => "Notes Pages",
"h1" => "Handouts (1 slide per page)",
@@ -818,7 +818,7 @@ fn dlg_replace_fonts(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
let mut to = d.get("to", "");
egui::Grid::new("replace_fonts").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
let field = ui.label("Replace:");
let combo = egui::ComboBox::from_id_salt("rf_from").width(240.0).selected_text(from.clone()).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("rf_from").width(240.0).selected_text(from.clone()).show_ui(ui, |ui| {
for f in &used {
ui.selectable_value(&mut from, f.clone(), f);
}
@@ -31,17 +31,13 @@ fn two_boxes() -> Harness<'static, SlideApp> {
fn harness_of(s: Session) -> Harness<'static, SlideApp> {
let app = SlideApp::new(s, Services::default());
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1440.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
+1 -1
View File
@@ -223,7 +223,7 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
}
ui.separator();
let field = ui.label("Sort");
let combo = egui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
for k in SortKey::ALL {
if ui.selectable_label(v.key == k, k.label().0).clicked() {
v.key = k;
+1 -1
View File
@@ -49,7 +49,7 @@ pub(super) fn date_time_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog)
let lang_label = DATE_LANGS.iter().find(|(k, _)| *k == lang).map(|(_, l)| *l).unwrap_or("English (United States)");
ui.horizontal(|ui| {
ui.label("Language:");
let opened = egui::ComboBox::from_id_salt("date-lang").selected_text(lang_label).width(240.0).show_ui(ui, |ui| {
let opened = craft_ui::ComboBox::from_id_salt("date-lang").selected_text(lang_label).width(240.0).show_ui(ui, |ui| {
for (k, l) in DATE_LANGS {
if ui.selectable_label(lang == *k, *l).clicked() {
d.fields.insert("language".into(), (*k).to_string());
+1 -1
View File
@@ -16,7 +16,7 @@ pub(super) fn gif_options(app: &SlideApp, ui: &mut Ui, d: &mut Dialog) -> Result
ui.add_space(4.0);
ui.horizontal(|ui| {
let field = ui.add_sized(vec2(120.0, 20.0), egui::Label::new("Size:"));
let combo = egui::ComboBox::from_id_salt("gif_size").selected_text(size_label(&size)).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("gif_size").selected_text(size_label(&size)).show_ui(ui, |ui| {
for k in SIZE_PRESETS.iter().map(|(k, _)| *k).chain(["custom"]) {
if ui.selectable_label(size == k, size_label(k)).clicked() {
d.fields.insert("gifSize".into(), k.into());
+2 -2
View File
@@ -26,7 +26,7 @@ pub(super) fn font_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bo
}
ui.horizontal(|ui| {
let field = ui.add_sized(vec2(88.0, 20.0), egui::Label::new("Font"));
let combo = egui::ComboBox::from_id_salt("font_dialog_family")
let combo = craft_ui::ComboBox::from_id_salt("font_dialog_family")
.selected_text(if family.is_empty() { " " } else { family.as_str() })
.width(300.0)
.show_ui(ui, |ui| {
@@ -75,7 +75,7 @@ pub(super) fn font_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bo
let mut spacing = d.get("spacing", "0");
let edited = ui.add(egui::TextEdit::singleline(&mut spacing).desired_width(64.0).hint_text("pt"));
let mut picked = None;
let combo = egui::ComboBox::from_id_salt("font_dialog_spacing")
let combo = craft_ui::ComboBox::from_id_salt("font_dialog_spacing")
.selected_text(match spacing.as_str() {
"-3" => "Very tight",
"-1.5" => "Tight",
@@ -13,17 +13,13 @@ fn harness() -> Harness<'static, SlideApp> {
// A selected shape, not a caret: the dialog then formats the text that is already there.
let _ = s.execute("text.exit", &json!({}));
let app = SlideApp::new(s, Services::default());
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1440.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
+13 -12
View File
@@ -103,19 +103,20 @@ pub(super) fn paragraph_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog)
let field = ui.add_sized(vec2(110.0, 20.0), egui::Label::new("Line spacing"));
let kind = d.get("lineKind", "multiple");
let value = d.get("lineValue", "1");
let combo = egui::ComboBox::from_id_salt("paragraph_line").selected_text(line_preset_label(&kind, &value)).width(140.0).show_ui(ui, |ui| {
for (label, k, v) in [
("Single", "multiple", Some("1")),
("1.5 lines", "multiple", Some("1.5")),
("Double", "multiple", Some("2")),
("Multiple", "multiple", None),
("Exactly", "exactly", None),
] {
if ui.selectable_label(line_preset_label(&kind, &value) == label, label).clicked() {
picked = Some((k, v));
let combo =
craft_ui::ComboBox::from_id_salt("paragraph_line").selected_text(line_preset_label(&kind, &value)).width(140.0).show_ui(ui, |ui| {
for (label, k, v) in [
("Single", "multiple", Some("1")),
("1.5 lines", "multiple", Some("1.5")),
("Double", "multiple", Some("2")),
("Multiple", "multiple", None),
("Exactly", "exactly", None),
] {
if ui.selectable_label(line_preset_label(&kind, &value) == label, label).clicked() {
picked = Some((k, v));
}
}
}
});
});
let _ = combo.response.labelled_by(field.id);
ui.add_space(8.0);
let _ = labeled_text(ui, d, "At", "lineValue", 64.0);
@@ -13,17 +13,13 @@ fn harness() -> Harness<'static, SlideApp> {
s.execute("shape.insert", &json!({"preset": "rect", "rect": [80.0, 80.0, 320.0, 80.0], "text": "Hello"})).unwrap();
let _ = s.execute("text.exit", &json!({}));
let app = SlideApp::new(s, Services::default());
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1440.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
+1 -1
View File
@@ -69,7 +69,7 @@ fn pick_album_picture(app: &mut SlideApp) -> Option<Value> {
fn album_choice(ui: &mut Ui, d: &mut Dialog, id: &str, name: &str, key: &str, default: &str, choices: &[(&str, &str)]) {
let cur = d.get(key, default);
let label = choices.iter().find(|(k, _)| *k == cur).map(|(_, l)| *l).unwrap_or(default);
let opened = egui::ComboBox::from_id_salt(id).selected_text(label).width(220.0).show_ui(ui, |ui| {
let opened = craft_ui::ComboBox::from_id_salt(id).selected_text(label).width(220.0).show_ui(ui, |ui| {
for (k, l) in choices {
if ui.selectable_label(cur == *k, *l).clicked() {
d.fields.insert(key.into(), (*k).to_string());
@@ -18,17 +18,13 @@ fn png() -> Vec<u8> {
}
fn harness(app: SlideApp) -> Harness<'static, SlideApp> {
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1600.0, 1200.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
@@ -18,7 +18,7 @@ fn interface_size<'a>(h: &'a Harness<'_, SlideApp>) -> Node<'a> {
}
fn harness() -> Harness<'static, SlideApp> {
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -7,7 +7,7 @@ use serde_json::json;
use crate::{Services, SlideApp};
fn harness() -> Harness<'static, SlideApp> {
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1600.0, 900.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+4 -4
View File
@@ -17,7 +17,7 @@ fn spelling_dialog_changes_and_ignores_words() {
let mut app = SlideApp::new(Session::with_new(), Services::default());
app.session.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 500, 120], "text": "Our plna for teh quarter"})).unwrap();
app.dialog = Some(crate::dialogs::Dialog::new("spelling"));
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1100.0, 700.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1100.0, 700.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -82,7 +82,7 @@ fn squiggles_mark_misspelt_words_in_the_background() {
let st = app.session.active().unwrap().clone();
let lines = app.squiggles.settle(&st);
assert_eq!(lines.len(), 3, "{lines:?}");
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1100.0, 700.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1100.0, 700.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -153,7 +153,7 @@ fn squiggles_in_table_cells_and_notes_and_on_the_ui_thread() {
// Each under its own cell: the first in the top-left one, the second in the bottom-right one.
assert!(lines[0].0.x < 380.0 && lines[0].0.y < 160.0 && lines[1].0.x > 380.0 && lines[1].0.y > 160.0, "{lines:?}");
assert_eq!(app.squiggles.settle_notes("Remmeber to show the totl", "xx-TB"), vec![(0, 8), (21, 25)]);
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1100.0, 760.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -226,7 +226,7 @@ fn notes_menu_language_dialog_and_repeated_words() {
let st = app.session.active().unwrap().clone();
// "is is" is flagged as repeated, "wrok" as misspelt.
assert_eq!(app.squiggles.settle(&st).len(), 2);
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1100.0, 760.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+21 -24
View File
@@ -48,14 +48,13 @@ fn header_footer_apply_keeps_an_existing_date_format() {
})
.collect()
};
let mut harness =
egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(session, crate::Services::default()),
);
let mut harness = egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(session, crate::Services::default()),
);
harness.run_steps(2);
assert_eq!(date_fields(harness.state()), vec!["datetime4".to_string()]);
harness.state_mut().run("app.dialog", json!({"id": "headerFooter"})).unwrap();
@@ -90,14 +89,13 @@ fn export_dialog_writes_an_animated_gif() {
};
let mut session = deckcraft_engine::Session::with_new();
session.execute("slide.new", &json!({})).unwrap();
let mut harness =
egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(session, services),
);
let mut harness = egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(session, services),
);
harness.run_steps(2);
harness.state_mut().run("app.exportDialog", json!({})).unwrap();
harness.run_steps(2);
@@ -142,14 +140,13 @@ fn export_dialog_writes_a_png_with_a_transparent_background() {
let path = dir.join("slide.png");
let picked = path.to_string_lossy().to_string();
let services = crate::Services { pick_save: Some(Box::new(move |_: &str| Some(picked.clone()))), ..Default::default() };
let mut harness =
egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(deckcraft_engine::Session::with_new(), services),
);
let mut harness = egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(deckcraft_engine::Session::with_new(), services),
);
harness.run_steps(2);
harness.state_mut().run("app.exportDialog", json!({})).unwrap();
harness.run_steps(2);
@@ -10,7 +10,7 @@ use crate::{Services, SlideApp};
fn harness() -> Harness<'static, SlideApp> {
let mut app = SlideApp::new(Session::with_new(), Services::default());
app.ui.tab = "Design".into();
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1800.0, 1100.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1800.0, 1100.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+1 -1
View File
@@ -30,7 +30,7 @@ fn theme_font_choices(app: &SlideApp, selected: &str) -> Vec<String> {
/// Draw an accessible font combo box and update the selected family; the caller supplies the
/// visible label.
fn font_combo(ui: &mut Ui, label: &str, choices: &[String], selected: &mut String) {
let resp = egui::ComboBox::from_id_salt(label).selected_text(selected.as_str()).width(240.0).show_ui(ui, |ui| {
let resp = craft_ui::ComboBox::from_id_salt(label).selected_text(selected.as_str()).width(240.0).show_ui(ui, |ui| {
for face in choices {
if ui.selectable_label(selected == face, face).clicked() {
*selected = face.clone();
@@ -9,7 +9,7 @@ use crate::{Services, SlideApp};
fn harness() -> Harness<'static, SlideApp> {
let mut app = SlideApp::new(Session::with_new(), Services::default());
app.ui.tab = "Design".into();
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1800.0, 1100.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1800.0, 1100.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+28 -120
View File
@@ -1,38 +1,23 @@
//! One background check at start-up (and on demand from Help) for a newer release, the modal
//! prompt that offers to update and restart, and the result of a check, as craft-update's dialogs
//! on the app's [`DialogHost`](craft_ui::dialog::DialogHost). The flow itself is
//! `craft_update::updater::Updater`.
//! One background check at start-up (and on demand from Help) for a newer release, and the modal
//! prompt that offers to update and restart. The flow itself is `craft_update::updater::Updater`.
use craft_ui::dialog::DialogResult;
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
use craft_update::updater::{Action, Status, Updater};
use craft_update::{CheckResultDialog, CheckResultResponse};
use crate::SlideApp;
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// What Help > Check for Updates… answers in Nightly, which ArtCraft Launcher updates.
pub(crate) const NIGHTLY_UPDATES: &str = "DeckCraft Nightly is updated by ArtCraft Launcher";
pub(crate) struct Runtime {
updater: Updater,
/// The desktop host turns the check at start on; tests and the web build leave it off.
enabled: bool,
check_requested: bool,
/// The stable self-updater (its feed, cache and records under Stable's folders) is a stable
/// service only. The launch identity is read once, when the UI state is built, so every entry
/// point below agrees and no test can reselect the process-wide identity.
stable_services: bool,
}
impl Default for Runtime {
fn default() -> Self {
Self {
updater: Updater::new(&crate::UPDATE_APP, VERSION),
enabled: false,
check_requested: false,
stable_services: crate::os_window::stable_services_allowed(),
}
Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false }
}
}
@@ -40,88 +25,55 @@ pub(crate) fn enable(app: &mut SlideApp) {
app.updates_rt.enabled = true;
}
/// Help > Check for Updates…: runs a check and reports the outcome either way. Nightly has no
/// update check of its own (the Launcher owns the install) and never touches Stable's updater.
pub(crate) fn request_check(app: &mut SlideApp) -> Result<(), String> {
if !app.updates_rt.stable_services {
return Err(NIGHTLY_UPDATES.into());
}
/// Help > Check for Updates…: runs a check and reports the outcome either way.
pub(crate) fn request_check(app: &mut SlideApp) {
if !matches!(app.updates_rt.updater.status(), Status::Checking) {
app.updates_rt.check_requested = true;
}
Ok(())
}
/// Starts the helper of an update that is ready, so that it installs once the process has exited.
/// Later calls do nothing; Nightly has no ready stable update to start.
/// Later calls do nothing.
pub(crate) fn start_pending_update(app: &mut SlideApp) {
if app.updates_rt.stable_services {
app.updates_rt.updater.start_pending_update();
}
app.updates_rt.updater.start_pending_update();
}
pub(crate) fn tick(app: &mut SlideApp, ctx: &egui::Context) {
let rt = &mut app.updates_rt;
if !rt.stable_services {
return;
}
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now();
rt.updater.check_now(ctx);
} else if rt.enabled {
rt.updater.check_at_start();
rt.updater.check_at_start(ctx);
}
rt.updater.tick(ctx);
}
/// One pass of the update flow, before the dialog host runs (`SlideApp::ui`): answers the result
/// dialog closed in the last pass, drives the startup prompt, and keeps the result dialog open and
/// current while the updater has something to report.
pub(crate) fn show(app: &mut SlideApp, ctx: &egui::Context) {
if !app.updates_rt.stable_services {
return;
}
// An installation starts, and a ready update asks the app to close, only while nothing is unsaved.
let clean = !app.session.documents().iter().any(|d| d.is_dirty());
// Answered before the dialog is kept open below, so a dismissed result does not open again.
if let Some(result) = app.framework_dialogs.take::<UpdateCheckDialog>() {
answer(&mut app.updates_rt, ctx, result, clean);
}
match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) {
match app.updates_rt.updater.show_if(ctx, clean) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
// The app's close path asks about unsaved work; `on_exit` starts the restart helper.
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
_ => {}
Action::None => {}
}
// The result dialog reports a requested check, and at the first start after an update what
// The result window reports a requested check, and at the first start after an update what
// that update came to (installed, or why it failed).
let updater = &app.updates_rt.updater;
let reports = !matches!(updater.status(), Status::Idle);
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
let open = app.framework_dialogs.is_open::<UpdateCheckDialog>();
if reports && !open {
app.framework_dialogs.open(UpdateCheckDialog::new(VERSION));
} else if !reports && open {
app.framework_dialogs.cancel::<UpdateCheckDialog>(ctx);
}
if let Some(dialog) = app.framework_dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
let rt = &mut app.updates_rt;
if !matches!(rt.updater.status(), Status::Idle) {
let response = CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status());
answer(rt, response);
}
}
/// Acts on the result dialog's answer.
fn answer(rt: &mut Runtime, ctx: &egui::Context, result: DialogResult<CheckChoice>, clean: bool) {
match result {
DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain) => rt.check_requested = true,
// The next pass's `run` asks the window to close once nothing is unsaved.
DialogResult::Ok(CheckChoice::RestartToUpdate) => rt.updater.restart_to_update(),
DialogResult::Ok(CheckChoice::Update) => {
rt.updater.request_install(clean);
}
DialogResult::Ok(CheckChoice::Download) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())),
// OK, Esc and the close box dismiss the outcome it showed.
_ => rt.updater.dismiss_status(),
/// Acts on the result window's answer.
fn answer(rt: &mut Runtime, response: CheckResultResponse) {
match response {
CheckResultResponse::Close => rt.updater.dismiss_status(),
CheckResultResponse::CheckAgain => rt.check_requested = true,
// The next frame's `show_if` asks the window to close once nothing is unsaved.
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
CheckResultResponse::None => {}
}
}
@@ -133,22 +85,9 @@ mod tests {
fn an_offered_release_opens_the_prompt() {
let mut app = SlideApp::new(deckcraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
assert!(!app.updates_rt.updater.prompt_open());
app.updates_rt.updater.offer(craft_update::Release { tag: "v99.0.0".into(), ..Default::default() });
// The offer reads on a thread whether this copy can install the release itself; a later
// pass's tick opens the prompt.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while !app.updates_rt.updater.prompt_open() && std::time::Instant::now() < deadline {
ctx.run_ui(egui::RawInput::default(), |ui| {
tick(&mut app, ui.ctx());
show(&mut app, ui.ctx());
app.framework_dialogs.run(ui);
})
.textures_delta
.clear();
std::thread::sleep(std::time::Duration::from_millis(2));
}
ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui.ctx())).textures_delta.clear();
assert!(app.updates_rt.updater.prompt_open());
}
@@ -164,33 +103,6 @@ mod tests {
app
}
/// Nightly is updated by ArtCraft Launcher: the stable feed, its cache and its records (all
/// under Stable's folders) stay untouched, and Help > Check for Updates… says so.
#[test]
fn a_nightly_launch_never_starts_the_stable_updater() {
let mut app = SlideApp::new(deckcraft_engine::Session::new(), crate::Services::default());
assert!(app.updates_rt.stable_services, "the test binary is a stable launch");
app.updates_rt.stable_services = false;
assert_eq!(request_check(&mut app), Err(NIGHTLY_UPDATES.to_string()));
assert!(!app.updates_rt.check_requested, "a refused check must not be queued");
start_pending_update(&mut app);
let ctx = egui::Context::default();
ctx.run_ui(egui::RawInput::default(), |ui| {
tick(&mut app, ui.ctx());
show(&mut app, ui.ctx());
})
.textures_delta
.clear();
assert_eq!(app.updates_rt.updater.status(), &Status::Idle, "Nightly never drives the updater");
}
/// The identity is sampled when the UI state is built, so the answer cannot drift later.
#[test]
fn the_updater_reads_the_launch_identity_once() {
assert_eq!(Runtime::default().stable_services, crate::os_window::stable_services_allowed());
assert_eq!(crate::os_window::identity(), crate::os_window::LaunchIdentity::Stable);
}
fn records_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("deckcraft-updates-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -205,16 +117,14 @@ mod tests {
std::fs::write(root.join("data").join("self-update-done.txt"), VERSION).unwrap();
let mut app = app_with_records(&root);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| {
tick(&mut app, ui.ctx());
show(&mut app, ui.ctx());
app.framework_dialogs.run(ui);
})
.textures_delta
.clear();
assert!(matches!(app.updates_rt.updater.status(), Status::Updated(_)), "{:?}", app.updates_rt.updater.status());
answer(&mut app.updates_rt, &ctx, DialogResult::Ok(CheckChoice::Close), true);
answer(&mut app.updates_rt, CheckResultResponse::Close);
assert_eq!(app.updates_rt.updater.status(), &Status::Idle);
let _ = std::fs::remove_dir_all(&root);
}
@@ -227,16 +137,14 @@ mod tests {
std::fs::write(root.join("data").join("logs").join("self-update-error.txt"), "the disk is full").unwrap();
let mut app = app_with_records(&root);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| {
tick(&mut app, ui.ctx());
show(&mut app, ui.ctx());
app.framework_dialogs.run(ui);
})
.textures_delta
.clear();
assert_eq!(app.updates_rt.updater.status(), &Status::InstallFailed("the disk is full".into()));
answer(&mut app.updates_rt, &ctx, DialogResult::Ok(CheckChoice::CheckAgain), true);
answer(&mut app.updates_rt, CheckResultResponse::CheckAgain);
assert!(app.updates_rt.check_requested);
let _ = std::fs::remove_dir_all(&root);
}
-232
View File
@@ -1,232 +0,0 @@
//! The document window as the window's one canvas stop: Tab, real presses and its keys.
use deckcraft_engine::Session;
use egui::{Event, Id, Key, Modifiers, PointerButton, Role, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable as _;
use serde_json::json;
use crate::framework::document_id;
use crate::state::ViewMode;
use crate::{Services, SlideApp};
fn harness() -> Harness<'static, SlideApp> {
let mut session = Session::with_new();
session.prefs.autocorrect = false;
let mut app = SlideApp::new(session, Services::default());
app.ui.notes = false;
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
fn focused(h: &Harness<'_, SlideApp>) -> Option<Id> {
h.ctx.memory(|m| m.focused())
}
fn press(h: &mut Harness<'_, SlideApp>, modifiers: Modifiers, key: Key) {
h.key_press_modifiers(modifiers, key);
h.run_steps(2);
}
fn tab(h: &mut Harness<'_, SlideApp>) {
press(h, Modifiers::NONE, Key::Tab);
}
fn selected(h: &Harness<'_, SlideApp>) -> Vec<deckcraft_model::ShapeId> {
h.state().session.active().unwrap().selection.shapes.clone()
}
#[test]
fn tab_selects_the_slides_objects_then_moves_on_and_shift_tab_walks_back() {
let mut h = harness();
assert_eq!(focused(&h), Some(document_id()), "an opened presentation has the keyboard");
let objects: Vec<_> = h.state().session.active().unwrap().shapes().iter().map(|s| s.id).collect();
assert!(objects.len() > 1);
for object in &objects {
tab(&mut h);
assert_eq!((selected(&h), focused(&h)), (vec![*object], Some(document_id())));
}
press(&mut h, Modifiers::SHIFT, Key::Tab);
let before = focused(&h);
assert!(before.is_some() && before != Some(document_id()), "with the last object selected, Shift+Tab leaves the slide");
tab(&mut h);
assert_eq!(focused(&h), Some(document_id()), "Tab from the stop before it stops at the slide");
tab(&mut h);
let after = focused(&h);
assert!(after.is_some() && after != Some(document_id()) && after != before, "past the last object, Tab moves on");
press(&mut h, Modifiers::SHIFT, Key::Tab);
assert_eq!(focused(&h), Some(document_id()), "Shift+Tab walks back to the slide");
assert_eq!(selected(&h), objects[objects.len() - 1..]);
}
#[test]
fn a_press_on_the_slide_takes_the_keyboard_from_a_focused_button() {
let mut h = harness();
h.get_by_role_and_label(Role::Button, "File").focus();
h.run_steps(2);
assert!(h.get_by_role_and_label(Role::Button, "File").is_focused());
let pos = h.state().canvas_rect.unwrap().right_bottom() - vec2(10.0, 10.0);
h.hover_at(pos);
h.run_steps(1);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(1);
}
assert_eq!(focused(&h), Some(document_id()));
press(&mut h, Modifiers::NONE, Key::Enter);
assert!(!h.state().backstage_open(), "the File button isn't activated");
assert_eq!(h.state().session.active().unwrap().doc.slides.len(), 2, "Enter adds a slide");
}
#[test]
fn after_a_press_on_a_pane_tab_selects_the_next_object() {
let mut h = harness();
let pos = egui::pos2(h.state().ui.thumbs_width / 2.0, 300.0);
h.hover_at(pos);
h.run_steps(1);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
assert!(h.state().slides_focused, "the press is in the thumbnail pane");
let first = h.state().session.active().unwrap().shapes()[0].id;
tab(&mut h);
assert_eq!((selected(&h), focused(&h)), (vec![first], Some(document_id())));
}
#[test]
fn after_a_dialog_closes_tab_selects_the_next_object() {
let mut h = harness();
h.state_mut().dialog = Some(crate::dialogs::Dialog::new("find"));
h.run_steps(3);
assert!(h.ctx.text_edit_focused(), "the dialog's field has the focus");
h.state_mut().dialog = None;
h.run_steps(4);
let first = h.state().session.active().unwrap().shapes()[0].id;
tab(&mut h);
assert_eq!((selected(&h), focused(&h)), (vec![first], Some(document_id())));
}
#[test]
fn after_enter_in_a_ribbon_field_tab_selects_the_next_object() {
let mut h = harness();
h.state_mut().ui.tab = "Transitions".into();
tab(&mut h);
let objects: Vec<_> = h.state().session.active().unwrap().shapes().iter().map(|s| s.id).collect();
assert_eq!(selected(&h), objects[..1]);
h.get_by_role_and_label(Role::TextInput, "Duration value").focus();
h.run_steps(2);
assert!(h.ctx.text_edit_focused());
press(&mut h, Modifiers::NONE, Key::Enter);
assert!(!h.ctx.text_edit_focused(), "Enter commits the field");
assert!(h.state().session.active().unwrap().selection.text.is_none(), "and reaches nothing on the slide");
tab(&mut h);
assert_eq!((selected(&h), focused(&h)), (vec![objects[1]], Some(document_id())));
}
#[test]
fn a_press_in_the_sorter_takes_the_keyboard_from_a_focused_button() {
let mut h = harness();
h.state_mut().ui.view = ViewMode::Sorter;
h.run_steps(3);
h.get_by_role_and_label(Role::Button, "File").focus();
h.run_steps(2);
assert_ne!(focused(&h), Some(document_id()));
let pos = h.get_by_role_and_label(Role::Button, "Slide 1").rect().center();
h.hover_at(pos);
h.run_steps(1);
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(2);
assert_eq!(focused(&h), Some(document_id()));
}
#[test]
fn edited_text_traps_no_focus_in_the_sorter_or_the_file_tab() {
let mut h = harness();
let title = h.state().session.active().unwrap().shapes()[0].id.0;
h.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
h.run_steps(2);
h.state_mut().ui.view = ViewMode::Sorter;
h.run_steps(2);
tab(&mut h);
let stop = focused(&h);
assert!(stop.is_some_and(|id| id != document_id()), "Tab moves on from the sorter");
tab(&mut h);
assert!(focused(&h).is_some_and(|id| Some(id) != stop && id != document_id()), "and on again");
h.state_mut().open_backstage(crate::backstage::Page::Home);
h.run_steps(3);
tab(&mut h);
h.run_steps(2);
assert!(h.state().session.active().unwrap().selection.text.is_some());
assert!(focused(&h).is_some(), "Tab stays on a control of the File tab");
}
#[test]
fn a_presentation_opened_from_the_palette_gets_the_keyboard() {
let mut h = harness();
h.state_mut().run("app.palette", json!({})).unwrap();
h.run_steps(3);
assert!(h.ctx.text_edit_focused(), "the palette's field has the focus");
let app = h.state_mut();
app.palette = None;
app.run("file.new", json!({})).unwrap();
app.run("slide.new", json!({"layout": "blank"})).unwrap();
assert!(!app.session.tab_has_work(), "an empty slide, which asks for the focus only because it opened");
h.run_steps(4);
assert_eq!(focused(&h), Some(document_id()));
}
#[test]
fn the_focused_slide_takes_arrows_escape_typing_and_tab() {
let mut h = harness();
let left = |h: &Harness<'_, SlideApp>| {
let st = h.state().session.active().unwrap();
deckcraft_engine::cmd::xfrm_of(&st.doc, &st.selection, &st.shapes()[0]).x
};
tab(&mut h);
let x = left(&h);
press(&mut h, Modifiers::NONE, Key::ArrowRight);
assert!(left(&h) > x, "the arrow moves the object, not the focus");
press(&mut h, Modifiers::NONE, Key::Escape);
assert!(selected(&h).is_empty());
assert_eq!(focused(&h), Some(document_id()), "Escape leaves the focus on the slide");
tab(&mut h);
h.event(Event::Text("ab".into()));
h.run_steps(2);
tab(&mut h);
h.event(Event::Text("c".into()));
h.run_steps(2);
let st = h.state().session.active().unwrap();
assert_eq!(st.shapes()[0].text.as_ref().unwrap().text(), "ab\tc");
assert!(st.selection.text.is_some());
press(&mut h, Modifiers::NONE, Key::Escape);
assert!(h.state().session.active().unwrap().selection.text.is_none(), "Escape ends text editing");
assert_eq!(focused(&h), Some(document_id()));
}
#[test]
fn every_view_draws_the_document_and_the_file_tab_takes_its_focus() {
let mut h = harness();
for view in [ViewMode::Outline, ViewMode::Reading, ViewMode::NotesPage, ViewMode::Sorter] {
h.state_mut().ui.view = view;
h.run_steps(3);
assert_eq!(focused(&h), Some(document_id()), "the focus stays in the document window");
}
tab(&mut h);
assert!(focused(&h).is_some_and(|id| id != document_id()), "Tab has no work in the slide sorter");
h.state_mut().ui.view = ViewMode::Normal;
h.state_mut().open_backstage(crate::backstage::Page::Home);
h.run_steps(3);
assert!(h.state().backstage_open());
h.key_press(Key::Escape);
h.run_steps(3);
assert!(!h.state().backstage_open(), "Escape leaves the File tab");
assert_eq!(focused(&h), Some(document_id()), "and the slide has the keyboard again");
}
+4 -5
View File
@@ -123,11 +123,10 @@ fn hex(c: [u8; 4]) -> String {
}
/// The slide canvas while the Eyedropper waits: the pointer is a crosshair with the colour under it
/// beside it, a real click takes it (Enter and Space are egui's fake clicks of the focused canvas). Returns true when it
/// used the pointer (the tools get none).
/// beside it, a click takes it. Returns true when it used the pointer (the tools get none).
pub fn canvas(app: &mut SlideApp, ui: &Ui, resp: &egui::Response, xf: Xf) -> bool {
let Some(state) = app.eyedropper.as_ref() else { return false };
let escape = crate::framework::escape_pressed(ui.ctx());
let escape = ui.input(|i| i.key_pressed(egui::Key::Escape));
if escape || resp.secondary_clicked() {
app.eyedropper = None;
return true;
@@ -136,7 +135,7 @@ pub fn canvas(app: &mut SlideApp, ui: &Ui, resp: &egui::Response, xf: Xf) -> boo
let on_slide = app.slide_rect.is_some_and(|r| r.contains(pos));
if !on_slide {
ui.ctx().set_cursor_icon(CursorIcon::NotAllowed);
if resp.clicked_by(egui::PointerButton::Primary) {
if resp.clicked() {
app.eyedropper = None;
}
return true;
@@ -147,7 +146,7 @@ pub fn canvas(app: &mut SlideApp, ui: &Ui, resp: &egui::Response, xf: Xf) -> boo
if let Some(c) = under {
loupe(ui, pos, c);
}
if resp.clicked_by(egui::PointerButton::Primary) {
if resp.clicked() {
let (pick, slide) = (state.pick, state.slide);
app.eyedropper = None;
match pick {
+2 -15
View File
@@ -15,7 +15,7 @@ fn harness() -> Harness<'static, SlideApp> {
session.execute("slide.new", &json!({"layout": "blank"})).unwrap();
session.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 200, 100]})).unwrap();
session.execute("shape.fill", &json!({"color": "#ff0000"})).unwrap();
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
@@ -59,19 +59,6 @@ fn selection(h: &Harness<'static, SlideApp>) -> Vec<u32> {
h.state().session.doc().unwrap().selection.shapes.iter().map(|s| s.0).collect()
}
#[test]
fn space_on_the_focused_slide_picks_no_colour() {
let mut h = harness();
ask(&mut h);
let on_shape = at(&h, 150.0, 150.0);
h.input_mut().events.push(Event::PointerMoved(on_shape));
h.run_steps(3);
assert!(h.ctx.memory(|m| m.has_focus(crate::framework::document_id())));
h.key_press(egui::Key::Space);
h.run_steps(3);
assert!(h.state().eyedropper.is_some() && !result_waits_for(&h.ctx, menu()));
}
#[test]
fn a_click_on_the_slide_takes_the_colour_under_it_and_nothing_else_happens() {
let mut h = harness();
@@ -138,7 +125,7 @@ fn set_transparent_color_takes_the_colour_clicked_in_the_picture() {
session.execute("insert.picture", &json!({"data": data, "name": "a.png", "rect": [100, 100, 400, 200]})).unwrap();
let mut app = SlideApp::new(session, Services::default());
app.ui.tab = "Picture Format".into();
let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1600.0, 1200.0)).build_ui_state(
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+7 -11
View File
@@ -13,17 +13,13 @@ use serde_json::json;
use crate::{Services, SlideApp, theme};
fn harness(app: SlideApp) -> Harness<'static, SlideApp> {
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
// The app keeps asking for frames, so step instead of run().
h.run_steps(3);
h
+7 -11
View File
@@ -14,17 +14,13 @@ fn ctrl_f_puts_the_caret_in_find_what() {
s.execute("text.exit", &json!({})).unwrap();
s.doc_mut().unwrap().selection.shapes.clear();
let app = SlideApp::new(s, Services::default());
let mut h = Harness::builder()
.with_context_setup(crate::framework::install_headless)
.with_size(egui::vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::F);
h.run_steps(3);
-36
View File
@@ -1,36 +0,0 @@
//! The compiled channel, shared by the About dialog and the window name. The build script sets
//! `cfg(deckcraft_nightly_v1)` and `DECKCRAFT_BUILT_VERSION` from `DECKCRAFT_BUILD_CHANNEL`, the
//! same switch the app crate's build script reads, so both crates agree in one build.
/// The display name: the same string the Launcher and the macOS bundle use.
pub const fn app_name() -> &'static str {
if is_nightly() { "DeckCraft Nightly" } else { "DeckCraft" }
}
pub const fn is_nightly() -> bool {
cfg!(deckcraft_nightly_v1)
}
/// The version the binary was built as: the workspace version for stable, the prepared Nightly
/// feed identity for Nightly (never the bare Cargo version).
pub const fn version() -> &'static str {
env!("DECKCRAFT_BUILT_VERSION")
}
#[cfg(test)]
mod tests {
#[test]
fn nightly_and_stable_names_match_the_build_channel() {
assert_eq!(super::is_nightly(), cfg!(deckcraft_nightly_v1));
assert_eq!(super::app_name(), if cfg!(deckcraft_nightly_v1) { "DeckCraft Nightly" } else { "DeckCraft" });
assert!(super::version().starts_with(env!("CARGO_PKG_VERSION").split('-').next().unwrap_or_default()));
}
#[test]
fn a_nightly_build_never_reports_the_bare_workspace_version() {
if cfg!(deckcraft_nightly_v1) {
assert_ne!(super::version(), env!("CARGO_PKG_VERSION"));
assert!(super::version().contains("-nightly."));
}
}
}
-182
View File
@@ -1,182 +0,0 @@
//! The craft-ui runtime, hosted from DeckCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`SlideApp::before_input`] in `raw_input_hook`, [`SlideApp::close_path`]
//! last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with [`install_headless`].
//! `SlideApp::ui` runs the framework dialogs ([`SlideApp::framework_dialogs`]) after DeckCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of DeckCraft's own egui
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] or [`take_window_cancel`]; the
//! document window is declared to the runtime with [`host_canvas`] each pass that draws it, which keeps the edit chords
//! and the clipboard events, and Tab while it has the focus and Tab has work, in egui's input for DeckCraft's own key
//! routing (`SlideApp::keyboard`). That routing has the keyboard unless [`widget_has_keyboard`].
use std::sync::Arc;
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::{Chord, Key, Mods};
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{self, EditSet, FocusTarget, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::system::WindowSystem;
use crate::SlideApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. DeckCraft's own definitions
/// (`theme::install_fonts_with`, in the first UI pass) replace it before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>) -> Result<(), String> {
let spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id());
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Installs the runtime on the desktop window's context, once, before the first pass. `forced_x11` when the app
/// opens its window through XWayland. DeckCraft draws its own title bar row (`ribbon::title_bar`) and gives the
/// runtime no frame decision, so the runtime takes no part of the window's move area or hit test.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context, forced_x11: bool) -> Result<(), String> {
use craft_host::target::Backend;
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
install_with(ctx, ShellInfo::default().backend(backend), Arc::new(craft_window::system::SystemWindows))
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) {
log::warn!("{error}");
}
}
/// Who DeckCraft is to the framework's dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "deckcraft", name: "DeckCraft", version: env!("CARGO_PKG_VERSION") })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.deckcraft.png"))
.build(),
)
}
impl SlideApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
embed::before_input(ctx, |output| self.frame_input(output));
}
/// The root values of this frame. DeckCraft registers no commands with the runtime and lets it toggle no chrome,
/// so the output carries nothing it acts on. The interface scale is DeckCraft's own (`UiState::ui_scale`, which
/// `ui_setup` applies), so the runtime's zoom and DeckCraft's agree.
fn frame_input(&mut self, _output: FrameOutput) -> FrameInput {
let mode = if self.ui.brightness == crate::theme::Brightness::Dark { craft_theme::Mode::Dark } else { craft_theme::Mode::Light };
// The slide show and the canvas read Ctrl/Cmd+wheel themselves, so a smooth Ctrl+wheel stays a wheel event.
let root = RootEnv::new().mode(mode).scale(Scale::new(self.ui.ui_scale.clamp(0.5, 3.0))).ctrl_wheel_pinch(false);
FrameInput::new(root).host(Arc::clone(&self.framework_host))
}
/// The framework's part of `App::logic`, after DeckCraft's own: the root window's close path. With unsaved
/// presentations the window stays open while the quit dialog asks; its answer closes the window again with
/// `quit_confirmed` set.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || {
if self.quit_confirmed || !self.session.documents().iter().any(|d| d.is_dirty()) {
return CloseDecision::Close;
}
self.show = None;
if self.dialog.as_ref().is_none_or(|d| d.id != "quit") {
self.dialog = Some(crate::dialogs::Dialog::new("quit"));
}
CloseDecision::Hold
});
}
}
/// Alt+1 to Alt+9, the Quick Access Toolbar's positions on Windows and Linux (`menus::ui_shortcut`). Claimed, so
/// the runtime's Alt+numpad code entry leaves them to DeckCraft's shortcuts.
const QUICK_ACCESS_KEYS: [Chord; 9] = [
Chord::new(Mods::ALT, Key::Num1),
Chord::new(Mods::ALT, Key::Num2),
Chord::new(Mods::ALT, Key::Num3),
Chord::new(Mods::ALT, Key::Num4),
Chord::new(Mods::ALT, Key::Num5),
Chord::new(Mods::ALT, Key::Num6),
Chord::new(Mods::ALT, Key::Num7),
Chord::new(Mods::ALT, Key::Num8),
Chord::new(Mods::ALT, Key::Num9),
];
/// The keys DeckCraft's document window keeps while it has the focus or is the window's key target: every clipboard
/// event and edit chord, and the Quick Access Toolbar's Alt+digits, which `SlideApp::keyboard` routes itself.
const DOCUMENT_KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL).with_claims(&QUICK_ACCESS_KEYS);
/// The document window's widget: the slide canvas, the slide sorter or the notes page, whichever the view draws.
pub(crate) fn document_id() -> egui::Id {
egui::Id::unique("deckcraft_document")
}
/// Declares DeckCraft's document window, drawn in this pass, as the window's canvas. With nothing focused it is the
/// window's key target: the edit chords, the clipboard events and the claimed Alt+digits stay in egui's input for
/// DeckCraft. Tab and Shift+Tab stop at it; with `keeps_tab` the focused document keeps them in egui's input, else they
/// move on from it.
pub(crate) fn host_canvas(ctx: &egui::Context, keeps_tab: bool) {
let keys = if keeps_tab { DOCUMENT_KEYS.with_keep(KeepKeys::Tab) } else { DOCUMENT_KEYS };
focus::host_canvas(ctx, document_id(), keys);
}
/// Gives the document window the keyboard focus. It is the runtime's focus, which an Escape does not take away.
pub(crate) fn focus_document(ctx: &egui::Context) {
focus::request(ctx, FocusTarget::Id(document_id()));
}
/// The widget that has the keyboard, the document window left out: a focused document leaves the keyboard to
/// DeckCraft's own key routing, as with nothing focused.
pub(crate) fn focused_widget(ctx: &egui::Context) -> Option<egui::Id> {
ctx.memory(|m| m.focused()).filter(|id| *id != document_id())
}
/// Whether a widget other than the document window has the keyboard.
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
focused_widget(ctx).is_some()
}
/// Whether Escape was pressed in this pass: from egui while one of DeckCraft's own widgets or popups has the keyboard,
/// otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_escape(ctx)
}
/// Whether the window's cancel (an Escape while nothing has framework focus, which the runtime takes out of egui's
/// events) is there and untaken. Key loops that read egui's events add it as an Escape press.
pub(crate) fn window_escape(ctx: &egui::Context) -> bool {
window_cancel(ctx, false)
}
/// The Escape press [`window_escape`] stands for, for key loops over egui's events.
pub(crate) const ESCAPE_PRESS: egui::Event =
egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
/// Takes the window's cancel (an Escape while nothing has framework focus): whether there was one.
pub(crate) fn take_window_cancel(ctx: &egui::Context) -> bool {
window_cancel(ctx, true)
}
fn window_cancel(ctx: &egui::Context, take: bool) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = intents.untaken(&Intent::Cancel);
take && pending && intents.take(Intent::Cancel)
});
pending
}
+1 -1
View File
@@ -13,7 +13,7 @@ fn harness(n: usize) -> egui_kittest::Harness<'static, SlideApp> {
for _ in 1..n {
s.execute("slide.new", &json!({})).unwrap();
}
egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
+20 -22
View File
@@ -11,14 +11,13 @@ use deckcraft_engine::Session;
/// Build the standard 1280×800 UI harness around a supplied session and run three frames.
fn harness(session: Session) -> egui_kittest::Harness<'static, SlideApp> {
let mut h =
egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(session, Services::default()),
);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
SlideApp::new(session, Services::default()),
);
crate::install_ime_pass_hooks(&h.ctx);
// The app keeps requesting repaints, so step frames instead of run().
h.run_steps(3);
@@ -192,20 +191,19 @@ fn a_discarded_pass_keeps_the_tombstone_until_a_settled_pass_publishes_the_inter
use std::sync::{Arc, Mutex};
let traces = Arc::new(Mutex::new(Vec::new()));
let seen = traces.clone();
let mut h =
egui_kittest::Harness::builder().with_context_setup(crate::framework::install_headless).with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
move |ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
seen.lock().unwrap().push((
app.ime_cancelled.is_some(),
app.ime_interrupt_pending,
app.ime_composition.is_none(),
ui.ctx().will_discard(),
));
},
SlideApp::new(Session::with_new(), Services::default()),
);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
move |ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
seen.lock().unwrap().push((
app.ime_cancelled.is_some(),
app.ime_interrupt_pending,
app.ime_composition.is_none(),
ui.ctx().will_discard(),
));
},
SlideApp::new(Session::with_new(), Services::default()),
);
h.run_steps(3);
let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
h.state_mut().run("text.edit", json!({"id": title})).unwrap();

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